diff --git a/README.md b/README.md index 609cd789..86cf74c6 100644 --- a/README.md +++ b/README.md @@ -3,269 +3,28 @@ ## Introduction -### Introduction +Maxio Advanced Billing (formerly Chargify) provides an HTTP-based API that conforms to the principles of REST. +One of the many reasons to use Advanced Billing is the immense feature set and surrounding community [client libraries](page:development-tools/client-libraries). +The Maxio API returns JSON responses as the primary and recommended format, but XML is also provided as a backwards compatible option for Merchants who require it. -#### API Integration +### Steps to make your first Maxio Advanced Billing API call -Maxio Advanced Billing (formerly Chargify API) can be integrated with many environments and programming languages via our REST API. Some of our users have contributed their API wrappers in various programming languages. Check out the [API Code Overview](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI2-api-code-samples) doc for an introduction to the wrappers and available code samples. +1. [Sign-up](https://app.chargify.com/signup/maxio-billing-sandbox) or [log-in](https://app.chargify.com/login.html) to your [test site](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405553861773-Testing-Intro) account. +2. [Setup and configure authentication](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405281550477-API-Keys#api) credentials. +3. Submit your API request and try it out. +4. Verify results through response. +5. Test our integrations. -#### Testing Guide +We strongly suggest exploring the developer portal, our [integrations](https://www.maxio.com/integrations) and the API guide, as well as the entire set of application-based documentation to aid in your discovery of the product. -Maxio Advanced Billing has compiled a [testing guide](https://chargify.zendesk.com/hc/en-us/articles/4407904658587) that covers a list of important factors to consider while in the testing phase. Here's a high-level overiew of what's covered in our testing guide: +#### Example -+ Test credit card basics -+ Test site limits -+ Live mode versus test mode - -We strongly suggest reading over the testing guide, as well as the entire set of application-based documentation to aid in your discovery of the product. - -#### Engage Support - -We always enjoy (and appreciate) hearing about larger integrations ahead of time. If you’re planning on importing a large amount of data into Maxio via our API, we suggest sending a “heads up” to “support@chargify.com” so we can coordinate with you to ensure your import process goes smoothly. - -Our API, while considered stable, is continually being improved and polished. Please feel free to contact support if you experience issues when integrating with the Maxio Advanced Billing API. - -If you have any additional questions regarding our documentation please don't hesitate in reaching out. - -#### Support Access - -Access to our Technical Specialist team for API support is currently limited to purchasers of our larger Maxio support plans. - -But don’t worry! There are quite a few options to help you get the answers you need: - -- [Read our documentation for developers](https://developers.chargify.com/docs/developer-docs/ZG9jOjM0NjA3MQ-overview) -- Explore the endpoints of our API Documentation -- [Watch our videos and tutorials](https://chargify.com/tutorials) -- [Check out the Chargify tag on Stack Overflow](http://stackoverflow.com/questions/tagged/chargify) - -### API Overview - -The Chargify API allows you to interact with our system programmatically from your own application. Using the API you interact with Resources such as: - -- Products -- Subscriptions -- Customers -- etc. - -The API attempts to conform to the [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) design principles. -You interact with the resources exposed via the API by accessing resource collection and element URIs using the HTTP verbs (GET, POST, PUT, and DELETE). -Chargify accepts and returns both JSON and XML data via the API. - -You’ll likely need access to a web developer or programmer (if you’re not one) to get the most use out of the API. - -#### Available Formats: JSON and XML - -JSON is the primary and recommended format for use with the Chargify API. XML is also provided as a backwards compatible option for Merchants who require it. - -#### Authentication - -Authentication is implemented as HTTP Basic Authentication over TLS >= 1.2 (HTTPS), as described in [API Authentication](https://developers.chargify.com/docs/developer-docs/ZG9jOjE1NTUxNQ-authentication) - -#### URL - -The URL for API requests includes the subdomain of the Site you are working with: - -`https://.chargify.com/` - -#### Response Data - -Response data is sent as either XML or JSON, depending on the type of data requested (`HTTP Content-Type` header) or the type specified as being accepted (HTTP `Accept` header). - -GETs for individual statements & invoices may also be requested as PDF using `application/pdf` or appending `.pdf` to the resource URI. - -Response codes are sent via the normal HTTP Response Code, and are documented separately for each resource. - -For boolean fields, please note that a value of `null` may be considered as false. However, this is not true across all cases. Please excercise good judgement here, or contact support with any questions. - -For example: - -+ `null` can define that there's no data available for that attribute - -#### Pagination - -When an endpoint returns a list of items, it will be paginated. Usually, 20 items will be returned by default, and you may request up to a maximum of 200 at a time. Pagination is done with query string parameters, for example: `?page=5&per_page=200` - -#### Response Time Zones - -API responses from Chargify are sent with the timezone of current Chargify site. - -Alternately, webhooks sent from Chargify globally utilize EST as the timezone for all content in the body of the payload. - -#### Request Data - -POST and PUT request data may be formatted as either XML (`application/xml`) or JSON (`application/json`). For best results, you should set your HTTP `Content-Type` request header accordingly, although you may also specify your format by appending `.xml` or `.json` extensions on to the resource URI. - -Note that Chargify does not accept PUT or POST data sent as query params or form encoded data – data must be sent as either XML or JSON. If you fail to set your `Content-Type` to either `application/xml` or `application/json`, your request may fail due to triggering of forgery protection mechanisms. - -##### About Decimal Numbers - -In order to prevent losing precision, we serialize decimal numbers as strings instead of as JSON numbers. - -We recommend parsing these strings into their decimal equivalent using a decimal number library in your programming language (i.e. `BigDecimal` in Ruby) instead of relying on floating point values or arithmetic. - -##### About Amount Fields - -Fields holding amount values are given as a string representing a decimal whole currency amount. - -For example, `"1.23"` in currency `"USD"` would equate to `$1.23`. - -Not all fields will be rounded to the smallest currency denomination. Intermediate results, such as those that derive from line-level tax calculations, may hold precision up to 8 decimal places. However, the top-level totals we provide (e.g. `total_amount`) will be rounded to the smallest currency denomination. - -It is up to API consumers to parse the string into a decimal number representation and do any rounding necessary for your application. - -#### Debugging - -If you’re having difficulty executing a request via our API, try the simplest thing and attempt your request via the curl command-line tool, as shown in the below example. Add the `--verbose` flag to your request to receive even more debugging information. - -Another handy tool is [Beeceptor](https://beeceptor.com/). You can use this to intercept your request to see exactly what is being sent. - -If you are unable to connect at all, check that you are using TLS 1.2 or better. - -If you see a "Could not resolve host" error, double check that the url is correct, including your subdomain. For example: `mysite.chargify.com`. This error means your DNS server could not find an IP address for the domain you are trying to connect to. - -#### Backwards Compatibility - -We consider the following changes to be backwards compatible and may make them without advance notice: - -+ Adding new API endpoints, or adding new attributes in the responses of existing endpoints -+ Adding new optional parameters to be sent to existing API endpoints -+ Adding new fields to exported data -+ Changing the type or length of any of the ID attributes - + For example, most IDs are currently integers, but you should not assume that this will always be the case. - -In addition, you should not depend on the order of attributes within the API response as this may change. - -Chargify does not provide notifications for additions that are clearly defined as backwards compatible. - -#### Examples - -The following examples use the curl command-line tool to execute API requests. - -##### Subscription Listing +The following example uses the curl command-line tool to execute API requests. **Request** curl -u :x -H Accept:application/json -H Content-Type:application/json https://acme.chargify.com/subscriptions.json -### API Access Limitations - -There are a few scenarios that may end up in causing an API request to be blocked even with correct credentials. -**Please note:** All relevant API requests will be blocked if any of the below conditions are true. These limitations also apply to [Chargify Direct](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDE3-introduction). - -Those scenarios are as follows: - -- Your Chargify subscription is canceled. -- Your Chargify trial has reached an end. -- The site you're making a request for is in the process of ["clearing site data"](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405428327309) - - _Note: any API request for another site that is in a good state will NOT be blocked_ -- The site you're making a request for has been deleted. - - _Note: any API request for another site that is in a good state will NOT be blocked_ - -Read more about your Chargify subscription [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405430043149-Advanced-Billing-Subscription#advanced-billing-subscription-0-0) - -#### What happens when an API request is blocked - -The request will fail with a `422` http status code. The response will also include a message explaining the reason for the request being blocked. For example: - -- If your Chargify subscription is canceled: - -```json -{ - "errors" => [ - [0] "Your Chargify account has been canceled. Please contact support@chargify.com to reactivate." - ] -} -``` - -- If your Chargify trial has reached and end and you attempted to make an API request, the response body will look like: - -```json -{ - "errors" => [ - [0] "Your trial has ended, please contact sales." - ] -} -``` - -- If the site you're making a request for is in the process of ["clearing site data"](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405428327309): - -```json -{ - "errors" => [ - [0] "Site data clearing is in progress. Please try later." - ] -} -``` - -- If the site you're making a request for has been deleted: - -```json -{ - "errors" => [ - [0] "This site has been deleted." - ] -} -``` - -### Secure Applications - -Please note that it is NOT possible to make API requests directly from the customer's browser or device. Doing so would expose your API key on the client side, and anyone who has that key has full access to all of your Chargify data. - -Instead you will need to take care to tokenize sensitive information by using [Chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview) or a similar JavaScript library provided by your gateway, and then post the token and other information to your own server, from which you can make the API call to Chargify. - -#### Troubleshooting - -If you attempt to make a Chargify API request directly from the customer's browser, you may see an error such as: - -``` -Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. -``` - -or - -``` -Origin 'https://example.com' is therefore not allowed access.` `The response had HTTP status code 404. -``` - -This is an error message indicating that Cross-Origin Resource Sharing (CORS) is not enabled on the Chargify server. - -### Relationship Invoicing - -#### API Compatibility for Relationship Invoicing - -This section describes the API for the new, [Relationship Invoicing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253) style of invoices introduced in January 2018. - -If you are an existing customer from prior to January 2018 or have not otherwise explicitly opted into this new style of invoices, you are probably looking for the legacy "Invoices" section that describes [invoice-billing legacy-style invoices](./b3A6MTQxMDgzNjQ-read-invoice). - -These new invoices provide a single representation of all of your Chargify billing, whether you collect automatically or via remittance. - -#### About Decimal Numbers - -In order to prevent losing precision, we serialize decimal numbers as strings instead of as JSON numbers. - -We recommend parsing these strings into their decimal equivalent using a decimal number library in your programming language (i.e. `BigDecimal` in Ruby) instead of relying on floating point values or arithmetic. - -#### About Amount Fields - -Fields holding amount values are given as a string representing a decimal whole currency amount. - -For example, `"1.23"` in currency `"USD"` would equate to `$1.23`. - -Not all fields will be rounded to the smallest currency denomination. Intermediate results, such as those that derive from line-level tax calculations, may hold precision up to 8 decimal places. However, the top-level totals we provide (e.g. `total_amount`) will be rounded to the smallest currency denomination. - -It is up to API consumers to parse the string into a decimal number representation and do any rounding necessary for your application. - -##### Relationship Invoicing Summary - -+ If your site **is** using relationship invoicing, you may only use the methods described in this section for working with invoices. - -+ If your site is **not** using relationship invoicing, please use the legacy invoice methods: - - + [Invoices](./b3A6MTQxMTA0MTA-read-invoice) - + [Invoices: Payments](./b3A6MTQxMTA0MTI-create-invoice-payment) - + [Invoices: Charges](./b3A6MTQxMTA0MTM-create-charge) - + [Invoices: Credits](./b3A6MTQxMTA0MTQ-create-invoice-credit) - ### Requirements The SDK requires **Go version 1.18 or above**. @@ -278,11 +37,11 @@ The following section explains how to use the advancedbilling library in a new p To use the package in your application, you can install the package from [pkg.go.dev](https://pkg.go.dev/) using the following command: -```bash -$ go get github.com/maxio-com/ab-golang-sdk@v1.0.1-alpha.1 +```bash +$ go get github.com/maxio-com/ab-golang-sdk@v1.0.0-alpha.1 ``` -You can also view the package at: https://pkg.go.dev/github.com/maxio-com/ab-golang-sdk@v1.0.1-alpha.1 +You can also view the package at: https://pkg.go.dev/github.com/maxio-com/ab-golang-sdk@v1.0.0-alpha.1 ## Initialize the API Client @@ -301,21 +60,21 @@ The following parameters are configurable for the API Client: The API client can be initialized as follows: ```go -client := advancedbilling.NewClient( - advancedbilling.CreateConfiguration( - advancedbilling.WithHttpConfiguration( - advancedbilling.CreateHttpConfiguration( - advancedbilling.WithTimeout(30), - ), - ), - advancedbilling.WithEnvironment(advancedbilling.PRODUCTION), - advancedbilling.WithBasicAuthCredentials( - advancedbilling.NewBasicAuthCredentials( - "BasicAuthUserName", - "BasicAuthPassword", - ), - ), - ), +client := advancedbilling.NewClient( + advancedbilling.CreateConfiguration( + advancedbilling.WithHttpConfiguration( + advancedbilling.CreateHttpConfiguration( + advancedbilling.WithTimeout(30), + ), + ), + advancedbilling.WithEnvironment(advancedbilling.PRODUCTION), + advancedbilling.WithBasicAuthCredentials( + advancedbilling.NewBasicAuthCredentials( + "BasicAuthUserName", + "BasicAuthPassword", + ), + ), + ), ) ``` @@ -332,46 +91,46 @@ The SDK can be configured to use a different environment for making API calls. A ## Authorization -This API uses the following authentication schemes. - +This API uses the following authentication schemes. + * [`BasicAuth (Basic Authentication)`](doc/auth/basic-authentication.md) ## List of APIs -* [API Exports](doc/controllers/api-exports.md) -* [Advance Invoice](doc/controllers/advance-invoice.md) -* [Billing Portal](doc/controllers/billing-portal.md) -* [Custom Fields](doc/controllers/custom-fields.md) -* [Events-Based Billing Segments](doc/controllers/events-based-billing-segments.md) -* [Payment Profiles](doc/controllers/payment-profiles.md) -* [Product Families](doc/controllers/product-families.md) -* [Product Price Points](doc/controllers/product-price-points.md) -* [Proforma Invoices](doc/controllers/proforma-invoices.md) -* [Reason Codes](doc/controllers/reason-codes.md) -* [Referral Codes](doc/controllers/referral-codes.md) -* [Sales Commissions](doc/controllers/sales-commissions.md) -* [Subscription Components](doc/controllers/subscription-components.md) -* [Subscription Groups](doc/controllers/subscription-groups.md) -* [Subscription Group Invoice Account](doc/controllers/subscription-group-invoice-account.md) -* [Subscription Group Status](doc/controllers/subscription-group-status.md) -* [Subscription Invoice Account](doc/controllers/subscription-invoice-account.md) -* [Subscription Notes](doc/controllers/subscription-notes.md) -* [Subscription Products](doc/controllers/subscription-products.md) -* [Subscription Status](doc/controllers/subscription-status.md) -* [Coupons](doc/controllers/coupons.md) -* [Components](doc/controllers/components.md) -* [Customers](doc/controllers/customers.md) -* [Events](doc/controllers/events.md) -* [Insights](doc/controllers/insights.md) -* [Invoices](doc/controllers/invoices.md) -* [Offers](doc/controllers/offers.md) -* [Products](doc/controllers/products.md) -* [Sites](doc/controllers/sites.md) -* [Subscriptions](doc/controllers/subscriptions.md) +* [API Exports](doc/controllers/api-exports.md) +* [Advance Invoice](doc/controllers/advance-invoice.md) +* [Billing Portal](doc/controllers/billing-portal.md) +* [Custom Fields](doc/controllers/custom-fields.md) +* [Events-Based Billing Segments](doc/controllers/events-based-billing-segments.md) +* [Payment Profiles](doc/controllers/payment-profiles.md) +* [Product Families](doc/controllers/product-families.md) +* [Product Price Points](doc/controllers/product-price-points.md) +* [Proforma Invoices](doc/controllers/proforma-invoices.md) +* [Reason Codes](doc/controllers/reason-codes.md) +* [Referral Codes](doc/controllers/referral-codes.md) +* [Sales Commissions](doc/controllers/sales-commissions.md) +* [Subscription Components](doc/controllers/subscription-components.md) +* [Subscription Groups](doc/controllers/subscription-groups.md) +* [Subscription Group Invoice Account](doc/controllers/subscription-group-invoice-account.md) +* [Subscription Group Status](doc/controllers/subscription-group-status.md) +* [Subscription Invoice Account](doc/controllers/subscription-invoice-account.md) +* [Subscription Notes](doc/controllers/subscription-notes.md) +* [Subscription Products](doc/controllers/subscription-products.md) +* [Subscription Status](doc/controllers/subscription-status.md) +* [Coupons](doc/controllers/coupons.md) +* [Components](doc/controllers/components.md) +* [Customers](doc/controllers/customers.md) +* [Events](doc/controllers/events.md) +* [Insights](doc/controllers/insights.md) +* [Invoices](doc/controllers/invoices.md) +* [Offers](doc/controllers/offers.md) +* [Products](doc/controllers/products.md) +* [Sites](doc/controllers/sites.md) +* [Subscriptions](doc/controllers/subscriptions.md) * [Webhooks](doc/controllers/webhooks.md) ## Classes Documentation -* [HttpConfiguration](doc/http-configuration.md) +* [HttpConfiguration](doc/http-configuration.md) * [RetryConfiguration](doc/retry-configuration.md) diff --git a/advance_invoice_controller.go b/advance_invoice_controller.go index 3af54ce4..f52553d0 100644 --- a/advance_invoice_controller.go +++ b/advance_invoice_controller.go @@ -1,124 +1,124 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" ) // AdvanceInvoiceController represents a controller struct. type AdvanceInvoiceController struct { - baseController + baseController } -// NewAdvanceInvoiceController creates a new instance of AdvanceInvoiceController. +// NewAdvanceInvoiceController creates a new instance of AdvanceInvoiceController. // It takes a baseController as a parameter and returns a pointer to the AdvanceInvoiceController. func NewAdvanceInvoiceController(baseController baseController) *AdvanceInvoiceController { - advanceInvoiceController := AdvanceInvoiceController{baseController: baseController} - return &advanceInvoiceController + advanceInvoiceController := AdvanceInvoiceController{baseController: baseController} + return &advanceInvoiceController } -// IssueAdvanceInvoice takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.Invoice data and -// an error if there was an issue with the request or response. -// Generate an invoice in advance for a subscription's next renewal date. [Please see our docs](reference/Chargify-API.v1.yaml/components/schemas/Invoice) for more information on advance invoices, including eligibility on generating one; for the most part, they function like any other invoice, except they are issued early and have special behavior upon being voided. -// A subscription may only have one advance invoice per billing period. Attempting to issue an advance invoice when one already exists will return an error. -// That said, regeneration of the invoice may be forced with the params `force: true`, which will void an advance invoice if one exists and generate a new one. If no advance invoice exists, a new one will be generated. +// IssueAdvanceInvoice takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.Invoice data and +// an error if there was an issue with the request or response. +// Generate an invoice in advance for a subscription's next renewal date. [Please see our docs]($m/Invoice) for more information on advance invoices, including eligibility on generating one; for the most part, they function like any other invoice, except they are issued early and have special behavior upon being voided. +// A subscription may only have one advance invoice per billing period. Attempting to issue an advance invoice when one already exists will return an error. +// That said, regeneration of the invoice may be forced with the params `force: true`, which will void an advance invoice if one exists and generate a new one. If no advance invoice exists, a new one will be generated. // We recommend using either the create or preview endpoints for proforma invoices to preview this advance invoice before using this endpoint to generate it. func (a *AdvanceInvoiceController) IssueAdvanceInvoice( - ctx context.Context, - subscriptionId int, - body *models.IssueAdvanceInvoiceRequest) ( - models.ApiResponse[models.Invoice], - error) { - req := a.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/advance_invoice/issue.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.Invoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.Invoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.IssueAdvanceInvoiceRequest) ( + models.ApiResponse[models.Invoice], + error) { + req := a.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/advance_invoice/issue.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.Invoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.Invoice](decoder) + return models.NewApiResponse(result, resp), err } -// ReadAdvanceInvoice takes context, subscriptionId as parameters and -// returns an models.ApiResponse with models.Invoice data and -// an error if there was an issue with the request or response. +// ReadAdvanceInvoice takes context, subscriptionId as parameters and +// returns an models.ApiResponse with models.Invoice data and +// an error if there was an issue with the request or response. // Once an advance invoice has been generated for a subscription's upcoming renewal, it can be viewed through this endpoint. There can only be one advance invoice per subscription per billing cycle. func (a *AdvanceInvoiceController) ReadAdvanceInvoice( - ctx context.Context, - subscriptionId int) ( - models.ApiResponse[models.Invoice], - error) { - req := a.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v/advance_invoice.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - - var result models.Invoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.Invoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int) ( + models.ApiResponse[models.Invoice], + error) { + req := a.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v/advance_invoice.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + + var result models.Invoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.Invoice](decoder) + return models.NewApiResponse(result, resp), err } -// VoidAdvanceInvoice takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.Invoice data and -// an error if there was an issue with the request or response. -// Void a subscription's existing advance invoice. Once voided, it can later be regenerated if desired. -// A `reason` is required in order to void, and the invoice must have an open status. Voiding will cause any prepayments and credits that were applied to the invoice to be returned to the subscription. For a full overview of the impact of voiding, please [see our help docs](reference/Chargify-API.v1.yaml/components/schemas/Invoice). +// VoidAdvanceInvoice takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.Invoice data and +// an error if there was an issue with the request or response. +// Void a subscription's existing advance invoice. Once voided, it can later be regenerated if desired. +// A `reason` is required in order to void, and the invoice must have an open status. Voiding will cause any prepayments and credits that were applied to the invoice to be returned to the subscription. For a full overview of the impact of voiding, please [see our help docs]($m/Invoice). func (a *AdvanceInvoiceController) VoidAdvanceInvoice( - ctx context.Context, - subscriptionId int, - body *models.VoidInvoiceRequest) ( - models.ApiResponse[models.Invoice], - error) { - req := a.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/advance_invoice/void.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.Invoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.Invoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.VoidInvoiceRequest) ( + models.ApiResponse[models.Invoice], + error) { + req := a.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/advance_invoice/void.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.Invoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.Invoice](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/api_exports_controller.go b/api_exports_controller.go index d8fc1f08..86f1221f 100644 --- a/api_exports_controller.go +++ b/api_exports_controller.go @@ -1,292 +1,325 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" ) // APIExportsController represents a controller struct. type APIExportsController struct { - baseController + baseController } -// NewAPIExportsController creates a new instance of APIExportsController. +// NewAPIExportsController creates a new instance of APIExportsController. // It takes a baseController as a parameter and returns a pointer to the APIExportsController. func NewAPIExportsController(baseController baseController) *APIExportsController { - APIExportsController := APIExportsController{baseController: baseController} - return &APIExportsController + APIExportsController := APIExportsController{baseController: baseController} + return &APIExportsController } -// ListExportedProformaInvoices takes context, batchId, perPage, page as parameters and -// returns an models.ApiResponse with []models.ProformaInvoice data and -// an error if there was an issue with the request or response. -// This API returns an array of exported proforma invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. +// ListExportedProformaInvoicesInput represents the input of the ListExportedProformaInvoices endpoint. +type ListExportedProformaInvoicesInput struct { + // Id of a Batch Job. + BatchId string + // This parameter indicates how many records to fetch in each request. + // Default value is 100. + // The maximum allowed values is 10000; any per_page value over 10000 will be changed to 10000. + PerPage *int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int +} + +// ListExportedProformaInvoices takes context, batchId, perPage, page as parameters and +// returns an models.ApiResponse with []models.ProformaInvoice data and +// an error if there was an issue with the request or response. +// This API returns an array of exported proforma invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. // Example: `GET https://{subdomain}.chargify.com/api_exports/proforma_invoices/123/rows?per_page=10000&page=1`. func (a *APIExportsController) ListExportedProformaInvoices( - ctx context.Context, - batchId string, - perPage *int, - page *int) ( - models.ApiResponse[[]models.ProformaInvoice], - error) { - req := a.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/api_exports/proforma_invoices/%v/rows.json", batchId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if page != nil { - req.QueryParam("page", *page) - } - - var result []models.ProformaInvoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.ProformaInvoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListExportedProformaInvoicesInput) ( + models.ApiResponse[[]models.ProformaInvoice], + error) { + req := a.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/api_exports/proforma_invoices/%v/rows.json", input.BatchId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + + var result []models.ProformaInvoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.ProformaInvoice](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListExportedInvoicesInput represents the input of the ListExportedInvoices endpoint. +type ListExportedInvoicesInput struct { + // Id of a Batch Job. + BatchId string + // This parameter indicates how many records to fetch in each request. + // Default value is 100. + // The maximum allowed values is 10000; any per_page value over 10000 will be changed to 10000. + PerPage *int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int } -// ListExportedInvoices takes context, batchId, perPage, page as parameters and -// returns an models.ApiResponse with []models.Invoice data and -// an error if there was an issue with the request or response. -// This API returns an array of exported invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. +// ListExportedInvoices takes context, batchId, perPage, page as parameters and +// returns an models.ApiResponse with []models.Invoice data and +// an error if there was an issue with the request or response. +// This API returns an array of exported invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. // Example: `GET https://{subdomain}.chargify.com/api_exports/invoices/123/rows?per_page=10000&page=1`. func (a *APIExportsController) ListExportedInvoices( - ctx context.Context, - batchId string, - perPage *int, - page *int) ( - models.ApiResponse[[]models.Invoice], - error) { - req := a.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/api_exports/invoices/%v/rows.json", batchId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if page != nil { - req.QueryParam("page", *page) - } - - var result []models.Invoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.Invoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListExportedInvoicesInput) ( + models.ApiResponse[[]models.Invoice], + error) { + req := a.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/api_exports/invoices/%v/rows.json", input.BatchId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + + var result []models.Invoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.Invoice](decoder) + return models.NewApiResponse(result, resp), err } -// ListExportedSubscriptions takes context, batchId, perPage, page as parameters and -// returns an models.ApiResponse with []models.Subscription data and -// an error if there was an issue with the request or response. -// This API returns an array of exported subscriptions for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. +// ListExportedSubscriptionsInput represents the input of the ListExportedSubscriptions endpoint. +type ListExportedSubscriptionsInput struct { + // Id of a Batch Job. + BatchId string + // This parameter indicates how many records to fetch in each request. + // Default value is 100. + // The maximum allowed values is 10000; any per_page value over 10000 will be changed to 10000. + PerPage *int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int +} + +// ListExportedSubscriptions takes context, batchId, perPage, page as parameters and +// returns an models.ApiResponse with []models.Subscription data and +// an error if there was an issue with the request or response. +// This API returns an array of exported subscriptions for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. // Example: `GET https://{subdomain}.chargify.com/api_exports/subscriptions/123/rows?per_page=200&page=1`. func (a *APIExportsController) ListExportedSubscriptions( - ctx context.Context, - batchId string, - perPage *int, - page *int) ( - models.ApiResponse[[]models.Subscription], - error) { - req := a.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/api_exports/subscriptions/%v/rows.json", batchId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if page != nil { - req.QueryParam("page", *page) - } - - var result []models.Subscription - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.Subscription](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListExportedSubscriptionsInput) ( + models.ApiResponse[[]models.Subscription], + error) { + req := a.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/api_exports/subscriptions/%v/rows.json", input.BatchId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + + var result []models.Subscription + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.Subscription](decoder) + return models.NewApiResponse(result, resp), err } -// ExportProformaInvoices takes context as parameters and -// returns an models.ApiResponse with models.BatchJobResponse data and -// an error if there was an issue with the request or response. -// This API creates a proforma invoices export and returns a batchjob object. +// ExportProformaInvoices takes context as parameters and +// returns an models.ApiResponse with models.BatchJobResponse data and +// an error if there was an issue with the request or response. +// This API creates a proforma invoices export and returns a batchjob object. // It is only available for Relationship Invoicing architecture. func (a *APIExportsController) ExportProformaInvoices(ctx context.Context) ( - models.ApiResponse[models.BatchJobResponse], - error) { - req := a.prepareRequest(ctx, "POST", "/api_exports/proforma_invoices.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "409": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, - }) - var result models.BatchJobResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) - return models.NewApiResponse(result, resp), err + models.ApiResponse[models.BatchJobResponse], + error) { + req := a.prepareRequest(ctx, "POST", "/api_exports/proforma_invoices.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "409": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, + }) + var result models.BatchJobResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ExportInvoices takes context as parameters and -// returns an models.ApiResponse with models.BatchJobResponse data and -// an error if there was an issue with the request or response. +// ExportInvoices takes context as parameters and +// returns an models.ApiResponse with models.BatchJobResponse data and +// an error if there was an issue with the request or response. // This API creates an invoices export and returns a batchjob object. func (a *APIExportsController) ExportInvoices(ctx context.Context) ( - models.ApiResponse[models.BatchJobResponse], - error) { - req := a.prepareRequest(ctx, "POST", "/api_exports/invoices.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "409": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, - }) - var result models.BatchJobResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) - return models.NewApiResponse(result, resp), err + models.ApiResponse[models.BatchJobResponse], + error) { + req := a.prepareRequest(ctx, "POST", "/api_exports/invoices.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "409": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, + }) + var result models.BatchJobResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ExportSubscriptions takes context as parameters and -// returns an models.ApiResponse with models.BatchJobResponse data and -// an error if there was an issue with the request or response. +// ExportSubscriptions takes context as parameters and +// returns an models.ApiResponse with models.BatchJobResponse data and +// an error if there was an issue with the request or response. // This API creates a subscriptions export and returns a batchjob object. func (a *APIExportsController) ExportSubscriptions(ctx context.Context) ( - models.ApiResponse[models.BatchJobResponse], - error) { - req := a.prepareRequest(ctx, "POST", "/api_exports/subscriptions.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "409": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, - }) - var result models.BatchJobResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) - return models.NewApiResponse(result, resp), err + models.ApiResponse[models.BatchJobResponse], + error) { + req := a.prepareRequest(ctx, "POST", "/api_exports/subscriptions.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "409": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, + }) + var result models.BatchJobResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadProformaInvoicesExport takes context, batchId as parameters and -// returns an models.ApiResponse with models.BatchJobResponse data and -// an error if there was an issue with the request or response. +// ReadProformaInvoicesExport takes context, batchId as parameters and +// returns an models.ApiResponse with models.BatchJobResponse data and +// an error if there was an issue with the request or response. // This API returns a batchjob object for proforma invoices export. func (a *APIExportsController) ReadProformaInvoicesExport( - ctx context.Context, - batchId string) ( - models.ApiResponse[models.BatchJobResponse], - error) { - req := a.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/api_exports/proforma_invoices/%v.json", batchId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - - var result models.BatchJobResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + batchId string) ( + models.ApiResponse[models.BatchJobResponse], + error) { + req := a.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/api_exports/proforma_invoices/%v.json", batchId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + + var result models.BatchJobResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadInvoicesExport takes context, batchId as parameters and -// returns an models.ApiResponse with models.BatchJobResponse data and -// an error if there was an issue with the request or response. +// ReadInvoicesExport takes context, batchId as parameters and +// returns an models.ApiResponse with models.BatchJobResponse data and +// an error if there was an issue with the request or response. // This API returns a batchjob object for invoices export. func (a *APIExportsController) ReadInvoicesExport( - ctx context.Context, - batchId string) ( - models.ApiResponse[models.BatchJobResponse], - error) { - req := a.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/api_exports/invoices/%v.json", batchId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - - var result models.BatchJobResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + batchId string) ( + models.ApiResponse[models.BatchJobResponse], + error) { + req := a.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/api_exports/invoices/%v.json", batchId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + + var result models.BatchJobResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadSubscriptionsExport takes context, batchId as parameters and -// returns an models.ApiResponse with models.BatchJobResponse data and -// an error if there was an issue with the request or response. +// ReadSubscriptionsExport takes context, batchId as parameters and +// returns an models.ApiResponse with models.BatchJobResponse data and +// an error if there was an issue with the request or response. // This API returns a batchjob object for subscriptions export. func (a *APIExportsController) ReadSubscriptionsExport( - ctx context.Context, - batchId string) ( - models.ApiResponse[models.BatchJobResponse], - error) { - req := a.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/api_exports/subscriptions/%v.json", batchId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - - var result models.BatchJobResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + batchId string) ( + models.ApiResponse[models.BatchJobResponse], + error) { + req := a.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/api_exports/subscriptions/%v.json", batchId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + + var result models.BatchJobResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.BatchJobResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/client.go b/client.go index 1b990032..18301df3 100644 --- a/client.go +++ b/client.go @@ -1,341 +1,342 @@ -/* -Package advancedbilling - -This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). */ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "net/http" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "net/http" ) // Client is an interface representing the main client for accessing configuration and controllers. type ClientInterface interface { - Configuration() Configuration - CloneWithConfiguration(options ...ConfigurationOptions) ClientInterface - APIExportsController() *APIExportsController - AdvanceInvoiceController() *AdvanceInvoiceController - BillingPortalController() *BillingPortalController - CouponsController() *CouponsController - ComponentsController() *ComponentsController - CustomersController() *CustomersController - CustomFieldsController() *CustomFieldsController - EventsController() *EventsController - EventsBasedBillingSegmentsController() *EventsBasedBillingSegmentsController - InsightsController() *InsightsController - InvoicesController() *InvoicesController - OffersController() *OffersController - PaymentProfilesController() *PaymentProfilesController - ProductFamiliesController() *ProductFamiliesController - ProductsController() *ProductsController - ProductPricePointsController() *ProductPricePointsController - ProformaInvoicesController() *ProformaInvoicesController - ReasonCodesController() *ReasonCodesController - ReferralCodesController() *ReferralCodesController - SalesCommissionsController() *SalesCommissionsController - SitesController() *SitesController - SubscriptionsController() *SubscriptionsController - SubscriptionComponentsController() *SubscriptionComponentsController - SubscriptionGroupsController() *SubscriptionGroupsController - SubscriptionGroupInvoiceAccountController() *SubscriptionGroupInvoiceAccountController - SubscriptionGroupStatusController() *SubscriptionGroupStatusController - SubscriptionInvoiceAccountController() *SubscriptionInvoiceAccountController - SubscriptionNotesController() *SubscriptionNotesController - SubscriptionProductsController() *SubscriptionProductsController - SubscriptionStatusController() *SubscriptionStatusController - WebhooksController() *WebhooksController - UserAgent() *string + Configuration() Configuration + CloneWithConfiguration(options ...ConfigurationOptions) ClientInterface + APIExportsController() *APIExportsController + AdvanceInvoiceController() *AdvanceInvoiceController + BillingPortalController() *BillingPortalController + CouponsController() *CouponsController + ComponentsController() *ComponentsController + CustomersController() *CustomersController + CustomFieldsController() *CustomFieldsController + EventsController() *EventsController + EventsBasedBillingSegmentsController() *EventsBasedBillingSegmentsController + InsightsController() *InsightsController + InvoicesController() *InvoicesController + OffersController() *OffersController + PaymentProfilesController() *PaymentProfilesController + ProductFamiliesController() *ProductFamiliesController + ProductsController() *ProductsController + ProductPricePointsController() *ProductPricePointsController + ProformaInvoicesController() *ProformaInvoicesController + ReasonCodesController() *ReasonCodesController + ReferralCodesController() *ReferralCodesController + SalesCommissionsController() *SalesCommissionsController + SitesController() *SitesController + SubscriptionsController() *SubscriptionsController + SubscriptionComponentsController() *SubscriptionComponentsController + SubscriptionGroupsController() *SubscriptionGroupsController + SubscriptionGroupInvoiceAccountController() *SubscriptionGroupInvoiceAccountController + SubscriptionGroupStatusController() *SubscriptionGroupStatusController + SubscriptionInvoiceAccountController() *SubscriptionInvoiceAccountController + SubscriptionNotesController() *SubscriptionNotesController + SubscriptionProductsController() *SubscriptionProductsController + SubscriptionStatusController() *SubscriptionStatusController + WebhooksController() *WebhooksController + UserAgent() *string } // client is an implementation of the Client interface. type client struct { - callBuilderFactory https.CallBuilderFactory - configuration Configuration - userAgent string - apiExportsController APIExportsController - advanceInvoiceController AdvanceInvoiceController - billingPortalController BillingPortalController - couponsController CouponsController - componentsController ComponentsController - customersController CustomersController - customFieldsController CustomFieldsController - eventsController EventsController - eventsBasedBillingSegmentsController EventsBasedBillingSegmentsController - insightsController InsightsController - invoicesController InvoicesController - offersController OffersController - paymentProfilesController PaymentProfilesController - productFamiliesController ProductFamiliesController - productsController ProductsController - productPricePointsController ProductPricePointsController - proformaInvoicesController ProformaInvoicesController - reasonCodesController ReasonCodesController - referralCodesController ReferralCodesController - salesCommissionsController SalesCommissionsController - sitesController SitesController - subscriptionsController SubscriptionsController - subscriptionComponentsController SubscriptionComponentsController - subscriptionGroupsController SubscriptionGroupsController - subscriptionGroupInvoiceAccountController SubscriptionGroupInvoiceAccountController - subscriptionGroupStatusController SubscriptionGroupStatusController - subscriptionInvoiceAccountController SubscriptionInvoiceAccountController - subscriptionNotesController SubscriptionNotesController - subscriptionProductsController SubscriptionProductsController - subscriptionStatusController SubscriptionStatusController - webhooksController WebhooksController -} - -// NewClient is the constructor for creating a new client instance. + callBuilderFactory https.CallBuilderFactory + configuration Configuration + userAgent string + apiExportsController APIExportsController + advanceInvoiceController AdvanceInvoiceController + billingPortalController BillingPortalController + couponsController CouponsController + componentsController ComponentsController + customersController CustomersController + customFieldsController CustomFieldsController + eventsController EventsController + eventsBasedBillingSegmentsController EventsBasedBillingSegmentsController + insightsController InsightsController + invoicesController InvoicesController + offersController OffersController + paymentProfilesController PaymentProfilesController + productFamiliesController ProductFamiliesController + productsController ProductsController + productPricePointsController ProductPricePointsController + proformaInvoicesController ProformaInvoicesController + reasonCodesController ReasonCodesController + referralCodesController ReferralCodesController + salesCommissionsController SalesCommissionsController + sitesController SitesController + subscriptionsController SubscriptionsController + subscriptionComponentsController SubscriptionComponentsController + subscriptionGroupsController SubscriptionGroupsController + subscriptionGroupInvoiceAccountController SubscriptionGroupInvoiceAccountController + subscriptionGroupStatusController SubscriptionGroupStatusController + subscriptionInvoiceAccountController SubscriptionInvoiceAccountController + subscriptionNotesController SubscriptionNotesController + subscriptionProductsController SubscriptionProductsController + subscriptionStatusController SubscriptionStatusController + webhooksController WebhooksController +} + +// NewClient is the constructor for creating a new client instance. // It takes a Configuration object as a parameter and returns the Client interface. func NewClient(configuration Configuration) ClientInterface { - client := &client{ - configuration: configuration, - } - - client.userAgent = utilities.UpdateUserAgent("AB SDK Go:v1.0.1-alpha.1 on OS {os-info}") - client.callBuilderFactory = callBuilderHandler( - func(server string) string { - if server == "" { - server = "default" - } - return getBaseUri(Server(server), client.configuration) - }, - createAuthenticationFromConfig(configuration), - https.NewHttpClient(configuration.HttpConfiguration()), - configuration.httpConfiguration.RetryConfiguration(), - withUserAgent(client.userAgent), - withGlobalErrors(), - ) - - baseController := NewBaseController(client) - client.apiExportsController = *NewAPIExportsController(*baseController) - client.advanceInvoiceController = *NewAdvanceInvoiceController(*baseController) - client.billingPortalController = *NewBillingPortalController(*baseController) - client.couponsController = *NewCouponsController(*baseController) - client.componentsController = *NewComponentsController(*baseController) - client.customersController = *NewCustomersController(*baseController) - client.customFieldsController = *NewCustomFieldsController(*baseController) - client.eventsController = *NewEventsController(*baseController) - client.eventsBasedBillingSegmentsController = *NewEventsBasedBillingSegmentsController(*baseController) - client.insightsController = *NewInsightsController(*baseController) - client.invoicesController = *NewInvoicesController(*baseController) - client.offersController = *NewOffersController(*baseController) - client.paymentProfilesController = *NewPaymentProfilesController(*baseController) - client.productFamiliesController = *NewProductFamiliesController(*baseController) - client.productsController = *NewProductsController(*baseController) - client.productPricePointsController = *NewProductPricePointsController(*baseController) - client.proformaInvoicesController = *NewProformaInvoicesController(*baseController) - client.reasonCodesController = *NewReasonCodesController(*baseController) - client.referralCodesController = *NewReferralCodesController(*baseController) - client.salesCommissionsController = *NewSalesCommissionsController(*baseController) - client.sitesController = *NewSitesController(*baseController) - client.subscriptionsController = *NewSubscriptionsController(*baseController) - client.subscriptionComponentsController = *NewSubscriptionComponentsController(*baseController) - client.subscriptionGroupsController = *NewSubscriptionGroupsController(*baseController) - client.subscriptionGroupInvoiceAccountController = *NewSubscriptionGroupInvoiceAccountController(*baseController) - client.subscriptionGroupStatusController = *NewSubscriptionGroupStatusController(*baseController) - client.subscriptionInvoiceAccountController = *NewSubscriptionInvoiceAccountController(*baseController) - client.subscriptionNotesController = *NewSubscriptionNotesController(*baseController) - client.subscriptionProductsController = *NewSubscriptionProductsController(*baseController) - client.subscriptionStatusController = *NewSubscriptionStatusController(*baseController) - client.webhooksController = *NewWebhooksController(*baseController) - return client + client := &client{ + configuration: configuration, + } + + client.userAgent = utilities.UpdateUserAgent("AB SDK Go:1.0.0-alpha.1 on OS {os-info}") + client.callBuilderFactory = callBuilderHandler( + func(server string) string { + if server == "" { + server = "default" + } + return getBaseUri(Server(server), client.configuration) + }, + createAuthenticationFromConfig(configuration), + https.NewHttpClient(configuration.HttpConfiguration()), + configuration.httpConfiguration.RetryConfiguration(), + https.Csv, + withUserAgent(client.userAgent), + withGlobalErrors(), + ) + + baseController := NewBaseController(client) + client.apiExportsController = *NewAPIExportsController(*baseController) + client.advanceInvoiceController = *NewAdvanceInvoiceController(*baseController) + client.billingPortalController = *NewBillingPortalController(*baseController) + client.couponsController = *NewCouponsController(*baseController) + client.componentsController = *NewComponentsController(*baseController) + client.customersController = *NewCustomersController(*baseController) + client.customFieldsController = *NewCustomFieldsController(*baseController) + client.eventsController = *NewEventsController(*baseController) + client.eventsBasedBillingSegmentsController = *NewEventsBasedBillingSegmentsController(*baseController) + client.insightsController = *NewInsightsController(*baseController) + client.invoicesController = *NewInvoicesController(*baseController) + client.offersController = *NewOffersController(*baseController) + client.paymentProfilesController = *NewPaymentProfilesController(*baseController) + client.productFamiliesController = *NewProductFamiliesController(*baseController) + client.productsController = *NewProductsController(*baseController) + client.productPricePointsController = *NewProductPricePointsController(*baseController) + client.proformaInvoicesController = *NewProformaInvoicesController(*baseController) + client.reasonCodesController = *NewReasonCodesController(*baseController) + client.referralCodesController = *NewReferralCodesController(*baseController) + client.salesCommissionsController = *NewSalesCommissionsController(*baseController) + client.sitesController = *NewSitesController(*baseController) + client.subscriptionsController = *NewSubscriptionsController(*baseController) + client.subscriptionComponentsController = *NewSubscriptionComponentsController(*baseController) + client.subscriptionGroupsController = *NewSubscriptionGroupsController(*baseController) + client.subscriptionGroupInvoiceAccountController = *NewSubscriptionGroupInvoiceAccountController(*baseController) + client.subscriptionGroupStatusController = *NewSubscriptionGroupStatusController(*baseController) + client.subscriptionInvoiceAccountController = *NewSubscriptionInvoiceAccountController(*baseController) + client.subscriptionNotesController = *NewSubscriptionNotesController(*baseController) + client.subscriptionProductsController = *NewSubscriptionProductsController(*baseController) + client.subscriptionStatusController = *NewSubscriptionStatusController(*baseController) + client.webhooksController = *NewWebhooksController(*baseController) + return client } // Configuration returns the configuration instance of the client. func (c *client) Configuration() Configuration { - return c.configuration + return c.configuration } // CloneWithConfiguration returns a new copy with the provided options of the configuration instance of the client. func (c *client) CloneWithConfiguration(options ...ConfigurationOptions) ClientInterface { - return NewClient(c.configuration.cloneWithOptions(options...)) + return NewClient(c.configuration.cloneWithOptions(options...)) } // APIExportsController returns the apiExportsController instance of the client. func (c *client) APIExportsController() *APIExportsController { - return &c.apiExportsController + return &c.apiExportsController } // AdvanceInvoiceController returns the advanceInvoiceController instance of the client. func (c *client) AdvanceInvoiceController() *AdvanceInvoiceController { - return &c.advanceInvoiceController + return &c.advanceInvoiceController } // BillingPortalController returns the billingPortalController instance of the client. func (c *client) BillingPortalController() *BillingPortalController { - return &c.billingPortalController + return &c.billingPortalController } // CouponsController returns the couponsController instance of the client. func (c *client) CouponsController() *CouponsController { - return &c.couponsController + return &c.couponsController } // ComponentsController returns the componentsController instance of the client. func (c *client) ComponentsController() *ComponentsController { - return &c.componentsController + return &c.componentsController } // CustomersController returns the customersController instance of the client. func (c *client) CustomersController() *CustomersController { - return &c.customersController + return &c.customersController } // CustomFieldsController returns the customFieldsController instance of the client. func (c *client) CustomFieldsController() *CustomFieldsController { - return &c.customFieldsController + return &c.customFieldsController } // EventsController returns the eventsController instance of the client. func (c *client) EventsController() *EventsController { - return &c.eventsController + return &c.eventsController } // EventsBasedBillingSegmentsController returns the eventsBasedBillingSegmentsController instance of the client. func (c *client) EventsBasedBillingSegmentsController() *EventsBasedBillingSegmentsController { - return &c.eventsBasedBillingSegmentsController + return &c.eventsBasedBillingSegmentsController } // InsightsController returns the insightsController instance of the client. func (c *client) InsightsController() *InsightsController { - return &c.insightsController + return &c.insightsController } // InvoicesController returns the invoicesController instance of the client. func (c *client) InvoicesController() *InvoicesController { - return &c.invoicesController + return &c.invoicesController } // OffersController returns the offersController instance of the client. func (c *client) OffersController() *OffersController { - return &c.offersController + return &c.offersController } // PaymentProfilesController returns the paymentProfilesController instance of the client. func (c *client) PaymentProfilesController() *PaymentProfilesController { - return &c.paymentProfilesController + return &c.paymentProfilesController } // ProductFamiliesController returns the productFamiliesController instance of the client. func (c *client) ProductFamiliesController() *ProductFamiliesController { - return &c.productFamiliesController + return &c.productFamiliesController } // ProductsController returns the productsController instance of the client. func (c *client) ProductsController() *ProductsController { - return &c.productsController + return &c.productsController } // ProductPricePointsController returns the productPricePointsController instance of the client. func (c *client) ProductPricePointsController() *ProductPricePointsController { - return &c.productPricePointsController + return &c.productPricePointsController } // ProformaInvoicesController returns the proformaInvoicesController instance of the client. func (c *client) ProformaInvoicesController() *ProformaInvoicesController { - return &c.proformaInvoicesController + return &c.proformaInvoicesController } // ReasonCodesController returns the reasonCodesController instance of the client. func (c *client) ReasonCodesController() *ReasonCodesController { - return &c.reasonCodesController + return &c.reasonCodesController } // ReferralCodesController returns the referralCodesController instance of the client. func (c *client) ReferralCodesController() *ReferralCodesController { - return &c.referralCodesController + return &c.referralCodesController } // SalesCommissionsController returns the salesCommissionsController instance of the client. func (c *client) SalesCommissionsController() *SalesCommissionsController { - return &c.salesCommissionsController + return &c.salesCommissionsController } // SitesController returns the sitesController instance of the client. func (c *client) SitesController() *SitesController { - return &c.sitesController + return &c.sitesController } // SubscriptionsController returns the subscriptionsController instance of the client. func (c *client) SubscriptionsController() *SubscriptionsController { - return &c.subscriptionsController + return &c.subscriptionsController } // SubscriptionComponentsController returns the subscriptionComponentsController instance of the client. func (c *client) SubscriptionComponentsController() *SubscriptionComponentsController { - return &c.subscriptionComponentsController + return &c.subscriptionComponentsController } // SubscriptionGroupsController returns the subscriptionGroupsController instance of the client. func (c *client) SubscriptionGroupsController() *SubscriptionGroupsController { - return &c.subscriptionGroupsController + return &c.subscriptionGroupsController } // SubscriptionGroupInvoiceAccountController returns the subscriptionGroupInvoiceAccountController instance of the client. func (c *client) SubscriptionGroupInvoiceAccountController() *SubscriptionGroupInvoiceAccountController { - return &c.subscriptionGroupInvoiceAccountController + return &c.subscriptionGroupInvoiceAccountController } // SubscriptionGroupStatusController returns the subscriptionGroupStatusController instance of the client. func (c *client) SubscriptionGroupStatusController() *SubscriptionGroupStatusController { - return &c.subscriptionGroupStatusController + return &c.subscriptionGroupStatusController } // SubscriptionInvoiceAccountController returns the subscriptionInvoiceAccountController instance of the client. func (c *client) SubscriptionInvoiceAccountController() *SubscriptionInvoiceAccountController { - return &c.subscriptionInvoiceAccountController + return &c.subscriptionInvoiceAccountController } // SubscriptionNotesController returns the subscriptionNotesController instance of the client. func (c *client) SubscriptionNotesController() *SubscriptionNotesController { - return &c.subscriptionNotesController + return &c.subscriptionNotesController } // SubscriptionProductsController returns the subscriptionProductsController instance of the client. func (c *client) SubscriptionProductsController() *SubscriptionProductsController { - return &c.subscriptionProductsController + return &c.subscriptionProductsController } // SubscriptionStatusController returns the subscriptionStatusController instance of the client. func (c *client) SubscriptionStatusController() *SubscriptionStatusController { - return &c.subscriptionStatusController + return &c.subscriptionStatusController } // WebhooksController returns the webhooksController instance of the client. func (c *client) WebhooksController() *WebhooksController { - return &c.webhooksController + return &c.webhooksController } // UserAgent returns the userAgent instance of the client. func (c *client) UserAgent() *string { - return &c.userAgent + return &c.userAgent } // GetCallBuilder returns the CallBuilderFactory used by the client. func (c *client) GetCallBuilder() https.CallBuilderFactory { - return c.callBuilderFactory + return c.callBuilderFactory } // getBaseUri returns the base URI based on the server and configuration. func getBaseUri( - server Server, - configuration Configuration) string { - if configuration.Environment() == Environment(PRODUCTION) { - if server == Server(ENUMDEFAULT) { - return fmt.Sprintf("https://%v.%v", configuration.Subdomain(), configuration.Domain()) - } - } - if configuration.Environment() == Environment(ENVIRONMENT2) { - if server == Server(ENUMDEFAULT) { - return "https://events.chargify.com" - } - } - return "TODO: Select a valid server." + server Server, + configuration Configuration) string { + if configuration.Environment() == Environment(PRODUCTION) { + if server == Server(ENUMDEFAULT) { + return fmt.Sprintf("https://%v.%v", configuration.Subdomain(), configuration.Domain()) + } + } + if configuration.Environment() == Environment(ENVIRONMENT2) { + if server == Server(ENUMDEFAULT) { + return "https://events.chargify.com" + } + } + return "TODO: Select a valid server." } // clientOptions is a function type representing options for the client. @@ -343,45 +344,46 @@ type clientOptions func(cb https.CallBuilder) // callBuilderHandler creates the call builder factory with various options. func callBuilderHandler( - baseUrlProvider func(server string) string, - auth map[string]https.AuthInterface, - httpClient https.HttpClient, - retryConfig RetryConfiguration, - opts ...clientOptions) https.CallBuilderFactory { - callBuilderFactory := https.CreateCallBuilderFactory(baseUrlProvider, auth, httpClient, retryConfig) - return tap(callBuilderFactory, opts...) + baseUrlProvider func(server string) string, + auth map[string]https.AuthInterface, + httpClient https.HttpClient, + retryConfig RetryConfiguration, + arraySerializationOption https.ArraySerializationOption, + opts ...clientOptions) https.CallBuilderFactory { + callBuilderFactory := https.CreateCallBuilderFactory(baseUrlProvider, auth, httpClient, retryConfig, arraySerializationOption) + return tap(callBuilderFactory, opts...) } // tap is a utility function to apply client options to the call builder factory. func tap( - callBuilderFactory https.CallBuilderFactory, - opts ...clientOptions) https.CallBuilderFactory { - return func(ctx context.Context, httpMethod, path string) https.CallBuilder { - callBuilder := callBuilderFactory(ctx, httpMethod, path) - for _, opt := range opts { - opt(callBuilder) - } - return callBuilder - } + callBuilderFactory https.CallBuilderFactory, + opts ...clientOptions) https.CallBuilderFactory { + return func(ctx context.Context, httpMethod, path string) https.CallBuilder { + callBuilder := callBuilderFactory(ctx, httpMethod, path) + for _, opt := range opts { + opt(callBuilder) + } + return callBuilder + } } // withUserAgent is an option to add a user agent header to the HTTP request. func withUserAgent(userAgent string) clientOptions { - f := func(request *http.Request) *http.Request { - request.Header.Set("user-agent", userAgent) - return request - } - return func(cb https.CallBuilder) { - cb.InterceptRequest(f) - } + f := func(request *http.Request) *http.Request { + request.Header.Set("user-agent", userAgent) + return request + } + return func(cb https.CallBuilder) { + cb.InterceptRequest(f) + } } // withGlobalErrors will add all globally defined errors to callBuilder. func withGlobalErrors() clientOptions { - return func(cb https.CallBuilder) { - cb.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "0": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'."}, - }) - } + return func(cb https.CallBuilder) { + cb.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "0": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'."}, + }) + } } diff --git a/components_controller.go b/components_controller.go index a95f6b16..32ef210b 100644 --- a/components_controller.go +++ b/components_controller.go @@ -1,865 +1,932 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "time" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "time" ) // ComponentsController represents a controller struct. type ComponentsController struct { - baseController + baseController } -// NewComponentsController creates a new instance of ComponentsController. +// NewComponentsController creates a new instance of ComponentsController. // It takes a baseController as a parameter and returns a pointer to the ComponentsController. func NewComponentsController(baseController baseController) *ComponentsController { - componentsController := ComponentsController{baseController: baseController} - return &componentsController + componentsController := ComponentsController{baseController: baseController} + return &componentsController } -// CreateMeteredComponent takes context, productFamilyId, body as parameters and -// returns an models.ApiResponse with models.ComponentResponse data and -// an error if there was an issue with the request or response. -// This request will create a component definition of kind **metered_component** under the specified product family. Metered component can then be added and “allocated” for a subscription. -// Metered components are used to bill for any type of unit that resets to 0 at the end of the billing period (think daily Google Adwords clicks or monthly cell phone minutes). This is most commonly associated with usage-based billing and many other pricing schemes. -// Note that this is different from recurring quantity-based components, which DO NOT reset to zero at the start of every billing period. If you want to bill for a quantity of something that does not change unless you change it, then you want quantity components, instead. +// CreateMeteredComponent takes context, productFamilyId, body as parameters and +// returns an models.ApiResponse with models.ComponentResponse data and +// an error if there was an issue with the request or response. +// This request will create a component definition of kind **metered_component** under the specified product family. Metered component can then be added and “allocated” for a subscription. +// Metered components are used to bill for any type of unit that resets to 0 at the end of the billing period (think daily Google Adwords clicks or monthly cell phone minutes). This is most commonly associated with usage-based billing and many other pricing schemes. +// Note that this is different from recurring quantity-based components, which DO NOT reset to zero at the start of every billing period. If you want to bill for a quantity of something that does not change unless you change it, then you want quantity components, instead. // For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). func (c *ComponentsController) CreateMeteredComponent( - ctx context.Context, - productFamilyId int, - body *models.CreateMeteredComponent) ( - models.ApiResponse[models.ComponentResponse], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/product_families/%v/metered_components.json", productFamilyId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + body *models.CreateMeteredComponent) ( + models.ApiResponse[models.ComponentResponse], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/product_families/%v/metered_components.json", productFamilyId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreateQuantityBasedComponent takes context, productFamilyId, body as parameters and -// returns an models.ApiResponse with models.ComponentResponse data and -// an error if there was an issue with the request or response. -// This request will create a component definition of kind **quantity_based_component** under the specified product family. Quantity Based component can then be added and “allocated” for a subscription. -// When defining Quantity Based component, You can choose one of 2 types: -// #### Recurring -// Recurring quantity-based components are used to bill for the number of some unit (think monthly software user licenses or the number of pairs of socks in a box-a-month club). This is most commonly associated with billing for user licenses, number of users, number of employees, etc. -// #### One-time -// One-time quantity-based components are used to create ad hoc usage charges that do not recur. For example, at the time of signup, you might want to charge your customer a one-time fee for onboarding or other services. -// The allocated quantity for one-time quantity-based components immediately gets reset back to zero after the allocation is made. +// CreateQuantityBasedComponent takes context, productFamilyId, body as parameters and +// returns an models.ApiResponse with models.ComponentResponse data and +// an error if there was an issue with the request or response. +// This request will create a component definition of kind **quantity_based_component** under the specified product family. Quantity Based component can then be added and “allocated” for a subscription. +// When defining Quantity Based component, You can choose one of 2 types: +// #### Recurring +// Recurring quantity-based components are used to bill for the number of some unit (think monthly software user licenses or the number of pairs of socks in a box-a-month club). This is most commonly associated with billing for user licenses, number of users, number of employees, etc. +// #### One-time +// One-time quantity-based components are used to create ad hoc usage charges that do not recur. For example, at the time of signup, you might want to charge your customer a one-time fee for onboarding or other services. +// The allocated quantity for one-time quantity-based components immediately gets reset back to zero after the allocation is made. // For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). func (c *ComponentsController) CreateQuantityBasedComponent( - ctx context.Context, - productFamilyId int, - body *models.CreateQuantityBasedComponent) ( - models.ApiResponse[models.ComponentResponse], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/product_families/%v/quantity_based_components.json", productFamilyId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + body *models.CreateQuantityBasedComponent) ( + models.ApiResponse[models.ComponentResponse], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/product_families/%v/quantity_based_components.json", productFamilyId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreateOnOffComponent takes context, productFamilyId, body as parameters and -// returns an models.ApiResponse with models.ComponentResponse data and -// an error if there was an issue with the request or response. -// This request will create a component definition of kind **on_off_component** under the specified product family. On/Off component can then be added and “allocated” for a subscription. -// On/off components are used for any flat fee, recurring add on (think $99/month for tech support or a flat add on shipping fee). +// CreateOnOffComponent takes context, productFamilyId, body as parameters and +// returns an models.ApiResponse with models.ComponentResponse data and +// an error if there was an issue with the request or response. +// This request will create a component definition of kind **on_off_component** under the specified product family. On/Off component can then be added and “allocated” for a subscription. +// On/off components are used for any flat fee, recurring add on (think $99/month for tech support or a flat add on shipping fee). // For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). func (c *ComponentsController) CreateOnOffComponent( - ctx context.Context, - productFamilyId int, - body *models.CreateOnOffComponent) ( - models.ApiResponse[models.ComponentResponse], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/product_families/%v/on_off_components.json", productFamilyId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + body *models.CreateOnOffComponent) ( + models.ApiResponse[models.ComponentResponse], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/product_families/%v/on_off_components.json", productFamilyId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreatePrepaidUsageComponent takes context, productFamilyId, body as parameters and -// returns an models.ApiResponse with models.ComponentResponse data and -// an error if there was an issue with the request or response. -// This request will create a component definition of kind **prepaid_usage_component** under the specified product family. Prepaid component can then be added and “allocated” for a subscription. -// Prepaid components allow customers to pre-purchase units that can be used up over time on their subscription. In a sense, they are the mirror image of metered components; while metered components charge at the end of the period for the amount of units used, prepaid components are charged for at the time of purchase, and we subsequently keep track of the usage against the amount purchased. +// CreatePrepaidUsageComponent takes context, productFamilyId, body as parameters and +// returns an models.ApiResponse with models.ComponentResponse data and +// an error if there was an issue with the request or response. +// This request will create a component definition of kind **prepaid_usage_component** under the specified product family. Prepaid component can then be added and “allocated” for a subscription. +// Prepaid components allow customers to pre-purchase units that can be used up over time on their subscription. In a sense, they are the mirror image of metered components; while metered components charge at the end of the period for the amount of units used, prepaid components are charged for at the time of purchase, and we subsequently keep track of the usage against the amount purchased. // For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). func (c *ComponentsController) CreatePrepaidUsageComponent( - ctx context.Context, - productFamilyId int, - body *models.CreatePrepaidComponent) ( - models.ApiResponse[models.ComponentResponse], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/product_families/%v/prepaid_usage_components.json", productFamilyId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + body *models.CreatePrepaidComponent) ( + models.ApiResponse[models.ComponentResponse], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/product_families/%v/prepaid_usage_components.json", productFamilyId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreateEventBasedComponent takes context, productFamilyId, body as parameters and -// returns an models.ApiResponse with models.ComponentResponse data and -// an error if there was an issue with the request or response. -// This request will create a component definition of kind **event_based_component** under the specified product family. Event-based component can then be added and “allocated” for a subscription. -// Event-based components are similar to other component types, in that you define the component parameters (such as name and taxability) and the pricing. A key difference for the event-based component is that it must be attached to a metric. This is because the metric provides the component with the actual quantity used in computing what and how much will be billed each period for each subscription. -// So, instead of reporting usage directly for each component (as you would with metered components), the usage is derived from analysis of your events. +// CreateEventBasedComponent takes context, productFamilyId, body as parameters and +// returns an models.ApiResponse with models.ComponentResponse data and +// an error if there was an issue with the request or response. +// This request will create a component definition of kind **event_based_component** under the specified product family. Event-based component can then be added and “allocated” for a subscription. +// Event-based components are similar to other component types, in that you define the component parameters (such as name and taxability) and the pricing. A key difference for the event-based component is that it must be attached to a metric. This is because the metric provides the component with the actual quantity used in computing what and how much will be billed each period for each subscription. +// So, instead of reporting usage directly for each component (as you would with metered components), the usage is derived from analysis of your events. // For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). func (c *ComponentsController) CreateEventBasedComponent( - ctx context.Context, - productFamilyId int, - body *models.CreateEBBComponent) ( - models.ApiResponse[models.ComponentResponse], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/product_families/%v/event_based_components.json", productFamilyId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + body *models.CreateEBBComponent) ( + models.ApiResponse[models.ComponentResponse], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/product_families/%v/event_based_components.json", productFamilyId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// FindComponent takes context, handle as parameters and -// returns an models.ApiResponse with models.ComponentResponse data and -// an error if there was an issue with the request or response. +// FindComponent takes context, handle as parameters and +// returns an models.ApiResponse with models.ComponentResponse data and +// an error if there was an issue with the request or response. // This request will return information regarding a component having the handle you provide. You can identify your components with a handle so you don't have to save or reference the IDs we generate. func (c *ComponentsController) FindComponent( - ctx context.Context, - handle string) ( - models.ApiResponse[models.ComponentResponse], - error) { - req := c.prepareRequest(ctx, "GET", "/components/lookup.json") - req.Authenticate(NewAuth("BasicAuth")) - req.QueryParam("handle", handle) - var result models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + handle string) ( + models.ApiResponse[models.ComponentResponse], + error) { + req := c.prepareRequest(ctx, "GET", "/components/lookup.json") + req.Authenticate(NewAuth("BasicAuth")) + req.QueryParam("handle", handle) + var result models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadComponent takes context, productFamilyId, componentId as parameters and -// returns an models.ApiResponse with models.ComponentResponse data and -// an error if there was an issue with the request or response. -// This request will return information regarding a component from a specific product family. +// ReadComponent takes context, productFamilyId, componentId as parameters and +// returns an models.ApiResponse with models.ComponentResponse data and +// an error if there was an issue with the request or response. +// This request will return information regarding a component from a specific product family. // You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. func (c *ComponentsController) ReadComponent( - ctx context.Context, - productFamilyId int, - componentId string) ( - models.ApiResponse[models.ComponentResponse], - error) { - req := c.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/product_families/%v/components/%v.json", productFamilyId, componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + componentId string) ( + models.ApiResponse[models.ComponentResponse], + error) { + req := c.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/product_families/%v/components/%v.json", productFamilyId, componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateProductFamilyComponent takes context, productFamilyId, componentId, body as parameters and -// returns an models.ApiResponse with models.ComponentResponse data and -// an error if there was an issue with the request or response. -// This request will update a component from a specific product family. +// UpdateProductFamilyComponent takes context, productFamilyId, componentId, body as parameters and +// returns an models.ApiResponse with models.ComponentResponse data and +// an error if there was an issue with the request or response. +// This request will update a component from a specific product family. // You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. func (c *ComponentsController) UpdateProductFamilyComponent( - ctx context.Context, - productFamilyId int, - componentId string, - body *models.UpdateComponentRequest) ( - models.ApiResponse[models.ComponentResponse], - error) { - req := c.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/product_families/%v/components/%v.json", productFamilyId, componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + componentId string, + body *models.UpdateComponentRequest) ( + models.ApiResponse[models.ComponentResponse], + error) { + req := c.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/product_families/%v/components/%v.json", productFamilyId, componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ArchiveComponent takes context, productFamilyId, componentId as parameters and -// returns an models.ApiResponse with models.Component data and -// an error if there was an issue with the request or response. +// ArchiveComponent takes context, productFamilyId, componentId as parameters and +// returns an models.ApiResponse with models.Component data and +// an error if there was an issue with the request or response. // Sending a DELETE request to this endpoint will archive the component. All current subscribers will be unffected; their subscription/purchase will continue to be charged as usual. func (c *ComponentsController) ArchiveComponent( - ctx context.Context, - productFamilyId int, - componentId string) ( - models.ApiResponse[models.Component], - error) { - req := c.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/product_families/%v/components/%v.json", productFamilyId, componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.Component - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.Component](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + componentId string) ( + models.ApiResponse[models.Component], + error) { + req := c.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/product_families/%v/components/%v.json", productFamilyId, componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.Component + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.Component](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListComponentsInput represents the input of the ListComponents endpoint. +type ListComponentsInput struct { + // The type of filter you would like to apply to your search. + DateField *models.BasicDateField + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + StartDate *string + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + EndDate *string + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. + StartDatetime *string + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. optional + EndDatetime *string + // Include archived items + IncludeArchived *bool + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // Allows fetching components with matching id based on provided value. Use in query `filter[ids]=1,2,3`. + FilterIds []string + // Allows fetching components with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. + FilterUseSiteExchangeRate *bool } -// ListComponents takes context, dateField, startDate, endDate, startDatetime, endDatetime, includeArchived, page, perPage, filterIds, filterUseSiteExchangeRate as parameters and -// returns an models.ApiResponse with []models.ComponentResponse data and -// an error if there was an issue with the request or response. +// ListComponents takes context, dateField, startDate, endDate, startDatetime, endDatetime, includeArchived, page, perPage, filterIds, filterUseSiteExchangeRate as parameters and +// returns an models.ApiResponse with []models.ComponentResponse data and +// an error if there was an issue with the request or response. // This request will return a list of components for a site. func (c *ComponentsController) ListComponents( - ctx context.Context, - dateField *models.BasicDateField, - startDate *string, - endDate *string, - startDatetime *string, - endDatetime *string, - includeArchived *bool, - page *int, - perPage *int, - filterIds []string, - filterUseSiteExchangeRate *bool) ( - models.ApiResponse[[]models.ComponentResponse], - error) { - req := c.prepareRequest(ctx, "GET", "/components.json") - req.Authenticate(NewAuth("BasicAuth")) - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if startDate != nil { - req.QueryParam("start_date", *startDate) - } - if endDate != nil { - req.QueryParam("end_date", *endDate) - } - if startDatetime != nil { - req.QueryParam("start_datetime", *startDatetime) - } - if endDatetime != nil { - req.QueryParam("end_datetime", *endDatetime) - } - if includeArchived != nil { - req.QueryParam("include_archived", *includeArchived) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if filterIds != nil { - req.QueryParam("filter[ids]", filterIds) - } - if filterUseSiteExchangeRate != nil { - req.QueryParam("filter[use_site_exchange_rate]", *filterUseSiteExchangeRate) - } - var result []models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListComponentsInput) ( + models.ApiResponse[[]models.ComponentResponse], + error) { + req := c.prepareRequest(ctx, "GET", "/components.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.StartDate != nil { + req.QueryParam("start_date", *input.StartDate) + } + if input.EndDate != nil { + req.QueryParam("end_date", *input.EndDate) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", *input.StartDatetime) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", *input.EndDatetime) + } + if input.IncludeArchived != nil { + req.QueryParam("include_archived", *input.IncludeArchived) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.FilterIds != nil { + req.QueryParam("filter[ids]", input.FilterIds) + } + if input.FilterUseSiteExchangeRate != nil { + req.QueryParam("filter[use_site_exchange_rate]", *input.FilterUseSiteExchangeRate) + } + var result []models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateComponent takes context, componentId, body as parameters and -// returns an models.ApiResponse with models.ComponentResponse data and -// an error if there was an issue with the request or response. -// This request will update a component. +// UpdateComponent takes context, componentId, body as parameters and +// returns an models.ApiResponse with models.ComponentResponse data and +// an error if there was an issue with the request or response. +// This request will update a component. // You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. func (c *ComponentsController) UpdateComponent( - ctx context.Context, - componentId string, - body *models.UpdateComponentRequest) ( - models.ApiResponse[models.ComponentResponse], - error) { - req := c.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/components/%v.json", componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + componentId string, + body *models.UpdateComponentRequest) ( + models.ApiResponse[models.ComponentResponse], + error) { + req := c.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/components/%v.json", componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// PromoteComponentPricePointToDefault takes context, componentId, pricePointId as parameters and -// returns an models.ApiResponse with models.ComponentResponse data and -// an error if there was an issue with the request or response. -// Sets a new default price point for the component. This new default will apply to all new subscriptions going forward - existing subscriptions will remain on their current price point. -// See [Price Points Documentation](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-points) for more information on price points and moving subscriptions between price points. +// PromoteComponentPricePointToDefault takes context, componentId, pricePointId as parameters and +// returns an models.ApiResponse with models.ComponentResponse data and +// an error if there was an issue with the request or response. +// Sets a new default price point for the component. This new default will apply to all new subscriptions going forward - existing subscriptions will remain on their current price point. +// See [Price Points Documentation](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-points) for more information on price points and moving subscriptions between price points. // Note: Custom price points are not able to be set as the default for a component. func (c *ComponentsController) PromoteComponentPricePointToDefault( - ctx context.Context, - componentId int, - pricePointId int) ( - models.ApiResponse[models.ComponentResponse], - error) { - req := c.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/components/%v/price_points/%v/default.json", componentId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + componentId int, + pricePointId int) ( + models.ApiResponse[models.ComponentResponse], + error) { + req := c.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/components/%v/price_points/%v/default.json", componentId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListComponentsForProductFamily takes context, productFamilyId, includeArchived, filterIds, page, perPage, dateField, endDate, endDatetime, startDate, startDatetime, filterUseSiteExchangeRate as parameters and -// returns an models.ApiResponse with []models.ComponentResponse data and -// an error if there was an issue with the request or response. +// ListComponentsForProductFamilyInput represents the input of the ListComponentsForProductFamily endpoint. +type ListComponentsForProductFamilyInput struct { + // The Chargify id of the product family + ProductFamilyId int + // Include archived items. + IncludeArchived *bool + // Allows fetching components with matching id based on provided value. Use in query `filter[ids]=1,2`. + FilterIds []int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The type of filter you would like to apply to your search. Use in query `date_field=created_at`. + DateField *models.BasicDateField + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + EndDate *string + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. optional. + EndDatetime *string + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + StartDate *string + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. + StartDatetime *string + // Allows fetching components with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. + FilterUseSiteExchangeRate *bool +} + +// ListComponentsForProductFamily takes context, productFamilyId, includeArchived, filterIds, page, perPage, dateField, endDate, endDatetime, startDate, startDatetime, filterUseSiteExchangeRate as parameters and +// returns an models.ApiResponse with []models.ComponentResponse data and +// an error if there was an issue with the request or response. // This request will return a list of components for a particular product family. func (c *ComponentsController) ListComponentsForProductFamily( - ctx context.Context, - productFamilyId int, - includeArchived *bool, - filterIds []int, - page *int, - perPage *int, - dateField *models.BasicDateField, - endDate *string, - endDatetime *string, - startDate *string, - startDatetime *string, - filterUseSiteExchangeRate *bool) ( - models.ApiResponse[[]models.ComponentResponse], - error) { - req := c.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/product_families/%v/components.json", productFamilyId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if includeArchived != nil { - req.QueryParam("include_archived", *includeArchived) - } - if filterIds != nil { - req.QueryParam("filter[ids]", filterIds) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if endDate != nil { - req.QueryParam("end_date", *endDate) - } - if endDatetime != nil { - req.QueryParam("end_datetime", *endDatetime) - } - if startDate != nil { - req.QueryParam("start_date", *startDate) - } - if startDatetime != nil { - req.QueryParam("start_datetime", *startDatetime) - } - if filterUseSiteExchangeRate != nil { - req.QueryParam("filter[use_site_exchange_rate]", *filterUseSiteExchangeRate) - } - - var result []models.ComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.ComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListComponentsForProductFamilyInput) ( + models.ApiResponse[[]models.ComponentResponse], + error) { + req := c.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/product_families/%v/components.json", input.ProductFamilyId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.IncludeArchived != nil { + req.QueryParam("include_archived", *input.IncludeArchived) + } + if input.FilterIds != nil { + req.QueryParam("filter[ids]", input.FilterIds) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.EndDate != nil { + req.QueryParam("end_date", *input.EndDate) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", *input.EndDatetime) + } + if input.StartDate != nil { + req.QueryParam("start_date", *input.StartDate) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", *input.StartDatetime) + } + if input.FilterUseSiteExchangeRate != nil { + req.QueryParam("filter[use_site_exchange_rate]", *input.FilterUseSiteExchangeRate) + } + + var result []models.ComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.ComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreateComponentPricePoint takes context, componentId, body as parameters and -// returns an models.ApiResponse with models.ComponentPricePointResponse data and -// an error if there was an issue with the request or response. +// CreateComponentPricePoint takes context, componentId, body as parameters and +// returns an models.ApiResponse with models.ComponentPricePointResponse data and +// an error if there was an issue with the request or response. // This endpoint can be used to create a new price point for an existing component. func (c *ComponentsController) CreateComponentPricePoint( - ctx context.Context, - componentId int, - body *models.CreateComponentPricePointRequest) ( - models.ApiResponse[models.ComponentPricePointResponse], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/components/%v/price_points.json", componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentPricePointResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentPricePointResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + componentId int, + body *models.CreateComponentPricePointRequest) ( + models.ApiResponse[models.ComponentPricePointResponse], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/components/%v/price_points.json", componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentPricePointResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentPricePointResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListComponentPricePointsInput represents the input of the ListComponentPricePoints endpoint. +type ListComponentPricePointsInput struct { + // The Chargify id of the component + ComponentId int + // Include an array of currency price data + CurrencyPrices *bool + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // Use in query: `filter[type]=catalog,default`. + FilterType []models.PricePointType } -// ListComponentPricePoints takes context, componentId, currencyPrices, page, perPage, filterType as parameters and -// returns an models.ApiResponse with models.ComponentPricePointsResponse data and -// an error if there was an issue with the request or response. -// Use this endpoint to read current price points that are associated with a component. -// You may specify the component by using either the numeric id or the `handle:gold` syntax. -// When fetching a component's price points, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. +// ListComponentPricePoints takes context, componentId, currencyPrices, page, perPage, filterType as parameters and +// returns an models.ApiResponse with models.ComponentPricePointsResponse data and +// an error if there was an issue with the request or response. +// Use this endpoint to read current price points that are associated with a component. +// You may specify the component by using either the numeric id or the `handle:gold` syntax. +// When fetching a component's price points, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. // If the price point is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. func (c *ComponentsController) ListComponentPricePoints( - ctx context.Context, - componentId int, - currencyPrices *bool, - page *int, - perPage *int, - filterType []models.PricePointType) ( - models.ApiResponse[models.ComponentPricePointsResponse], - error) { - req := c.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/components/%v/price_points.json", componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if currencyPrices != nil { - req.QueryParam("currency_prices", *currencyPrices) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if filterType != nil { - req.QueryParam("filter[type]", filterType) - } - - var result models.ComponentPricePointsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentPricePointsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListComponentPricePointsInput) ( + models.ApiResponse[models.ComponentPricePointsResponse], + error) { + req := c.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/components/%v/price_points.json", input.ComponentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.CurrencyPrices != nil { + req.QueryParam("currency_prices", *input.CurrencyPrices) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.FilterType != nil { + req.QueryParam("filter[type]", input.FilterType) + } + + var result models.ComponentPricePointsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentPricePointsResponse](decoder) + return models.NewApiResponse(result, resp), err } -// BulkCreateComponentPricePoints takes context, componentId, body as parameters and -// returns an models.ApiResponse with models.ComponentPricePointsResponse data and -// an error if there was an issue with the request or response. +// BulkCreateComponentPricePoints takes context, componentId, body as parameters and +// returns an models.ApiResponse with models.ComponentPricePointsResponse data and +// an error if there was an issue with the request or response. // Use this endpoint to create multiple component price points in one request. func (c *ComponentsController) BulkCreateComponentPricePoints( - ctx context.Context, - componentId string, - body *models.CreateComponentPricePointsRequest) ( - models.ApiResponse[models.ComponentPricePointsResponse], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/components/%v/price_points/bulk.json", componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentPricePointsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentPricePointsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + componentId string, + body *models.CreateComponentPricePointsRequest) ( + models.ApiResponse[models.ComponentPricePointsResponse], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/components/%v/price_points/bulk.json", componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentPricePointsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentPricePointsResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateComponentPricePoint takes context, componentId, pricePointId, body as parameters and -// returns an models.ApiResponse with models.ComponentPricePointResponse data and -// an error if there was an issue with the request or response. -// When updating a price point, it's prices can be updated as well by creating new prices or editing / removing existing ones. -// Passing in a price bracket without an `id` will attempt to create a new price. -// Including an `id` will update the corresponding price, and including the `_destroy` flag set to true along with the `id` will remove that price. +// UpdateComponentPricePoint takes context, componentId, pricePointId, body as parameters and +// returns an models.ApiResponse with models.ComponentPricePointResponse data and +// an error if there was an issue with the request or response. +// When updating a price point, it's prices can be updated as well by creating new prices or editing / removing existing ones. +// Passing in a price bracket without an `id` will attempt to create a new price. +// Including an `id` will update the corresponding price, and including the `_destroy` flag set to true along with the `id` will remove that price. // Note: Custom price points cannot be updated directly. They must be edited through the Subscription. func (c *ComponentsController) UpdateComponentPricePoint( - ctx context.Context, - componentId int, - pricePointId int, - body *models.UpdateComponentPricePointRequest) ( - models.ApiResponse[models.ComponentPricePointResponse], - error) { - req := c.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/components/%v/price_points/%v.json", componentId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentPricePointResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentPricePointResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + componentId int, + pricePointId int, + body *models.UpdateComponentPricePointRequest) ( + models.ApiResponse[models.ComponentPricePointResponse], + error) { + req := c.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/components/%v/price_points/%v.json", componentId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentPricePointResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentPricePointResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ArchiveComponentPricePoint takes context, componentId, pricePointId as parameters and -// returns an models.ApiResponse with models.ComponentPricePointResponse data and -// an error if there was an issue with the request or response. +// ArchiveComponentPricePoint takes context, componentId, pricePointId as parameters and +// returns an models.ApiResponse with models.ComponentPricePointResponse data and +// an error if there was an issue with the request or response. // A price point can be archived at any time. Subscriptions using a price point that has been archived will continue using it until they're moved to another price point. func (c *ComponentsController) ArchiveComponentPricePoint( - ctx context.Context, - componentId int, - pricePointId int) ( - models.ApiResponse[models.ComponentPricePointResponse], - error) { - req := c.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/components/%v/price_points/%v.json", componentId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.ComponentPricePointResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentPricePointResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + componentId int, + pricePointId int) ( + models.ApiResponse[models.ComponentPricePointResponse], + error) { + req := c.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/components/%v/price_points/%v.json", componentId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.ComponentPricePointResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentPricePointResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UnarchiveComponentPricePoint takes context, componentId, pricePointId as parameters and -// returns an models.ApiResponse with models.ComponentPricePointResponse data and -// an error if there was an issue with the request or response. +// UnarchiveComponentPricePoint takes context, componentId, pricePointId as parameters and +// returns an models.ApiResponse with models.ComponentPricePointResponse data and +// an error if there was an issue with the request or response. // Use this endpoint to unarchive a component price point. func (c *ComponentsController) UnarchiveComponentPricePoint( - ctx context.Context, - componentId int, - pricePointId int) ( - models.ApiResponse[models.ComponentPricePointResponse], - error) { - req := c.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/components/%v/price_points/%v/unarchive.json", componentId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.ComponentPricePointResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentPricePointResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + componentId int, + pricePointId int) ( + models.ApiResponse[models.ComponentPricePointResponse], + error) { + req := c.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/components/%v/price_points/%v/unarchive.json", componentId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.ComponentPricePointResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentPricePointResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreateCurrencyPrices takes context, pricePointId, body as parameters and -// returns an models.ApiResponse with models.ComponentCurrencyPricesResponse data and -// an error if there was an issue with the request or response. -// This endpoint allows you to create currency prices for a given currency that has been defined on the site level in your settings. -// When creating currency prices, they need to mirror the structure of your primary pricing. For each price level defined on the component price point, there should be a matching price level created in the given currency. +// CreateCurrencyPrices takes context, pricePointId, body as parameters and +// returns an models.ApiResponse with models.ComponentCurrencyPricesResponse data and +// an error if there was an issue with the request or response. +// This endpoint allows you to create currency prices for a given currency that has been defined on the site level in your settings. +// When creating currency prices, they need to mirror the structure of your primary pricing. For each price level defined on the component price point, there should be a matching price level created in the given currency. // Note: Currency Prices are not able to be created for custom price points. func (c *ComponentsController) CreateCurrencyPrices( - ctx context.Context, - pricePointId int, - body *models.CreateCurrencyPricesRequest) ( - models.ApiResponse[models.ComponentCurrencyPricesResponse], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/price_points/%v/currency_prices.json", pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {Message: "Unprocessable Entity (WebDAV)", Unmarshaller: errors.NewErrorArrayMapResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentCurrencyPricesResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentCurrencyPricesResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + pricePointId int, + body *models.CreateCurrencyPricesRequest) ( + models.ApiResponse[models.ComponentCurrencyPricesResponse], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/price_points/%v/currency_prices.json", pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {Message: "Unprocessable Entity (WebDAV)", Unmarshaller: errors.NewErrorArrayMapResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentCurrencyPricesResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentCurrencyPricesResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateCurrencyPrices takes context, pricePointId, body as parameters and -// returns an models.ApiResponse with models.ComponentCurrencyPricesResponse data and -// an error if there was an issue with the request or response. -// This endpoint allows you to update currency prices for a given currency that has been defined on the site level in your settings. +// UpdateCurrencyPrices takes context, pricePointId, body as parameters and +// returns an models.ApiResponse with models.ComponentCurrencyPricesResponse data and +// an error if there was an issue with the request or response. +// This endpoint allows you to update currency prices for a given currency that has been defined on the site level in your settings. // Note: Currency Prices are not able to be updated for custom price points. func (c *ComponentsController) UpdateCurrencyPrices( - ctx context.Context, - pricePointId int, - body *models.UpdateCurrencyPricesRequest) ( - models.ApiResponse[models.ComponentCurrencyPricesResponse], - error) { - req := c.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/price_points/%v/currency_prices.json", pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {Message: "Unprocessable Entity (WebDAV)", Unmarshaller: errors.NewErrorArrayMapResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ComponentCurrencyPricesResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ComponentCurrencyPricesResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + pricePointId int, + body *models.UpdateCurrencyPricesRequest) ( + models.ApiResponse[models.ComponentCurrencyPricesResponse], + error) { + req := c.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/price_points/%v/currency_prices.json", pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {Message: "Unprocessable Entity (WebDAV)", Unmarshaller: errors.NewErrorArrayMapResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ComponentCurrencyPricesResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ComponentCurrencyPricesResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListAllComponentPricePoints takes context, filterDateField, filterEndDate, filterEndDatetime, include, page, perPage, filterStartDate, filterStartDatetime, filterType, direction, filterIds, filterArchivedAt as parameters and -// returns an models.ApiResponse with models.ListComponentsPricePointsResponse data and -// an error if there was an issue with the request or response. +// ListAllComponentPricePointsInput represents the input of the ListAllComponentPricePoints endpoint. +type ListAllComponentPricePointsInput struct { + // The type of filter you would like to apply to your search. Use in query: `filter[date_field]=created_at`. + FilterDateField *models.BasicDateField + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + FilterEndDate *time.Time + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. + FilterEndDatetime *time.Time + // Allows including additional data in the response. Use in query: `include=currency_prices`. + Include *models.ListComponentsPricePointsInclude + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + FilterStartDate *time.Time + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. + FilterStartDatetime *time.Time + // Allows fetching price points with matching type. Use in query: `filter[type]=custom,catalog`. + FilterType []models.PricePointType + // Controls the order in which results are returned. + // Use in query `direction=asc`. + Direction *models.SortingDirection + // Allows fetching price points with matching id based on provided values. Use in query: `filter[ids]=1,2,3`. + FilterIds []int + // Allows fetching price points only if archived_at is present or not. Use in query: `filter[archived_at]=not_null`. + FilterArchivedAt *models.IncludeNotNull +} + +// ListAllComponentPricePoints takes context, filterDateField, filterEndDate, filterEndDatetime, include, page, perPage, filterStartDate, filterStartDatetime, filterType, direction, filterIds, filterArchivedAt as parameters and +// returns an models.ApiResponse with models.ListComponentsPricePointsResponse data and +// an error if there was an issue with the request or response. // This method allows to retrieve a list of Components Price Points belonging to a Site. func (c *ComponentsController) ListAllComponentPricePoints( - ctx context.Context, - filterDateField *models.BasicDateField, - filterEndDate *time.Time, - filterEndDatetime *time.Time, - include *models.ListComponentsPricePointsInclude, - page *int, - perPage *int, - filterStartDate *time.Time, - filterStartDatetime *time.Time, - filterType []models.PricePointType, - direction *models.SortingDirection, - filterIds []int, - filterArchivedAt *models.IncludeNotNull) ( - models.ApiResponse[models.ListComponentsPricePointsResponse], - error) { - req := c.prepareRequest(ctx, "GET", "/components_price_points.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - if filterDateField != nil { - req.QueryParam("filter[date_field]", *filterDateField) - } - if filterEndDate != nil { - req.QueryParam("filter[end_date]", filterEndDate.Format(models.DEFAULT_DATE)) - } - if filterEndDatetime != nil { - req.QueryParam("filter[end_datetime]", filterEndDatetime.Format(time.RFC3339)) - } - if include != nil { - req.QueryParam("include", *include) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if filterStartDate != nil { - req.QueryParam("filter[start_date]", filterStartDate.Format(models.DEFAULT_DATE)) - } - if filterStartDatetime != nil { - req.QueryParam("filter[start_datetime]", filterStartDatetime.Format(time.RFC3339)) - } - if filterType != nil { - req.QueryParam("filter[type]", filterType) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - if filterIds != nil { - req.QueryParam("filter[ids]", filterIds) - } - if filterArchivedAt != nil { - req.QueryParam("filter[archived_at]", *filterArchivedAt) - } - var result models.ListComponentsPricePointsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListComponentsPricePointsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListAllComponentPricePointsInput) ( + models.ApiResponse[models.ListComponentsPricePointsResponse], + error) { + req := c.prepareRequest(ctx, "GET", "/components_price_points.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + if input.FilterDateField != nil { + req.QueryParam("filter[date_field]", *input.FilterDateField) + } + if input.FilterEndDate != nil { + req.QueryParam("filter[end_date]", input.FilterEndDate.Format(models.DEFAULT_DATE)) + } + if input.FilterEndDatetime != nil { + req.QueryParam("filter[end_datetime]", input.FilterEndDatetime.Format(time.RFC3339)) + } + if input.Include != nil { + req.QueryParam("include", *input.Include) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.FilterStartDate != nil { + req.QueryParam("filter[start_date]", input.FilterStartDate.Format(models.DEFAULT_DATE)) + } + if input.FilterStartDatetime != nil { + req.QueryParam("filter[start_datetime]", input.FilterStartDatetime.Format(time.RFC3339)) + } + if input.FilterType != nil { + req.QueryParam("filter[type]", input.FilterType) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + if input.FilterIds != nil { + req.QueryParam("filter[ids]", input.FilterIds) + } + if input.FilterArchivedAt != nil { + req.QueryParam("filter[archived_at]", *input.FilterArchivedAt) + } + var result models.ListComponentsPricePointsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListComponentsPricePointsResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/coupons_controller.go b/coupons_controller.go index 4f8193d9..fa99e5a7 100644 --- a/coupons_controller.go +++ b/coupons_controller.go @@ -1,612 +1,664 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" - "time" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" + "time" ) // CouponsController represents a controller struct. type CouponsController struct { - baseController + baseController } -// NewCouponsController creates a new instance of CouponsController. +// NewCouponsController creates a new instance of CouponsController. // It takes a baseController as a parameter and returns a pointer to the CouponsController. func NewCouponsController(baseController baseController) *CouponsController { - couponsController := CouponsController{baseController: baseController} - return &couponsController + couponsController := CouponsController{baseController: baseController} + return &couponsController } -// CreateCoupon takes context, productFamilyId, body as parameters and -// returns an models.ApiResponse with models.CouponResponse data and -// an error if there was an issue with the request or response. -// ## Coupons Documentation -// Coupons can be administered in the Chargify application or created via API. Please view our section on [creating coupons](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404742830733) for more information. -// Additionally, for documentation on how to apply a coupon to a subscription within the Chargify UI, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404761012877). -// ## Create Coupon -// This request will create a coupon, based on the provided information. -// When creating a coupon, you must specify a product family using the `product_family_id`. If no `product_family_id` is passed, the first product family available is used. You will also need to formulate your URL to cite the Product Family ID in your request. -// You can restrict a coupon to only apply to specific products / components by optionally passing in hashes of `restricted_products` and/or `restricted_components` in the format: +// CreateCoupon takes context, productFamilyId, body as parameters and +// returns an models.ApiResponse with models.CouponResponse data and +// an error if there was an issue with the request or response. +// ## Coupons Documentation +// Coupons can be administered in the Chargify application or created via API. Please view our section on [creating coupons](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404742830733) for more information. +// Additionally, for documentation on how to apply a coupon to a subscription within the Chargify UI, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404761012877). +// ## Create Coupon +// This request will create a coupon, based on the provided information. +// When creating a coupon, you must specify a product family using the `product_family_id`. If no `product_family_id` is passed, the first product family available is used. You will also need to formulate your URL to cite the Product Family ID in your request. +// You can restrict a coupon to only apply to specific products / components by optionally passing in hashes of `restricted_products` and/or `restricted_components` in the format: // `{ "": boolean_value }` func (c *CouponsController) CreateCoupon( - ctx context.Context, - productFamilyId int, - body *models.CreateOrUpdateCoupon) ( - models.ApiResponse[models.CouponResponse], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/product_families/%v/coupons.json", productFamilyId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.CouponResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CouponResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + body *models.CreateOrUpdateCoupon) ( + models.ApiResponse[models.CouponResponse], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/product_families/%v/coupons.json", productFamilyId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.CouponResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CouponResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListCouponsForProductFamily takes context, productFamilyId, page, perPage, filterDateField, filterEndDate, filterEndDatetime, filterStartDate, filterStartDatetime, filterIds, filterCodes, currencyPrices, filterUseSiteExchangeRate as parameters and -// returns an models.ApiResponse with []models.CouponResponse data and -// an error if there was an issue with the request or response. -// List coupons for a specific Product Family in a Site. +// ListCouponsForProductFamilyInput represents the input of the ListCouponsForProductFamily endpoint. +type ListCouponsForProductFamilyInput struct { + // The Chargify id of the product family to which the coupon belongs + ProductFamilyId int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The type of filter you would like to apply to your search. Use in query `filter[date_field]=created_at`. + FilterDateField *models.BasicDateField + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `filter[date_field]=2011-12-15`. + FilterEndDate *time.Time + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `?filter[end_datetime]=2011-12-1T10:15:30+01:00`. + FilterEndDatetime *time.Time + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `filter[start_date]=2011-12-17`. + FilterStartDate *time.Time + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `filter[start_datetime]=2011-12-19T10:15:30+01:00`. + FilterStartDatetime *time.Time + // Allows fetching coupons with matching id based on provided values. Use in query `filter[ids]=1,2,3`. + FilterIds []int + // Allows fetching coupons with matching codes based on provided values. Use in query `filter[codes]=free,free_trial`. + FilterCodes []string + // When fetching coupons, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. Use in query `currency_prices=true`. + CurrencyPrices *bool + // Allows fetching coupons with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. + FilterUseSiteExchangeRate *bool +} + +// ListCouponsForProductFamily takes context, productFamilyId, page, perPage, filterDateField, filterEndDate, filterEndDatetime, filterStartDate, filterStartDatetime, filterIds, filterCodes, currencyPrices, filterUseSiteExchangeRate as parameters and +// returns an models.ApiResponse with []models.CouponResponse data and +// an error if there was an issue with the request or response. +// List coupons for a specific Product Family in a Site. // If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. func (c *CouponsController) ListCouponsForProductFamily( - ctx context.Context, - productFamilyId int, - page *int, - perPage *int, - filterDateField *models.BasicDateField, - filterEndDate *time.Time, - filterEndDatetime *time.Time, - filterStartDate *time.Time, - filterStartDatetime *time.Time, - filterIds []int, - filterCodes []string, - currencyPrices *bool, - filterUseSiteExchangeRate *bool) ( - models.ApiResponse[[]models.CouponResponse], - error) { - req := c.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/product_families/%v/coupons.json", productFamilyId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if filterDateField != nil { - req.QueryParam("filter[date_field]", *filterDateField) - } - if filterEndDate != nil { - req.QueryParam("filter[end_date]", filterEndDate.Format(models.DEFAULT_DATE)) - } - if filterEndDatetime != nil { - req.QueryParam("filter[end_datetime]", filterEndDatetime.Format(time.RFC3339)) - } - if filterStartDate != nil { - req.QueryParam("filter[start_date]", filterStartDate.Format(models.DEFAULT_DATE)) - } - if filterStartDatetime != nil { - req.QueryParam("filter[start_datetime]", filterStartDatetime.Format(time.RFC3339)) - } - if filterIds != nil { - req.QueryParam("filter[ids]", filterIds) - } - if filterCodes != nil { - req.QueryParam("filter[codes]", filterCodes) - } - if currencyPrices != nil { - req.QueryParam("currency_prices", *currencyPrices) - } - if filterUseSiteExchangeRate != nil { - req.QueryParam("filter[use_site_exchange_rate]", *filterUseSiteExchangeRate) - } - - var result []models.CouponResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.CouponResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListCouponsForProductFamilyInput) ( + models.ApiResponse[[]models.CouponResponse], + error) { + req := c.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/product_families/%v/coupons.json", input.ProductFamilyId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.FilterDateField != nil { + req.QueryParam("filter[date_field]", *input.FilterDateField) + } + if input.FilterEndDate != nil { + req.QueryParam("filter[end_date]", input.FilterEndDate.Format(models.DEFAULT_DATE)) + } + if input.FilterEndDatetime != nil { + req.QueryParam("filter[end_datetime]", input.FilterEndDatetime.Format(time.RFC3339)) + } + if input.FilterStartDate != nil { + req.QueryParam("filter[start_date]", input.FilterStartDate.Format(models.DEFAULT_DATE)) + } + if input.FilterStartDatetime != nil { + req.QueryParam("filter[start_datetime]", input.FilterStartDatetime.Format(time.RFC3339)) + } + if input.FilterIds != nil { + req.QueryParam("filter[ids]", input.FilterIds) + } + if input.FilterCodes != nil { + req.QueryParam("filter[codes]", input.FilterCodes) + } + if input.CurrencyPrices != nil { + req.QueryParam("currency_prices", *input.CurrencyPrices) + } + if input.FilterUseSiteExchangeRate != nil { + req.QueryParam("filter[use_site_exchange_rate]", *input.FilterUseSiteExchangeRate) + } + + var result []models.CouponResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.CouponResponse](decoder) + return models.NewApiResponse(result, resp), err } -// FindCoupon takes context, productFamilyId, code as parameters and -// returns an models.ApiResponse with models.CouponResponse data and -// an error if there was an issue with the request or response. -// You can search for a coupon via the API with the find method. By passing a code parameter, the find will attempt to locate a coupon that matches that code. If no coupon is found, a 404 is returned. +// FindCoupon takes context, productFamilyId, code as parameters and +// returns an models.ApiResponse with models.CouponResponse data and +// an error if there was an issue with the request or response. +// You can search for a coupon via the API with the find method. By passing a code parameter, the find will attempt to locate a coupon that matches that code. If no coupon is found, a 404 is returned. // If you have more than one product family and if the coupon you are trying to find does not belong to the default product family in your site, then you will need to specify (either in the url or as a query string param) the product family id. func (c *CouponsController) FindCoupon( - ctx context.Context, - productFamilyId *int, - code *string) ( - models.ApiResponse[models.CouponResponse], - error) { - req := c.prepareRequest(ctx, "GET", "/coupons/find.json") - req.Authenticate(NewAuth("BasicAuth")) - if productFamilyId != nil { - req.QueryParam("product_family_id", *productFamilyId) - } - if code != nil { - req.QueryParam("code", *code) - } - var result models.CouponResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CouponResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId *int, + code *string) ( + models.ApiResponse[models.CouponResponse], + error) { + req := c.prepareRequest(ctx, "GET", "/coupons/find.json") + req.Authenticate(NewAuth("BasicAuth")) + if productFamilyId != nil { + req.QueryParam("product_family_id", *productFamilyId) + } + if code != nil { + req.QueryParam("code", *code) + } + var result models.CouponResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CouponResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadCoupon takes context, productFamilyId, couponId as parameters and -// returns an models.ApiResponse with models.CouponResponse data and -// an error if there was an issue with the request or response. -// You can retrieve the Coupon via the API with the Show method. You must identify the Coupon in this call by the ID parameter that Chargify assigns. -// If instead you would like to find a Coupon using a Coupon code, see the Coupon Find method. -// When fetching a coupon, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. +// ReadCoupon takes context, productFamilyId, couponId as parameters and +// returns an models.ApiResponse with models.CouponResponse data and +// an error if there was an issue with the request or response. +// You can retrieve the Coupon via the API with the Show method. You must identify the Coupon in this call by the ID parameter that Chargify assigns. +// If instead you would like to find a Coupon using a Coupon code, see the Coupon Find method. +// When fetching a coupon, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. // If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. func (c *CouponsController) ReadCoupon( - ctx context.Context, - productFamilyId int, - couponId int) ( - models.ApiResponse[models.CouponResponse], - error) { - req := c.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/product_families/%v/coupons/%v.json", productFamilyId, couponId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.CouponResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CouponResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + couponId int) ( + models.ApiResponse[models.CouponResponse], + error) { + req := c.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/product_families/%v/coupons/%v.json", productFamilyId, couponId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.CouponResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CouponResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateCoupon takes context, productFamilyId, couponId, body as parameters and -// returns an models.ApiResponse with models.CouponResponse data and -// an error if there was an issue with the request or response. -// ## Update Coupon -// You can update a Coupon via the API with a PUT request to the resource endpoint. -// You can restrict a coupon to only apply to specific products / components by optionally passing in hashes of `restricted_products` and/or `restricted_components` in the format: +// UpdateCoupon takes context, productFamilyId, couponId, body as parameters and +// returns an models.ApiResponse with models.CouponResponse data and +// an error if there was an issue with the request or response. +// ## Update Coupon +// You can update a Coupon via the API with a PUT request to the resource endpoint. +// You can restrict a coupon to only apply to specific products / components by optionally passing in hashes of `restricted_products` and/or `restricted_components` in the format: // `{ "": boolean_value }` func (c *CouponsController) UpdateCoupon( - ctx context.Context, - productFamilyId int, - couponId int, - body *models.CreateOrUpdateCoupon) ( - models.ApiResponse[models.CouponResponse], - error) { - req := c.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/product_families/%v/coupons/%v.json", productFamilyId, couponId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.CouponResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CouponResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + couponId int, + body *models.CreateOrUpdateCoupon) ( + models.ApiResponse[models.CouponResponse], + error) { + req := c.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/product_families/%v/coupons/%v.json", productFamilyId, couponId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.CouponResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CouponResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ArchiveCoupon takes context, productFamilyId, couponId as parameters and -// returns an models.ApiResponse with models.CouponResponse data and -// an error if there was an issue with the request or response. -// You can archive a Coupon via the API with the archive method. -// Archiving makes that Coupon unavailable for future use, but allows it to remain attached and functional on existing Subscriptions that are using it. +// ArchiveCoupon takes context, productFamilyId, couponId as parameters and +// returns an models.ApiResponse with models.CouponResponse data and +// an error if there was an issue with the request or response. +// You can archive a Coupon via the API with the archive method. +// Archiving makes that Coupon unavailable for future use, but allows it to remain attached and functional on existing Subscriptions that are using it. // The `archived_at` date and time will be assigned. func (c *CouponsController) ArchiveCoupon( - ctx context.Context, - productFamilyId int, - couponId int) ( - models.ApiResponse[models.CouponResponse], - error) { - req := c.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/product_families/%v/coupons/%v.json", productFamilyId, couponId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.CouponResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CouponResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + couponId int) ( + models.ApiResponse[models.CouponResponse], + error) { + req := c.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/product_families/%v/coupons/%v.json", productFamilyId, couponId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.CouponResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CouponResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListCoupons takes context, page, perPage, dateField, startDate, endDate, startDatetime, endDatetime, filterIds, filterCodes, currencyPrices, filterEndDate, filterEndDatetime, filterStartDate, filterStartDatetime, filterDateField, filterUseSiteExchangeRate as parameters and -// returns an models.ApiResponse with []models.CouponResponse data and -// an error if there was an issue with the request or response. -// You can retrieve a list of coupons. +// ListCouponsInput represents the input of the ListCoupons endpoint. +type ListCouponsInput struct { + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The field was deprecated: on January 20, 2022. We recommend using filter[date_field] instead to achieve the same result. The type of filter you would like to apply to your search. + DateField *models.BasicDateField // Deprecated + // The field was deprecated: on January 20, 2022. We recommend using filter[start_date] instead to achieve the same result. The start date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + StartDate *time.Time // Deprecated + // The field was deprecated: on January 20, 2022. We recommend using filter[end_date] instead to achieve the same result. The end date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + EndDate *time.Time // Deprecated + // The field was deprecated: on January 20, 2022. We recommend using filter[start_datetime] instead to achieve the same result. The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. + StartDatetime *time.Time // Deprecated + // The field was deprecated: on January 20, 2022. We recommend using filter[end_datetime] instead to achieve the same result. The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. + EndDatetime *time.Time // Deprecated + // Allows fetching coupons with matching id based on provided values. Use in query `filter[ids]=1,2,3`. + FilterIds []int + // Allows fetching coupons with matching code based on provided values. Use in query `filter[ids]=1,2,3`. + FilterCodes []string + // When fetching coupons, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. Use in query `currency_prices=true`. + CurrencyPrices *bool + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `filter[end_date]=2011-12-17`. + FilterEndDate *time.Time + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `filter[end_datetime]=2011-12-19T10:15:30+01:00`. + FilterEndDatetime *time.Time + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `filter[start_date]=2011-12-19`. + FilterStartDate *time.Time + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `filter[start_datetime]=2011-12-19T10:15:30+01:00`. + FilterStartDatetime *time.Time + // The type of filter you would like to apply to your search. Use in query `filter[date_field]=updated_at`. + FilterDateField *models.BasicDateField + // Allows fetching coupons with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. + FilterUseSiteExchangeRate *bool +} + +// ListCoupons takes context, page, perPage, dateField, startDate, endDate, startDatetime, endDatetime, filterIds, filterCodes, currencyPrices, filterEndDate, filterEndDatetime, filterStartDate, filterStartDatetime, filterDateField, filterUseSiteExchangeRate as parameters and +// returns an models.ApiResponse with []models.CouponResponse data and +// an error if there was an issue with the request or response. +// You can retrieve a list of coupons. // If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. func (c *CouponsController) ListCoupons( - ctx context.Context, - page *int, - perPage *int, - dateField *models.BasicDateField, - startDate *time.Time, - endDate *time.Time, - startDatetime *time.Time, - endDatetime *time.Time, - filterIds []int, - filterCodes []string, - currencyPrices *bool, - filterEndDate *time.Time, - filterEndDatetime *time.Time, - filterStartDate *time.Time, - filterStartDatetime *time.Time, - filterDateField *models.BasicDateField, - filterUseSiteExchangeRate *bool) ( - models.ApiResponse[[]models.CouponResponse], - error) { - req := c.prepareRequest(ctx, "GET", "/coupons.json") - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if startDate != nil { - req.QueryParam("start_date", startDate.Format(models.DEFAULT_DATE)) - } - if endDate != nil { - req.QueryParam("end_date", endDate.Format(models.DEFAULT_DATE)) - } - if startDatetime != nil { - req.QueryParam("start_datetime", startDatetime.Format(time.RFC3339)) - } - if endDatetime != nil { - req.QueryParam("end_datetime", endDatetime.Format(time.RFC3339)) - } - if filterIds != nil { - req.QueryParam("filter[ids]", filterIds) - } - if filterCodes != nil { - req.QueryParam("filter[codes]", filterCodes) - } - if currencyPrices != nil { - req.QueryParam("currency_prices", *currencyPrices) - } - if filterEndDate != nil { - req.QueryParam("filter[end_date]", filterEndDate.Format(models.DEFAULT_DATE)) - } - if filterEndDatetime != nil { - req.QueryParam("filter[end_datetime]", filterEndDatetime.Format(time.RFC3339)) - } - if filterStartDate != nil { - req.QueryParam("filter[start_date]", filterStartDate.Format(models.DEFAULT_DATE)) - } - if filterStartDatetime != nil { - req.QueryParam("filter[start_datetime]", filterStartDatetime.Format(time.RFC3339)) - } - if filterDateField != nil { - req.QueryParam("filter[date_field]", *filterDateField) - } - if filterUseSiteExchangeRate != nil { - req.QueryParam("filter[use_site_exchange_rate]", *filterUseSiteExchangeRate) - } - var result []models.CouponResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.CouponResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListCouponsInput) ( + models.ApiResponse[[]models.CouponResponse], + error) { + req := c.prepareRequest(ctx, "GET", "/coupons.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.StartDate != nil { + req.QueryParam("start_date", input.StartDate.Format(models.DEFAULT_DATE)) + } + if input.EndDate != nil { + req.QueryParam("end_date", input.EndDate.Format(models.DEFAULT_DATE)) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", input.StartDatetime.Format(time.RFC3339)) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", input.EndDatetime.Format(time.RFC3339)) + } + if input.FilterIds != nil { + req.QueryParam("filter[ids]", input.FilterIds) + } + if input.FilterCodes != nil { + req.QueryParam("filter[codes]", input.FilterCodes) + } + if input.CurrencyPrices != nil { + req.QueryParam("currency_prices", *input.CurrencyPrices) + } + if input.FilterEndDate != nil { + req.QueryParam("filter[end_date]", input.FilterEndDate.Format(models.DEFAULT_DATE)) + } + if input.FilterEndDatetime != nil { + req.QueryParam("filter[end_datetime]", input.FilterEndDatetime.Format(time.RFC3339)) + } + if input.FilterStartDate != nil { + req.QueryParam("filter[start_date]", input.FilterStartDate.Format(models.DEFAULT_DATE)) + } + if input.FilterStartDatetime != nil { + req.QueryParam("filter[start_datetime]", input.FilterStartDatetime.Format(time.RFC3339)) + } + if input.FilterDateField != nil { + req.QueryParam("filter[date_field]", *input.FilterDateField) + } + if input.FilterUseSiteExchangeRate != nil { + req.QueryParam("filter[use_site_exchange_rate]", *input.FilterUseSiteExchangeRate) + } + var result []models.CouponResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.CouponResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadCouponUsage takes context, productFamilyId, couponId as parameters and -// returns an models.ApiResponse with []models.CouponUsage data and -// an error if there was an issue with the request or response. +// ReadCouponUsage takes context, productFamilyId, couponId as parameters and +// returns an models.ApiResponse with []models.CouponUsage data and +// an error if there was an issue with the request or response. // This request will provide details about the coupon usage as an array of data hashes, one per product. func (c *CouponsController) ReadCouponUsage( - ctx context.Context, - productFamilyId int, - couponId int) ( - models.ApiResponse[[]models.CouponUsage], - error) { - req := c.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/product_families/%v/coupons/%v/usage.json", productFamilyId, couponId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result []models.CouponUsage - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.CouponUsage](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + couponId int) ( + models.ApiResponse[[]models.CouponUsage], + error) { + req := c.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/product_families/%v/coupons/%v/usage.json", productFamilyId, couponId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result []models.CouponUsage + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.CouponUsage](decoder) + return models.NewApiResponse(result, resp), err } -// ValidateCoupon takes context, code, productFamilyId as parameters and -// returns an models.ApiResponse with models.CouponResponse data and -// an error if there was an issue with the request or response. -// You can verify if a specific coupon code is valid using the `validate` method. This method is useful for validating coupon codes that are entered by a customer. If the coupon is found and is valid, the coupon will be returned with a 200 status code. -// If the coupon is invalid, the status code will be 404 and the response will say why it is invalid. If the coupon is valid, the status code will be 200 and the coupon will be returned. The following reasons for invalidity are supported: -// + Coupon not found -// + Coupon is invalid -// + Coupon expired -// If you have more than one product family and if the coupon you are validating does not belong to the first product family in your site, then you will need to specify the product family, either in the url or as a query string param. This can be done by supplying the id or the handle in the `handle:my-family` format. -// Eg. -// ``` -// https://.chargify.com/product_families/handle:/coupons/validate.?code= -// ``` -// Or: -// ``` -// https://.chargify.com/coupons/validate.?code=&product_family_id= +// ValidateCoupon takes context, code, productFamilyId as parameters and +// returns an models.ApiResponse with models.CouponResponse data and +// an error if there was an issue with the request or response. +// You can verify if a specific coupon code is valid using the `validate` method. This method is useful for validating coupon codes that are entered by a customer. If the coupon is found and is valid, the coupon will be returned with a 200 status code. +// If the coupon is invalid, the status code will be 404 and the response will say why it is invalid. If the coupon is valid, the status code will be 200 and the coupon will be returned. The following reasons for invalidity are supported: +// + Coupon not found +// + Coupon is invalid +// + Coupon expired +// If you have more than one product family and if the coupon you are validating does not belong to the first product family in your site, then you will need to specify the product family, either in the url or as a query string param. This can be done by supplying the id or the handle in the `handle:my-family` format. +// Eg. +// ``` +// https://.chargify.com/product_families/handle:/coupons/validate.?code= +// ``` +// Or: +// ``` +// https://.chargify.com/coupons/validate.?code=&product_family_id= // ``` func (c *CouponsController) ValidateCoupon( - ctx context.Context, - code string, - productFamilyId *int) ( - models.ApiResponse[models.CouponResponse], - error) { - req := c.prepareRequest(ctx, "GET", "/coupons/validate.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {Message: "Not Found", Unmarshaller: errors.NewSingleStringErrorResponse}, - }) - req.QueryParam("code", code) - if productFamilyId != nil { - req.QueryParam("product_family_id", *productFamilyId) - } - var result models.CouponResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CouponResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + code string, + productFamilyId *int) ( + models.ApiResponse[models.CouponResponse], + error) { + req := c.prepareRequest(ctx, "GET", "/coupons/validate.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {Message: "Not Found", Unmarshaller: errors.NewSingleStringErrorResponse}, + }) + req.QueryParam("code", code) + if productFamilyId != nil { + req.QueryParam("product_family_id", *productFamilyId) + } + var result models.CouponResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CouponResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreateOrUpdateCouponCurrencyPrices takes context, couponId, body as parameters and -// returns an models.ApiResponse with models.CouponCurrencyResponse data and -// an error if there was an issue with the request or response. -// This endpoint allows you to create and/or update currency prices for an existing coupon. Multiple prices can be created or updated in a single request but each of the currencies must be defined on the site level already and the coupon must be an amount-based coupon, not percentage. +// CreateOrUpdateCouponCurrencyPrices takes context, couponId, body as parameters and +// returns an models.ApiResponse with models.CouponCurrencyResponse data and +// an error if there was an issue with the request or response. +// This endpoint allows you to create and/or update currency prices for an existing coupon. Multiple prices can be created or updated in a single request but each of the currencies must be defined on the site level already and the coupon must be an amount-based coupon, not percentage. // Currency pricing for coupons must mirror the setup of the primary coupon pricing - if the primary coupon is percentage based, you will not be able to define pricing in non-primary currencies. func (c *CouponsController) CreateOrUpdateCouponCurrencyPrices( - ctx context.Context, - couponId int, - body *models.CouponCurrencyRequest) ( - models.ApiResponse[models.CouponCurrencyResponse], - error) { - req := c.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/coupons/%v/currency_prices.json", couponId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.CouponCurrencyResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CouponCurrencyResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + couponId int, + body *models.CouponCurrencyRequest) ( + models.ApiResponse[models.CouponCurrencyResponse], + error) { + req := c.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/coupons/%v/currency_prices.json", couponId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.CouponCurrencyResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CouponCurrencyResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreateCouponSubcodes takes context, couponId, body as parameters and -// returns an models.ApiResponse with models.CouponSubcodesResponse data and -// an error if there was an issue with the request or response. -// ## Coupon Subcodes Intro -// Coupon Subcodes allow you to create a set of unique codes that allow you to expand the use of one coupon. -// For example: -// Master Coupon Code: -// + SPRING2020 -// Coupon Subcodes: -// + SPRING90210 -// + DP80302 -// + SPRINGBALTIMORE -// Coupon subcodes can be administered in the Admin Interface or via the API. -// When creating a coupon subcode, you must specify a coupon to attach it to using the coupon_id. Valid coupon subcodes are all capital letters, contain only letters and numbers, and do not have any spaces. Lowercase letters will be capitalized before the subcode is created. -// ## Coupon Subcodes Documentation -// Full documentation on how to create coupon subcodes in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#coupon-codes). -// Additionally, for documentation on how to apply a coupon to a Subscription within the Chargify UI, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#coupon). -// ## Create Coupon Subcode -// This request allows you to create specific subcodes underneath an existing coupon code. -// *Note*: If you are using any of the allowed special characters ("%", "@", "+", "-", "_", and "."), you must encode them for use in the URL. -// % to %25 -// @ to %40 -// + to %2B -// - to %2D -// _ to %5F -// . to %2E +// CreateCouponSubcodes takes context, couponId, body as parameters and +// returns an models.ApiResponse with models.CouponSubcodesResponse data and +// an error if there was an issue with the request or response. +// ## Coupon Subcodes Intro +// Coupon Subcodes allow you to create a set of unique codes that allow you to expand the use of one coupon. +// For example: +// Master Coupon Code: +// + SPRING2020 +// Coupon Subcodes: +// + SPRING90210 +// + DP80302 +// + SPRINGBALTIMORE +// Coupon subcodes can be administered in the Admin Interface or via the API. +// When creating a coupon subcode, you must specify a coupon to attach it to using the coupon_id. Valid coupon subcodes are all capital letters, contain only letters and numbers, and do not have any spaces. Lowercase letters will be capitalized before the subcode is created. +// ## Coupon Subcodes Documentation +// Full documentation on how to create coupon subcodes in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#coupon-codes). +// Additionally, for documentation on how to apply a coupon to a Subscription within the Chargify UI, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#coupon). +// ## Create Coupon Subcode +// This request allows you to create specific subcodes underneath an existing coupon code. +// *Note*: If you are using any of the allowed special characters ("%", "@", "+", "-", "_", and "."), you must encode them for use in the URL. +// % to %25 +// @ to %40 +// + to %2B +// - to %2D +// _ to %5F +// . to %2E // So, if the coupon subcode is `20%OFF`, the URL to delete this coupon subcode would be: `https://.chargify.com/coupons/567/codes/20%25OFF.` func (c *CouponsController) CreateCouponSubcodes( - ctx context.Context, - couponId int, - body *models.CouponSubcodes) ( - models.ApiResponse[models.CouponSubcodesResponse], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/coupons/%v/codes.json", couponId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.CouponSubcodesResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CouponSubcodesResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + couponId int, + body *models.CouponSubcodes) ( + models.ApiResponse[models.CouponSubcodesResponse], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/coupons/%v/codes.json", couponId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.CouponSubcodesResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CouponSubcodesResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListCouponSubcodes takes context, couponId, page, perPage as parameters and -// returns an models.ApiResponse with models.CouponSubcodes data and -// an error if there was an issue with the request or response. +// ListCouponSubcodesInput represents the input of the ListCouponSubcodes endpoint. +type ListCouponSubcodesInput struct { + // The Chargify id of the coupon + CouponId int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int +} + +// ListCouponSubcodes takes context, couponId, page, perPage as parameters and +// returns an models.ApiResponse with models.CouponSubcodes data and +// an error if there was an issue with the request or response. // This request allows you to request the subcodes that are attached to a coupon. func (c *CouponsController) ListCouponSubcodes( - ctx context.Context, - couponId int, - page *int, - perPage *int) ( - models.ApiResponse[models.CouponSubcodes], - error) { - req := c.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/coupons/%v/codes.json", couponId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - - var result models.CouponSubcodes - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CouponSubcodes](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListCouponSubcodesInput) ( + models.ApiResponse[models.CouponSubcodes], + error) { + req := c.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/coupons/%v/codes.json", input.CouponId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + + var result models.CouponSubcodes + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CouponSubcodes](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateCouponSubcodes takes context, couponId, body as parameters and -// returns an models.ApiResponse with models.CouponSubcodesResponse data and -// an error if there was an issue with the request or response. -// You can update the subcodes for the given Coupon via the API with a PUT request to the resource endpoint. -// Send an array of new coupon subcodes. -// **Note**: All current subcodes for that Coupon will be deleted first, and replaced with the list of subcodes sent to this endpoint. -// The response will contain: -// + The created subcodes, -// + Subcodes that were not created because they already exist, +// UpdateCouponSubcodes takes context, couponId, body as parameters and +// returns an models.ApiResponse with models.CouponSubcodesResponse data and +// an error if there was an issue with the request or response. +// You can update the subcodes for the given Coupon via the API with a PUT request to the resource endpoint. +// Send an array of new coupon subcodes. +// **Note**: All current subcodes for that Coupon will be deleted first, and replaced with the list of subcodes sent to this endpoint. +// The response will contain: +// + The created subcodes, +// + Subcodes that were not created because they already exist, // + Any subcodes not created because they are invalid. func (c *CouponsController) UpdateCouponSubcodes( - ctx context.Context, - couponId int, - body *models.CouponSubcodes) ( - models.ApiResponse[models.CouponSubcodesResponse], - error) { - req := c.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/coupons/%v/codes.json", couponId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.CouponSubcodesResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CouponSubcodesResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + couponId int, + body *models.CouponSubcodes) ( + models.ApiResponse[models.CouponSubcodesResponse], + error) { + req := c.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/coupons/%v/codes.json", couponId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.CouponSubcodesResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CouponSubcodesResponse](decoder) + return models.NewApiResponse(result, resp), err } -// DeleteCouponSubcode takes context, couponId, subcode as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// ## Example -// Given a coupon with an ID of 567, and a coupon subcode of 20OFF, the URL to `DELETE` this coupon subcode would be: -// ``` -// http://subdomain.chargify.com/coupons/567/codes/20OFF. -// ``` -// Note: If you are using any of the allowed special characters (“%”, “@”, “+”, “-”, “_”, and “.”), you must encode them for use in the URL. -// | Special character | Encoding | -// |-------------------|----------| -// | % | %25 | -// | @ | %40 | -// | + | %2B | -// | – | %2D | -// | _ | %5F | -// | . | %2E | -// ## Percent Encoding Example +// DeleteCouponSubcode takes context, couponId, subcode as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// ## Example +// Given a coupon with an ID of 567, and a coupon subcode of 20OFF, the URL to `DELETE` this coupon subcode would be: +// ``` +// http://subdomain.chargify.com/coupons/567/codes/20OFF. +// ``` +// Note: If you are using any of the allowed special characters (“%”, “@”, “+”, “-”, “_”, and “.”), you must encode them for use in the URL. +// | Special character | Encoding | +// |-------------------|----------| +// | % | %25 | +// | @ | %40 | +// | + | %2B | +// | – | %2D | +// | _ | %5F | +// | . | %2E | +// ## Percent Encoding Example // Or if the coupon subcode is 20%OFF, the URL to delete this coupon subcode would be: @https://.chargify.com/coupons/567/codes/20%25OFF. func (c *CouponsController) DeleteCouponSubcode( - ctx context.Context, - couponId int, - subcode string) ( - *http.Response, - error) { - req := c.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/coupons/%v/codes/%v.json", couponId, subcode), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + couponId int, + subcode string) ( + *http.Response, + error) { + req := c.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/coupons/%v/codes/%v.json", couponId, subcode), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } diff --git a/custom_fields_controller.go b/custom_fields_controller.go index 8c6f5de3..c758cede 100644 --- a/custom_fields_controller.go +++ b/custom_fields_controller.go @@ -1,415 +1,458 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" - "time" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" + "time" ) // CustomFieldsController represents a controller struct. type CustomFieldsController struct { - baseController + baseController } -// NewCustomFieldsController creates a new instance of CustomFieldsController. +// NewCustomFieldsController creates a new instance of CustomFieldsController. // It takes a baseController as a parameter and returns a pointer to the CustomFieldsController. func NewCustomFieldsController(baseController baseController) *CustomFieldsController { - customFieldsController := CustomFieldsController{baseController: baseController} - return &customFieldsController + customFieldsController := CustomFieldsController{baseController: baseController} + return &customFieldsController } -// CreateMetafields takes context, resourceType, body as parameters and -// returns an models.ApiResponse with []models.Metafield data and -// an error if there was an issue with the request or response. -// ## Custom Fields: Metafield Intro -// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. -// + **Metafield is the custom field** -// + **Metadata is the data populating the custom field.** -// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405332553613-Custom-Fields-Reference). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404434903181-Subscription-Summary#custom-fields) -// Metafield are the place where you will set up your resource to accept additional data. It is scoped to the site instead of a specific customer or subscription. Think of it as the key, and Metadata as the value on every record. -// ## Create Metafields -// Use this endpoint to create metafields for your Site. Metafields can be populated with metadata after the fact. -// Each site is limited to 100 unique Metafields (i.e. keys, or names) per resource. This means you can have 100 Metafields for Subscription and another 100 for Customer. -// ### Metafields "On-the-Fly" -// It is possible to create Metafields “on the fly” when you create your Metadata – if a non-existant name is passed when creating Metadata, a Metafield for that key will be automatically created. The Metafield API, however, gives you more control over your “keys”. -// ### Metafield Scope Warning +// CreateMetafields takes context, resourceType, body as parameters and +// returns an models.ApiResponse with []models.Metafield data and +// an error if there was an issue with the request or response. +// ## Custom Fields: Metafield Intro +// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. +// + **Metafield is the custom field** +// + **Metadata is the data populating the custom field.** +// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405332553613-Custom-Fields-Reference). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404434903181-Subscription-Summary#custom-fields) +// Metafield are the place where you will set up your resource to accept additional data. It is scoped to the site instead of a specific customer or subscription. Think of it as the key, and Metadata as the value on every record. +// ## Create Metafields +// Use this endpoint to create metafields for your Site. Metafields can be populated with metadata after the fact. +// Each site is limited to 100 unique Metafields (i.e. keys, or names) per resource. This means you can have 100 Metafields for Subscription and another 100 for Customer. +// ### Metafields "On-the-Fly" +// It is possible to create Metafields “on the fly” when you create your Metadata – if a non-existant name is passed when creating Metadata, a Metafield for that key will be automatically created. The Metafield API, however, gives you more control over your “keys”. +// ### Metafield Scope Warning // If configuring metafields in the Admin UI or via the API, be careful sending updates to metafields with the scope attribute – **if a partial update is sent it will overwrite the current configuration**. func (c *CustomFieldsController) CreateMetafields( - ctx context.Context, - resourceType models.ResourceType, - body *models.CreateMetafieldsRequest) ( - models.ApiResponse[[]models.Metafield], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/%v/metafields.json", resourceType), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result []models.Metafield - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.Metafield](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + resourceType models.ResourceType, + body *models.CreateMetafieldsRequest) ( + models.ApiResponse[[]models.Metafield], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/%v/metafields.json", resourceType), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result []models.Metafield + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.Metafield](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListMetafieldsInput represents the input of the ListMetafields endpoint. +type ListMetafieldsInput struct { + // the resource type to which the metafields belong + ResourceType models.ResourceType + // filter by the name of the metafield + Name *string + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // Controls the order in which results are returned. + // Use in query `direction=asc`. + Direction *models.SortingDirection } -// ListMetafields takes context, resourceType, name, page, perPage, direction as parameters and -// returns an models.ApiResponse with models.ListMetafieldsResponse data and -// an error if there was an issue with the request or response. +// ListMetafields takes context, resourceType, name, page, perPage, direction as parameters and +// returns an models.ApiResponse with models.ListMetafieldsResponse data and +// an error if there was an issue with the request or response. // This endpoint lists metafields associated with a site. The metafield description and usage is contained in the response. func (c *CustomFieldsController) ListMetafields( - ctx context.Context, - resourceType models.ResourceType, - name *string, - page *int, - perPage *int, - direction *models.SortingDirection) ( - models.ApiResponse[models.ListMetafieldsResponse], - error) { - req := c.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/%v/metafields.json", resourceType), - ) - req.Authenticate(NewAuth("BasicAuth")) - if name != nil { - req.QueryParam("name", *name) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - - var result models.ListMetafieldsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListMetafieldsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListMetafieldsInput) ( + models.ApiResponse[models.ListMetafieldsResponse], + error) { + req := c.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/%v/metafields.json", input.ResourceType), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.Name != nil { + req.QueryParam("name", *input.Name) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + + var result models.ListMetafieldsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListMetafieldsResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateMetafield takes context, resourceType, body as parameters and -// returns an models.ApiResponse with []models.Metafield data and -// an error if there was an issue with the request or response. +// UpdateMetafield takes context, resourceType, body as parameters and +// returns an models.ApiResponse with []models.Metafield data and +// an error if there was an issue with the request or response. // Use the following method to update metafields for your Site. Metafields can be populated with metadata after the fact. func (c *CustomFieldsController) UpdateMetafield( - ctx context.Context, - resourceType models.ResourceType, - body *models.UpdateMetafieldsRequest) ( - models.ApiResponse[[]models.Metafield], - error) { - req := c.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/%v/metafields.json", resourceType), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result []models.Metafield - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.Metafield](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + resourceType models.ResourceType, + body *models.UpdateMetafieldsRequest) ( + models.ApiResponse[[]models.Metafield], + error) { + req := c.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/%v/metafields.json", resourceType), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result []models.Metafield + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.Metafield](decoder) + return models.NewApiResponse(result, resp), err } -// DeleteMetafield takes context, resourceType, name as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// Use the following method to delete a metafield. This will remove the metafield from the Site. +// DeleteMetafield takes context, resourceType, name as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// Use the following method to delete a metafield. This will remove the metafield from the Site. // Additionally, this will remove the metafield and associated metadata with all Subscriptions on the Site. func (c *CustomFieldsController) DeleteMetafield( - ctx context.Context, - resourceType models.ResourceType, - name *string) ( - *http.Response, - error) { - req := c.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/%v/metafields.json", resourceType), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - if name != nil { - req.QueryParam("name", *name) - } - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + resourceType models.ResourceType, + name *string) ( + *http.Response, + error) { + req := c.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/%v/metafields.json", resourceType), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + if name != nil { + req.QueryParam("name", *name) + } + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// CreateMetadata takes context, resourceType, resourceId, body as parameters and -// returns an models.ApiResponse with []models.Metadata data and -// an error if there was an issue with the request or response. -// ## Custom Fields: Metadata Intro -// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. -// + **Metafield is the custom field** -// + **Metadata is the data populating the custom field.** -// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407659856411). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#custom-fields) -// Metadata is associated to a customer or subscription, and corresponds to a Metafield. When creating a new metadata object for a given record, **if the metafield is not present it will be created**. -// ## Metadata limits -// Metadata values are limited to 2kB in size. Additonally, there are limits on the number of unique metafields available per resource. -// ## Create Metadata -// This method will create a metafield for the site on the fly if it does not already exist, and populate the metadata value. -// ### Subscription or Customer Resource +// CreateMetadata takes context, resourceType, resourceId, body as parameters and +// returns an models.ApiResponse with []models.Metadata data and +// an error if there was an issue with the request or response. +// ## Custom Fields: Metadata Intro +// **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. +// + **Metafield is the custom field** +// + **Metadata is the data populating the custom field.** +// Chargify Metafields are used to add meaningful attributes to subscription and customer resources. Full documentation on how to create Custom Fields in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407659856411). For additional documentation on how to record data within custom fields, please see our subscription-based documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#custom-fields) +// Metadata is associated to a customer or subscription, and corresponds to a Metafield. When creating a new metadata object for a given record, **if the metafield is not present it will be created**. +// ## Metadata limits +// Metadata values are limited to 2kB in size. Additonally, there are limits on the number of unique metafields available per resource. +// ## Create Metadata +// This method will create a metafield for the site on the fly if it does not already exist, and populate the metadata value. +// ### Subscription or Customer Resource // Please pay special attention to the resource you use when creating metadata. func (c *CustomFieldsController) CreateMetadata( - ctx context.Context, - resourceType models.ResourceType, - resourceId int, - body *models.CreateMetadataRequest) ( - models.ApiResponse[[]models.Metadata], - error) { - req := c.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/%v/%v/metadata.json", resourceType, resourceId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result []models.Metadata - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.Metadata](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + resourceType models.ResourceType, + resourceId int, + body *models.CreateMetadataRequest) ( + models.ApiResponse[[]models.Metadata], + error) { + req := c.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/%v/%v/metadata.json", resourceType, resourceId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result []models.Metadata + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.Metadata](decoder) + return models.NewApiResponse(result, resp), err } -// ListMetadata takes context, resourceType, resourceId, page, perPage as parameters and -// returns an models.ApiResponse with models.PaginatedMetadata data and -// an error if there was an issue with the request or response. -// This request will list all of the metadata belonging to a particular resource (ie. subscription, customer) that is specified. -// ## Metadata Data +// ListMetadataInput represents the input of the ListMetadata endpoint. +type ListMetadataInput struct { + // the resource type to which the metafields belong + ResourceType models.ResourceType + // The Chargify id of the customer or the subscription for which the metadata applies + ResourceId int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int +} + +// ListMetadata takes context, resourceType, resourceId, page, perPage as parameters and +// returns an models.ApiResponse with models.PaginatedMetadata data and +// an error if there was an issue with the request or response. +// This request will list all of the metadata belonging to a particular resource (ie. subscription, customer) that is specified. +// ## Metadata Data // This endpoint will also display the current stats of your metadata to use as a tool for pagination. func (c *CustomFieldsController) ListMetadata( - ctx context.Context, - resourceType models.ResourceType, - resourceId int, - page *int, - perPage *int) ( - models.ApiResponse[models.PaginatedMetadata], - error) { - req := c.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/%v/%v/metadata.json", resourceType, resourceId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - - var result models.PaginatedMetadata - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.PaginatedMetadata](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListMetadataInput) ( + models.ApiResponse[models.PaginatedMetadata], + error) { + req := c.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/%v/%v/metadata.json", input.ResourceType, input.ResourceId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParamWithArraySerializationOption("page", *input.Page, https.Plain) + } + if input.PerPage != nil { + req.QueryParamWithArraySerializationOption("per_page", *input.PerPage, https.Plain) + } + + var result models.PaginatedMetadata + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.PaginatedMetadata](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateMetadata takes context, resourceType, resourceId, body as parameters and -// returns an models.ApiResponse with []models.Metadata data and -// an error if there was an issue with the request or response. +// UpdateMetadata takes context, resourceType, resourceId, body as parameters and +// returns an models.ApiResponse with []models.Metadata data and +// an error if there was an issue with the request or response. // This method allows you to update the existing metadata associated with a subscription or customer. func (c *CustomFieldsController) UpdateMetadata( - ctx context.Context, - resourceType models.ResourceType, - resourceId int, - body *models.UpdateMetadataRequest) ( - models.ApiResponse[[]models.Metadata], - error) { - req := c.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/%v/%v/metadata.json", resourceType, resourceId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result []models.Metadata - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.Metadata](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + resourceType models.ResourceType, + resourceId int, + body *models.UpdateMetadataRequest) ( + models.ApiResponse[[]models.Metadata], + error) { + req := c.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/%v/%v/metadata.json", resourceType, resourceId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result []models.Metadata + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.Metadata](decoder) + return models.NewApiResponse(result, resp), err } -// DeleteMetadata takes context, resourceType, resourceId, name, names as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// This method removes the metadata from the subscriber/customer cited. -// ## Query String Usage -// For instance if you wanted to delete the metadata for customer 99 named weight you would request: -// ``` -// https://acme.chargify.com/customers/99/metadata.json?name=weight -// ``` -// If you want to delete multiple metadata fields for a customer 99 named: `weight` and `age` you wrould request: -// ``` -// https://acme.chargify.com/customers/99/metadata.json?names[]=weight&names[]=age -// ``` -// ## Successful Response -// For a success, there will be a code `200` and the plain text response `true`. -// ## Unsuccessful Response +// DeleteMetadata takes context, resourceType, resourceId, name, names as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// This method removes the metadata from the subscriber/customer cited. +// ## Query String Usage +// For instance if you wanted to delete the metadata for customer 99 named weight you would request: +// ``` +// https://acme.chargify.com/customers/99/metadata.json?name=weight +// ``` +// If you want to delete multiple metadata fields for a customer 99 named: `weight` and `age` you wrould request: +// ``` +// https://acme.chargify.com/customers/99/metadata.json?names[]=weight&names[]=age +// ``` +// ## Successful Response +// For a success, there will be a code `200` and the plain text response `true`. +// ## Unsuccessful Response // When a failed response is encountered, you will receive a `404` response and the plain text response of `true`. func (c *CustomFieldsController) DeleteMetadata( - ctx context.Context, - resourceType models.ResourceType, - resourceId int, - name *string, - names []string) ( - *http.Response, - error) { - req := c.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/%v/%v/metadata.json", resourceType, resourceId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - if name != nil { - req.QueryParam("name", *name) - } - if names != nil { - req.QueryParam("names[]", names) - } - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + resourceType models.ResourceType, + resourceId int, + name *string, + names []string) ( + *http.Response, + error) { + req := c.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/%v/%v/metadata.json", resourceType, resourceId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + if name != nil { + req.QueryParamWithArraySerializationOption("name", *name, https.Plain) + } + if names != nil { + req.QueryParamWithArraySerializationOption("names[]", names, https.Plain) + } + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// ListMetadataForResourceType takes context, resourceType, page, perPage, dateField, startDate, endDate, startDatetime, endDatetime, withDeleted, resourceIds, direction as parameters and -// returns an models.ApiResponse with models.PaginatedMetadata data and -// an error if there was an issue with the request or response. -// This method will provide you information on usage of metadata across your selected resource (ie. subscriptions, customers) -// ## Metadata Data -// This endpoint will also display the current stats of your metadata to use as a tool for pagination. -// ### Metadata for multiple records -// `https://acme.chargify.com/subscriptions/metadata.json?resource_ids[]=1&resource_ids[]=2` -// ## Read Metadata for a Site +// ListMetadataForResourceTypeInput represents the input of the ListMetadataForResourceType endpoint. +type ListMetadataForResourceTypeInput struct { + // the resource type to which the metafields belong + ResourceType models.ResourceType + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The type of filter you would like to apply to your search. + DateField *models.BasicDateField + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns metadata with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + StartDate *time.Time + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns metadata with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + EndDate *time.Time + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns metadata with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. + StartDatetime *time.Time + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns metadata with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. + EndDatetime *time.Time + // Allow to fetch deleted metadata. + WithDeleted *bool + // Allow to fetch metadata for multiple records based on provided ids. Use in query: `resource_ids[]=122&resource_ids[]=123&resource_ids[]=124`. + ResourceIds []int + // Controls the order in which results are returned. + // Use in query `direction=asc`. + Direction *models.SortingDirection +} + +// ListMetadataForResourceType takes context, resourceType, page, perPage, dateField, startDate, endDate, startDatetime, endDatetime, withDeleted, resourceIds, direction as parameters and +// returns an models.ApiResponse with models.PaginatedMetadata data and +// an error if there was an issue with the request or response. +// This method will provide you information on usage of metadata across your selected resource (ie. subscriptions, customers) +// ## Metadata Data +// This endpoint will also display the current stats of your metadata to use as a tool for pagination. +// ### Metadata for multiple records +// `https://acme.chargify.com/subscriptions/metadata.json?resource_ids[]=1&resource_ids[]=2` +// ## Read Metadata for a Site // This endpoint will list the number of pages of metadata information that are contained within a site. func (c *CustomFieldsController) ListMetadataForResourceType( - ctx context.Context, - resourceType models.ResourceType, - page *int, - perPage *int, - dateField *models.BasicDateField, - startDate *time.Time, - endDate *time.Time, - startDatetime *time.Time, - endDatetime *time.Time, - withDeleted *bool, - resourceIds []int, - direction *models.SortingDirection) ( - models.ApiResponse[models.PaginatedMetadata], - error) { - req := c.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/%v/metadata.json", resourceType), - ) - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if startDate != nil { - req.QueryParam("start_date", startDate.Format(models.DEFAULT_DATE)) - } - if endDate != nil { - req.QueryParam("end_date", endDate.Format(models.DEFAULT_DATE)) - } - if startDatetime != nil { - req.QueryParam("start_datetime", startDatetime.Format(time.RFC3339)) - } - if endDatetime != nil { - req.QueryParam("end_datetime", endDatetime.Format(time.RFC3339)) - } - if withDeleted != nil { - req.QueryParam("with_deleted", *withDeleted) - } - if resourceIds != nil { - req.QueryParam("resource_ids[]", resourceIds) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - - var result models.PaginatedMetadata - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.PaginatedMetadata](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListMetadataForResourceTypeInput) ( + models.ApiResponse[models.PaginatedMetadata], + error) { + req := c.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/%v/metadata.json", input.ResourceType), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.StartDate != nil { + req.QueryParam("start_date", input.StartDate.Format(models.DEFAULT_DATE)) + } + if input.EndDate != nil { + req.QueryParam("end_date", input.EndDate.Format(models.DEFAULT_DATE)) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", input.StartDatetime.Format(time.RFC3339)) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", input.EndDatetime.Format(time.RFC3339)) + } + if input.WithDeleted != nil { + req.QueryParam("with_deleted", *input.WithDeleted) + } + if input.ResourceIds != nil { + req.QueryParam("resource_ids[]", input.ResourceIds) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + + var result models.PaginatedMetadata + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.PaginatedMetadata](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/customers_controller.go b/customers_controller.go index 31082c85..f4e80a87 100644 --- a/customers_controller.go +++ b/customers_controller.go @@ -1,248 +1,265 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" ) // CustomersController represents a controller struct. type CustomersController struct { - baseController + baseController } -// NewCustomersController creates a new instance of CustomersController. +// NewCustomersController creates a new instance of CustomersController. // It takes a baseController as a parameter and returns a pointer to the CustomersController. func NewCustomersController(baseController baseController) *CustomersController { - customersController := CustomersController{baseController: baseController} - return &customersController + customersController := CustomersController{baseController: baseController} + return &customersController } -// CreateCustomer takes context, body as parameters and -// returns an models.ApiResponse with models.CustomerResponse data and -// an error if there was an issue with the request or response. -// You may create a new Customer at any time, or you may create a Customer at the same time you create a Subscription. The only validation restriction is that you may only create one customer for a given reference value. -// If provided, the `reference` value must be unique. It represents a unique identifier for the customer from your own app, i.e. the customer’s ID. This allows you to retrieve a given customer via a piece of shared information. Alternatively, you may choose to leave `reference` blank, and store Chargify’s unique ID for the customer, which is in the `id` attribute. -// Full documentation on how to locate, create and edit Customers in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407659914267). -// ## Required Country Format -// Chargify requires that you use the ISO Standard Country codes when formatting country attribute of the customer. -// Countries should be formatted as 2 characters. For more information, please see the following wikipedia article on [ISO_3166-1.](http://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) -// ## Required State Format -// Chargify requires that you use the ISO Standard State codes when formatting state attribute of the customer. -// + US States (2 characters): [ISO_3166-2](https://en.wikipedia.org/wiki/ISO_3166-2:US) -// + States Outside the US (2-3 characters): To find the correct state codes outside of the US, please go to [ISO_3166-1](http://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) and click on the link in the “ISO 3166-2 codes” column next to country you wish to populate. -// ## Locale -// Chargify allows you to attribute a language/region to your customer to deliver invoices in any required language. +// CreateCustomer takes context, body as parameters and +// returns an models.ApiResponse with models.CustomerResponse data and +// an error if there was an issue with the request or response. +// You may create a new Customer at any time, or you may create a Customer at the same time you create a Subscription. The only validation restriction is that you may only create one customer for a given reference value. +// If provided, the `reference` value must be unique. It represents a unique identifier for the customer from your own app, i.e. the customer’s ID. This allows you to retrieve a given customer via a piece of shared information. Alternatively, you may choose to leave `reference` blank, and store Chargify’s unique ID for the customer, which is in the `id` attribute. +// Full documentation on how to locate, create and edit Customers in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407659914267). +// ## Required Country Format +// Chargify requires that you use the ISO Standard Country codes when formatting country attribute of the customer. +// Countries should be formatted as 2 characters. For more information, please see the following wikipedia article on [ISO_3166-1.](http://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) +// ## Required State Format +// Chargify requires that you use the ISO Standard State codes when formatting state attribute of the customer. +// + US States (2 characters): [ISO_3166-2](https://en.wikipedia.org/wiki/ISO_3166-2:US) +// + States Outside the US (2-3 characters): To find the correct state codes outside of the US, please go to [ISO_3166-1](http://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) and click on the link in the “ISO 3166-2 codes” column next to country you wish to populate. +// ## Locale +// Chargify allows you to attribute a language/region to your customer to deliver invoices in any required language. // For more: [Customer Locale](https://chargify.zendesk.com/hc/en-us/articles/4407870384283#customer-locale) func (c *CustomersController) CreateCustomer( - ctx context.Context, - body *models.CreateCustomerRequest) ( - models.ApiResponse[models.CustomerResponse], - error) { - req := c.prepareRequest(ctx, "POST", "/customers.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewCustomerErrorResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.CustomerResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CustomerResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.CreateCustomerRequest) ( + models.ApiResponse[models.CustomerResponse], + error) { + req := c.prepareRequest(ctx, "POST", "/customers.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewCustomerErrorResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.CustomerResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CustomerResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListCustomersInput represents the input of the ListCustomers endpoint. +type ListCustomersInput struct { + // Direction to sort customers by time of creation + Direction *models.SortingDirection + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 50. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The type of filter you would like to apply to your search. + // Use in query: `date_field=created_at`. + DateField *models.BasicDateField + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + StartDate *string + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + EndDate *string + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. + StartDatetime *string + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. + EndDatetime *string + // A search query by which to filter customers (can be an email, an ID, a reference, organization) + Q *string } -// ListCustomers takes context, direction, page, perPage, dateField, startDate, endDate, startDatetime, endDatetime, q as parameters and -// returns an models.ApiResponse with []models.CustomerResponse data and -// an error if there was an issue with the request or response. -// This request will by default list all customers associated with your Site. -// ## Find Customer -// Use the search feature with the `q` query parameter to retrieve an array of customers that matches the search query. -// Common use cases are: -// + Search by an email -// + Search by a Chargify ID -// + Search by an organization -// + Search by a reference value from your application -// + Search by a first or last name +// ListCustomers takes context, direction, page, perPage, dateField, startDate, endDate, startDatetime, endDatetime, q as parameters and +// returns an models.ApiResponse with []models.CustomerResponse data and +// an error if there was an issue with the request or response. +// This request will by default list all customers associated with your Site. +// ## Find Customer +// Use the search feature with the `q` query parameter to retrieve an array of customers that matches the search query. +// Common use cases are: +// + Search by an email +// + Search by a Chargify ID +// + Search by an organization +// + Search by a reference value from your application +// + Search by a first or last name // To retrieve a single, exact match by reference, please use the [lookup endpoint](https://developers.chargify.com/docs/api-docs/b710d8fbef104-read-customer-by-reference). func (c *CustomersController) ListCustomers( - ctx context.Context, - direction *models.SortingDirection, - page *int, - perPage *int, - dateField *models.BasicDateField, - startDate *string, - endDate *string, - startDatetime *string, - endDatetime *string, - q *string) ( - models.ApiResponse[[]models.CustomerResponse], - error) { - req := c.prepareRequest(ctx, "GET", "/customers.json") - req.Authenticate(NewAuth("BasicAuth")) - if direction != nil { - req.QueryParam("direction", *direction) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if startDate != nil { - req.QueryParam("start_date", *startDate) - } - if endDate != nil { - req.QueryParam("end_date", *endDate) - } - if startDatetime != nil { - req.QueryParam("start_datetime", *startDatetime) - } - if endDatetime != nil { - req.QueryParam("end_datetime", *endDatetime) - } - if q != nil { - req.QueryParam("q", *q) - } - var result []models.CustomerResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.CustomerResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListCustomersInput) ( + models.ApiResponse[[]models.CustomerResponse], + error) { + req := c.prepareRequest(ctx, "GET", "/customers.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.StartDate != nil { + req.QueryParam("start_date", *input.StartDate) + } + if input.EndDate != nil { + req.QueryParam("end_date", *input.EndDate) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", *input.StartDatetime) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", *input.EndDatetime) + } + if input.Q != nil { + req.QueryParam("q", *input.Q) + } + var result []models.CustomerResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.CustomerResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadCustomer takes context, id as parameters and -// returns an models.ApiResponse with models.CustomerResponse data and -// an error if there was an issue with the request or response. +// ReadCustomer takes context, id as parameters and +// returns an models.ApiResponse with models.CustomerResponse data and +// an error if there was an issue with the request or response. // This method allows to retrieve the Customer properties by Chargify-generated Customer ID. func (c *CustomersController) ReadCustomer( - ctx context.Context, - id int) ( - models.ApiResponse[models.CustomerResponse], - error) { - req := c.prepareRequest(ctx, "GET", fmt.Sprintf("/customers/%v.json", id)) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.CustomerResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CustomerResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + id int) ( + models.ApiResponse[models.CustomerResponse], + error) { + req := c.prepareRequest(ctx, "GET", fmt.Sprintf("/customers/%v.json", id)) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.CustomerResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CustomerResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateCustomer takes context, id, body as parameters and -// returns an models.ApiResponse with models.CustomerResponse data and -// an error if there was an issue with the request or response. +// UpdateCustomer takes context, id, body as parameters and +// returns an models.ApiResponse with models.CustomerResponse data and +// an error if there was an issue with the request or response. // This method allows to update the Customer. func (c *CustomersController) UpdateCustomer( - ctx context.Context, - id int, - body *models.UpdateCustomerRequest) ( - models.ApiResponse[models.CustomerResponse], - error) { - req := c.prepareRequest(ctx, "PUT", fmt.Sprintf("/customers/%v.json", id)) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewCustomerErrorResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.CustomerResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CustomerResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + id int, + body *models.UpdateCustomerRequest) ( + models.ApiResponse[models.CustomerResponse], + error) { + req := c.prepareRequest(ctx, "PUT", fmt.Sprintf("/customers/%v.json", id)) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewCustomerErrorResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.CustomerResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CustomerResponse](decoder) + return models.NewApiResponse(result, resp), err } -// DeleteCustomer takes context, id as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. +// DeleteCustomer takes context, id as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. // This method allows you to delete the Customer. func (c *CustomersController) DeleteCustomer( - ctx context.Context, - id int) ( - *http.Response, - error) { - req := c.prepareRequest(ctx, "DELETE", fmt.Sprintf("/customers/%v.json", id)) - req.Authenticate(NewAuth("BasicAuth")) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + id int) ( + *http.Response, + error) { + req := c.prepareRequest(ctx, "DELETE", fmt.Sprintf("/customers/%v.json", id)) + req.Authenticate(NewAuth("BasicAuth")) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// ReadCustomerByReference takes context, reference as parameters and -// returns an models.ApiResponse with models.CustomerResponse data and -// an error if there was an issue with the request or response. +// ReadCustomerByReference takes context, reference as parameters and +// returns an models.ApiResponse with models.CustomerResponse data and +// an error if there was an issue with the request or response. // Use this method to return the customer object if you have the unique **Reference ID (Your App)** value handy. It will return a single match. func (c *CustomersController) ReadCustomerByReference( - ctx context.Context, - reference string) ( - models.ApiResponse[models.CustomerResponse], - error) { - req := c.prepareRequest(ctx, "GET", "/customers/lookup.json") - req.Authenticate(NewAuth("BasicAuth")) - req.QueryParam("reference", reference) - var result models.CustomerResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CustomerResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + reference string) ( + models.ApiResponse[models.CustomerResponse], + error) { + req := c.prepareRequest(ctx, "GET", "/customers/lookup.json") + req.Authenticate(NewAuth("BasicAuth")) + req.QueryParam("reference", reference) + var result models.CustomerResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CustomerResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListCustomerSubscriptions takes context, customerId as parameters and -// returns an models.ApiResponse with []models.SubscriptionResponse data and -// an error if there was an issue with the request or response. +// ListCustomerSubscriptions takes context, customerId as parameters and +// returns an models.ApiResponse with []models.SubscriptionResponse data and +// an error if there was an issue with the request or response. // This method lists all subscriptions that belong to a customer. func (c *CustomersController) ListCustomerSubscriptions( - ctx context.Context, - customerId int) ( - models.ApiResponse[[]models.SubscriptionResponse], - error) { - req := c.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/customers/%v/subscriptions.json", customerId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result []models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + customerId int) ( + models.ApiResponse[[]models.SubscriptionResponse], + error) { + req := c.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/customers/%v/subscriptions.json", customerId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result []models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/doc/auth/basic-authentication.md b/doc/auth/basic-authentication.md index 1af5e78e..2328c370 100644 --- a/doc/auth/basic-authentication.md +++ b/doc/auth/basic-authentication.md @@ -1,28 +1,28 @@ - -# Basic Authentication - - - -Documentation for accessing and setting credentials for BasicAuth. - -## Auth Credentials - -| Name | Type | Description | Setter | Getter | -| --- | --- | --- | --- | --- | -| Username | `string` | The username to use with basic authentication | `WithUsername` | `Username` | -| Password | `string` | The password to use with basic authentication | `WithPassword` | `Password` | - - - -**Note:** Required auth credentials can be set using `WithBasicAuthCredentials()` by providing a credentials instance with `NewBasicAuthCredentials()` in the configuration initialization and accessed using the `BasicAuthCredentials()` method in the configuration instance. - -## Usage Example - -### Client Initialization - -You must provide credentials in the client as shown in the following code snippet. - -```go + +# Basic Authentication + + + +Documentation for accessing and setting credentials for BasicAuth. + +## Auth Credentials + +| Name | Type | Description | Setter | Getter | +| --- | --- | --- | --- | --- | +| Username | `string` | The username to use with basic authentication | `WithUsername` | `Username` | +| Password | `string` | The password to use with basic authentication | `WithPassword` | `Password` | + + + +**Note:** Required auth credentials can be set using `WithBasicAuthCredentials()` by providing a credentials instance with `NewBasicAuthCredentials()` in the configuration initialization and accessed using the `BasicAuthCredentials()` method in the configuration instance. + +## Usage Example + +### Client Initialization + +You must provide credentials in the client as shown in the following code snippet. + +```go client := advancedbilling.NewClient( advancedbilling.CreateConfiguration( advancedbilling.WithBasicAuthCredentials( @@ -32,7 +32,7 @@ client := advancedbilling.NewClient( ), ), ), -) -``` - - +) +``` + + diff --git a/doc/client.md b/doc/client.md index a70910f9..a9e5ea0a 100644 --- a/doc/client.md +++ b/doc/client.md @@ -1,19 +1,19 @@ - -# Client Class Documentation - -The following parameters are configurable for the API Client: - -| Parameter | Type | Description | -| --- | --- | --- | -| `subdomain` | `string` | The subdomain for your Chargify site.
*Default*: `"subdomain"` | -| `domain` | `string` | The Chargify server domain.
*Default*: `"chargify.com"` | -| `environment` | `Environment` | The API environment.
**Default: `Environment.PRODUCTION`** | -| `httpConfiguration` | [`HttpConfiguration`](http-configuration.md) | Configurable http client options like timeout and retries. | -| `basicAuthCredentials` | [`BasicAuthCredentials`](auth/basic-authentication.md) | The Credentials Setter for Basic Authentication | - -The API client can be initialized as follows: - -```go + +# Client Class Documentation + +The following parameters are configurable for the API Client: + +| Parameter | Type | Description | +| --- | --- | --- | +| `subdomain` | `string` | The subdomain for your Chargify site.
*Default*: `"subdomain"` | +| `domain` | `string` | The Chargify server domain.
*Default*: `"chargify.com"` | +| `environment` | `Environment` | The API environment.
**Default: `Environment.PRODUCTION`** | +| `httpConfiguration` | [`HttpConfiguration`](http-configuration.md) | Configurable http client options like timeout and retries. | +| `basicAuthCredentials` | [`BasicAuthCredentials`](auth/basic-authentication.md) | The Credentials Setter for Basic Authentication | + +The API client can be initialized as follows: + +```go client := advancedbilling.NewClient( advancedbilling.CreateConfiguration( advancedbilling.WithHttpConfiguration( @@ -29,46 +29,46 @@ client := advancedbilling.NewClient( ), ), ), -) -``` - -## Maxio Advanced Billing Client - -The gateway for the SDK. This class acts as a factory for the Controllers and also holds the configuration of the SDK. - -## Controllers - -| Name | Description | -| --- | --- | -| aPIExports | Gets APIExportsController | -| advanceInvoice | Gets AdvanceInvoiceController | -| billingPortal | Gets BillingPortalController | -| coupons | Gets CouponsController | -| components | Gets ComponentsController | -| customers | Gets CustomersController | -| customFields | Gets CustomFieldsController | -| events | Gets EventsController | -| eventsBasedBillingSegments | Gets EventsBasedBillingSegmentsController | -| insights | Gets InsightsController | -| invoices | Gets InvoicesController | -| offers | Gets OffersController | -| paymentProfiles | Gets PaymentProfilesController | -| productFamilies | Gets ProductFamiliesController | -| products | Gets ProductsController | -| productPricePoints | Gets ProductPricePointsController | -| proformaInvoices | Gets ProformaInvoicesController | -| reasonCodes | Gets ReasonCodesController | -| referralCodes | Gets ReferralCodesController | -| salesCommissions | Gets SalesCommissionsController | -| sites | Gets SitesController | -| subscriptions | Gets SubscriptionsController | -| subscriptionComponents | Gets SubscriptionComponentsController | -| subscriptionGroups | Gets SubscriptionGroupsController | -| subscriptionGroupInvoiceAccount | Gets SubscriptionGroupInvoiceAccountController | -| subscriptionGroupStatus | Gets SubscriptionGroupStatusController | -| subscriptionInvoiceAccount | Gets SubscriptionInvoiceAccountController | -| subscriptionNotes | Gets SubscriptionNotesController | -| subscriptionProducts | Gets SubscriptionProductsController | -| subscriptionStatus | Gets SubscriptionStatusController | -| webhooks | Gets WebhooksController | - +) +``` + +## Maxio Advanced Billing Client + +The gateway for the SDK. This class acts as a factory for the Controllers and also holds the configuration of the SDK. + +## Controllers + +| Name | Description | +| --- | --- | +| aPIExports | Gets APIExportsController | +| advanceInvoice | Gets AdvanceInvoiceController | +| billingPortal | Gets BillingPortalController | +| coupons | Gets CouponsController | +| components | Gets ComponentsController | +| customers | Gets CustomersController | +| customFields | Gets CustomFieldsController | +| events | Gets EventsController | +| eventsBasedBillingSegments | Gets EventsBasedBillingSegmentsController | +| insights | Gets InsightsController | +| invoices | Gets InvoicesController | +| offers | Gets OffersController | +| paymentProfiles | Gets PaymentProfilesController | +| productFamilies | Gets ProductFamiliesController | +| products | Gets ProductsController | +| productPricePoints | Gets ProductPricePointsController | +| proformaInvoices | Gets ProformaInvoicesController | +| reasonCodes | Gets ReasonCodesController | +| referralCodes | Gets ReferralCodesController | +| salesCommissions | Gets SalesCommissionsController | +| sites | Gets SitesController | +| subscriptions | Gets SubscriptionsController | +| subscriptionComponents | Gets SubscriptionComponentsController | +| subscriptionGroups | Gets SubscriptionGroupsController | +| subscriptionGroupInvoiceAccount | Gets SubscriptionGroupInvoiceAccountController | +| subscriptionGroupStatus | Gets SubscriptionGroupStatusController | +| subscriptionInvoiceAccount | Gets SubscriptionInvoiceAccountController | +| subscriptionNotes | Gets SubscriptionNotesController | +| subscriptionProducts | Gets SubscriptionProductsController | +| subscriptionStatus | Gets SubscriptionStatusController | +| webhooks | Gets WebhooksController | + diff --git a/doc/controllers/advance-invoice.md b/doc/controllers/advance-invoice.md index 3d5f7632..c4162fd3 100644 --- a/doc/controllers/advance-invoice.md +++ b/doc/controllers/advance-invoice.md @@ -1,50 +1,50 @@ -# Advance Invoice - -```go -advanceInvoiceController := client.AdvanceInvoiceController() -``` - -## Class Name - -`AdvanceInvoiceController` - -## Methods - +# Advance Invoice + +```go +advanceInvoiceController := client.AdvanceInvoiceController() +``` + +## Class Name + +`AdvanceInvoiceController` + +## Methods + * [Issue Advance Invoice](../../doc/controllers/advance-invoice.md#issue-advance-invoice) * [Read Advance Invoice](../../doc/controllers/advance-invoice.md#read-advance-invoice) -* [Void Advance Invoice](../../doc/controllers/advance-invoice.md#void-advance-invoice) - - -# Issue Advance Invoice - -Generate an invoice in advance for a subscription's next renewal date. [Please see our docs](reference/Chargify-API.v1.yaml/components/schemas/Invoice) for more information on advance invoices, including eligibility on generating one; for the most part, they function like any other invoice, except they are issued early and have special behavior upon being voided. +* [Void Advance Invoice](../../doc/controllers/advance-invoice.md#void-advance-invoice) + + +# Issue Advance Invoice + +Generate an invoice in advance for a subscription's next renewal date. [Please see our docs](../../doc/models/invoice.md) for more information on advance invoices, including eligibility on generating one; for the most part, they function like any other invoice, except they are issued early and have special behavior upon being voided. A subscription may only have one advance invoice per billing period. Attempting to issue an advance invoice when one already exists will return an error. That said, regeneration of the invoice may be forced with the params `force: true`, which will void an advance invoice if one exists and generate a new one. If no advance invoice exists, a new one will be generated. -We recommend using either the create or preview endpoints for proforma invoices to preview this advance invoice before using this endpoint to generate it. - -```go -IssueAdvanceInvoice( - ctx context.Context, - subscriptionId int, +We recommend using either the create or preview endpoints for proforma invoices to preview this advance invoice before using this endpoint to generate it. + +```go +IssueAdvanceInvoice( + ctx context.Context, + subscriptionId int, body *models.IssueAdvanceInvoiceRequest) ( models.ApiResponse[models.Invoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.IssueAdvanceInvoiceRequest`](../../doc/models/issue-advance-invoice-request.md) | Body, Optional | - | - -## Response Type - -[`models.Invoice`](../../doc/models/invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.IssueAdvanceInvoiceRequest`](../../doc/models/issue-advance-invoice-request.md) | Body, Optional | - | + +## Response Type + +[`models.Invoice`](../../doc/models/invoice.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -59,42 +59,42 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Read Advance Invoice - -Once an advance invoice has been generated for a subscription's upcoming renewal, it can be viewed through this endpoint. There can only be one advance invoice per subscription per billing cycle. - -```go -ReadAdvanceInvoice( - ctx context.Context, +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Read Advance Invoice + +Once an advance invoice has been generated for a subscription's upcoming renewal, it can be viewed through this endpoint. There can only be one advance invoice per subscription per billing cycle. + +```go +ReadAdvanceInvoice( + ctx context.Context, subscriptionId int) ( models.ApiResponse[models.Invoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -[`models.Invoice`](../../doc/models/invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +[`models.Invoice`](../../doc/models/invoice.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -105,44 +105,44 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Void Advance Invoice - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Void Advance Invoice + Void a subscription's existing advance invoice. Once voided, it can later be regenerated if desired. -A `reason` is required in order to void, and the invoice must have an open status. Voiding will cause any prepayments and credits that were applied to the invoice to be returned to the subscription. For a full overview of the impact of voiding, please [see our help docs](reference/Chargify-API.v1.yaml/components/schemas/Invoice). - -```go -VoidAdvanceInvoice( - ctx context.Context, - subscriptionId int, +A `reason` is required in order to void, and the invoice must have an open status. Voiding will cause any prepayments and credits that were applied to the invoice to be returned to the subscription. For a full overview of the impact of voiding, please [see our help docs](../../doc/models/invoice.md). + +```go +VoidAdvanceInvoice( + ctx context.Context, + subscriptionId int, body *models.VoidInvoiceRequest) ( models.ApiResponse[models.Invoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | - -## Response Type - -[`models.Invoice`](../../doc/models/invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | + +## Response Type + +[`models.Invoice`](../../doc/models/invoice.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -153,12 +153,12 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + diff --git a/doc/controllers/api-exports.md b/doc/controllers/api-exports.md index b29bda86..6adfab45 100644 --- a/doc/controllers/api-exports.md +++ b/doc/controllers/api-exports.md @@ -1,15 +1,15 @@ -# API Exports - -```go -APIExportsController := client.APIExportsController() -``` - -## Class Name - -`APIExportsController` - -## Methods - +# API Exports + +```go +APIExportsController := client.APIExportsController() +``` + +## Class Name + +`APIExportsController` + +## Methods + * [List Exported Proforma Invoices](../../doc/controllers/api-exports.md#list-exported-proforma-invoices) * [List Exported Invoices](../../doc/controllers/api-exports.md#list-exported-invoices) * [List Exported Subscriptions](../../doc/controllers/api-exports.md#list-exported-subscriptions) @@ -18,179 +18,191 @@ APIExportsController := client.APIExportsController() * [Export Subscriptions](../../doc/controllers/api-exports.md#export-subscriptions) * [Read Proforma Invoices Export](../../doc/controllers/api-exports.md#read-proforma-invoices-export) * [Read Invoices Export](../../doc/controllers/api-exports.md#read-invoices-export) -* [Read Subscriptions Export](../../doc/controllers/api-exports.md#read-subscriptions-export) - - -# List Exported Proforma Invoices - +* [Read Subscriptions Export](../../doc/controllers/api-exports.md#read-subscriptions-export) + + +# List Exported Proforma Invoices + This API returns an array of exported proforma invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. -Example: `GET https://{subdomain}.chargify.com/api_exports/proforma_invoices/123/rows?per_page=10000&page=1`. - -```go -ListExportedProformaInvoices( - ctx context.Context,input ListExportedProformaInvoicesInput) ( +Example: `GET https://{subdomain}.chargify.com/api_exports/proforma_invoices/123/rows?per_page=10000&page=1`. + +```go +ListExportedProformaInvoices( + ctx context.Context, + input ListExportedProformaInvoicesInput) ( models.ApiResponse[[]models.ProformaInvoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `batchId` | `string` | Template, Required | Id of a Batch Job. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request.
Default value is 100.
The maximum allowed values is 10000; any per_page value over 10000 will be changed to 10000. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | - -## Response Type - -[`[]models.ProformaInvoice`](../../doc/models/proforma-invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `batchId` | `string` | Template, Required | Id of a Batch Job. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request.
Default value is 100.
The maximum allowed values is 10000; any per_page value over 10000 will be changed to 10000. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | + +## Response Type + +[`[]models.ProformaInvoice`](../../doc/models/proforma-invoice.md) + +## Example Usage + +```go ctx := context.Background() -batchId := "batch_id8" -perPage := 100 -page := 2 -apiResponse, err := APIExportsController.ListExportedProformaInvoices(ctx, batchId, &perPage, &page) +collectedInput := advancedbilling.ListExportedProformaInvoicesInput{ + BatchId: "batch_id8", + PerPage: models.ToPointer(100), + Page: models.ToPointer(2), +} + +apiResponse, err := APIExportsController.ListExportedProformaInvoices(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# List Exported Invoices - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# List Exported Invoices + This API returns an array of exported invoices for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. -Example: `GET https://{subdomain}.chargify.com/api_exports/invoices/123/rows?per_page=10000&page=1`. - -```go -ListExportedInvoices( - ctx context.Context,input ListExportedInvoicesInput) ( +Example: `GET https://{subdomain}.chargify.com/api_exports/invoices/123/rows?per_page=10000&page=1`. + +```go +ListExportedInvoices( + ctx context.Context, + input ListExportedInvoicesInput) ( models.ApiResponse[[]models.Invoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `batchId` | `string` | Template, Required | Id of a Batch Job. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request.
Default value is 100.
The maximum allowed values is 10000; any per_page value over 10000 will be changed to 10000. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | - -## Response Type - -[`[]models.Invoice`](../../doc/models/invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `batchId` | `string` | Template, Required | Id of a Batch Job. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request.
Default value is 100.
The maximum allowed values is 10000; any per_page value over 10000 will be changed to 10000. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | + +## Response Type + +[`[]models.Invoice`](../../doc/models/invoice.md) + +## Example Usage + +```go ctx := context.Background() -batchId := "batch_id8" -perPage := 100 -page := 2 -apiResponse, err := APIExportsController.ListExportedInvoices(ctx, batchId, &perPage, &page) +collectedInput := advancedbilling.ListExportedInvoicesInput{ + BatchId: "batch_id8", + PerPage: models.ToPointer(100), + Page: models.ToPointer(2), +} + +apiResponse, err := APIExportsController.ListExportedInvoices(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# List Exported Subscriptions - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# List Exported Subscriptions + This API returns an array of exported subscriptions for a provided `batch_id`. Pay close attention to pagination in order to control responses from the server. -Example: `GET https://{subdomain}.chargify.com/api_exports/subscriptions/123/rows?per_page=200&page=1`. - -```go -ListExportedSubscriptions( - ctx context.Context,input ListExportedSubscriptionsInput) ( +Example: `GET https://{subdomain}.chargify.com/api_exports/subscriptions/123/rows?per_page=200&page=1`. + +```go +ListExportedSubscriptions( + ctx context.Context, + input ListExportedSubscriptionsInput) ( models.ApiResponse[[]models.Subscription], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `batchId` | `string` | Template, Required | Id of a Batch Job. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request.
Default value is 100.
The maximum allowed values is 10000; any per_page value over 10000 will be changed to 10000. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | - -## Response Type - -[`[]models.Subscription`](../../doc/models/subscription.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `batchId` | `string` | Template, Required | Id of a Batch Job. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request.
Default value is 100.
The maximum allowed values is 10000; any per_page value over 10000 will be changed to 10000. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | + +## Response Type + +[`[]models.Subscription`](../../doc/models/subscription.md) + +## Example Usage + +```go ctx := context.Background() -batchId := "batch_id8" -perPage := 100 -page := 2 -apiResponse, err := APIExportsController.ListExportedSubscriptions(ctx, batchId, &perPage, &page) +collectedInput := advancedbilling.ListExportedSubscriptionsInput{ + BatchId: "batch_id8", + PerPage: models.ToPointer(100), + Page: models.ToPointer(2), +} + +apiResponse, err := APIExportsController.ListExportedSubscriptions(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Export Proforma Invoices - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Export Proforma Invoices + This API creates a proforma invoices export and returns a batchjob object. -It is only available for Relationship Invoicing architecture. - -```go -ExportProformaInvoices( +It is only available for Relationship Invoicing architecture. + +```go +ExportProformaInvoices( ctx context.Context) ( models.ApiResponse[models.BatchJobResponse], - error) -``` - -## Response Type - -[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) - -## Example Usage - -```go + error) +``` + +## Response Type + +[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) + +## Example Usage + +```go ctx := context.Background() apiResponse, err := APIExportsController.ExportProformaInvoices(ctx) if err != nil { @@ -199,35 +211,35 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 409 | Conflict | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | - - -# Export Invoices - -This API creates an invoices export and returns a batchjob object. - -```go -ExportInvoices( +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 409 | Conflict | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | + + +# Export Invoices + +This API creates an invoices export and returns a batchjob object. + +```go +ExportInvoices( ctx context.Context) ( models.ApiResponse[models.BatchJobResponse], - error) -``` - -## Response Type - -[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) - -## Example Usage - -```go + error) +``` + +## Response Type + +[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) + +## Example Usage + +```go ctx := context.Background() apiResponse, err := APIExportsController.ExportInvoices(ctx) if err != nil { @@ -236,35 +248,35 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 409 | Conflict | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | - - -# Export Subscriptions - -This API creates a subscriptions export and returns a batchjob object. - -```go -ExportSubscriptions( +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 409 | Conflict | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | + + +# Export Subscriptions + +This API creates a subscriptions export and returns a batchjob object. + +```go +ExportSubscriptions( ctx context.Context) ( models.ApiResponse[models.BatchJobResponse], - error) -``` - -## Response Type - -[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) - -## Example Usage - -```go + error) +``` + +## Response Type + +[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) + +## Example Usage + +```go ctx := context.Background() apiResponse, err := APIExportsController.ExportSubscriptions(ctx) if err != nil { @@ -273,41 +285,41 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 409 | Conflict | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | - - -# Read Proforma Invoices Export - -This API returns a batchjob object for proforma invoices export. - -```go -ReadProformaInvoicesExport( - ctx context.Context, +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 409 | Conflict | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | + + +# Read Proforma Invoices Export + +This API returns a batchjob object for proforma invoices export. + +```go +ReadProformaInvoicesExport( + ctx context.Context, batchId string) ( models.ApiResponse[models.BatchJobResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `batchId` | `string` | Template, Required | Id of a Batch Job. | - -## Response Type - -[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `batchId` | `string` | Template, Required | Id of a Batch Job. | + +## Response Type + +[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) + +## Example Usage + +```go ctx := context.Background() batchId := "batch_id8" @@ -318,41 +330,41 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Read Invoices Export - -This API returns a batchjob object for invoices export. - -```go -ReadInvoicesExport( - ctx context.Context, +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Read Invoices Export + +This API returns a batchjob object for invoices export. + +```go +ReadInvoicesExport( + ctx context.Context, batchId string) ( models.ApiResponse[models.BatchJobResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `batchId` | `string` | Template, Required | Id of a Batch Job. | - -## Response Type - -[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `batchId` | `string` | Template, Required | Id of a Batch Job. | + +## Response Type + +[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) + +## Example Usage + +```go ctx := context.Background() batchId := "batch_id8" @@ -363,41 +375,41 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Read Subscriptions Export - -This API returns a batchjob object for subscriptions export. - -```go -ReadSubscriptionsExport( - ctx context.Context, +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Read Subscriptions Export + +This API returns a batchjob object for subscriptions export. + +```go +ReadSubscriptionsExport( + ctx context.Context, batchId string) ( models.ApiResponse[models.BatchJobResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `batchId` | `string` | Template, Required | Id of a Batch Job. | - -## Response Type - -[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `batchId` | `string` | Template, Required | Id of a Batch Job. | + +## Response Type + +[`models.BatchJobResponse`](../../doc/models/batch-job-response.md) + +## Example Usage + +```go ctx := context.Background() batchId := "batch_id8" @@ -408,12 +420,12 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + diff --git a/doc/controllers/billing-portal.md b/doc/controllers/billing-portal.md index 9f800504..724461eb 100644 --- a/doc/controllers/billing-portal.md +++ b/doc/controllers/billing-portal.md @@ -1,23 +1,23 @@ -# Billing Portal - -```go -billingPortalController := client.BillingPortalController() -``` - -## Class Name - -`BillingPortalController` - -## Methods - +# Billing Portal + +```go +billingPortalController := client.BillingPortalController() +``` + +## Class Name + +`BillingPortalController` + +## Methods + * [Enable Billing Portal for Customer](../../doc/controllers/billing-portal.md#enable-billing-portal-for-customer) * [Read Billing Portal Link](../../doc/controllers/billing-portal.md#read-billing-portal-link) * [Resend Billing Portal Invitation](../../doc/controllers/billing-portal.md#resend-billing-portal-invitation) -* [Revoke Billing Portal Access](../../doc/controllers/billing-portal.md#revoke-billing-portal-access) - - -# Enable Billing Portal for Customer - +* [Revoke Billing Portal Access](../../doc/controllers/billing-portal.md#revoke-billing-portal-access) + + +# Enable Billing Portal for Customer + ## Billing Portal Documentation Full documentation on how the Billing Portal operates within the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407648972443). @@ -32,31 +32,31 @@ If your customer has been invited to the Billing Portal, then they will receive If you need to provide your customer their Management URL through other means, you can retrieve it via the API. Because the URL is cryptographically signed with a timestamp, it is not possible for merchants to generate the URL without requesting it from Chargify. -In order to prevent abuse & overuse, we ask that you request a new URL only when absolutely necessary. Management URLs are good for 65 days, so you should re-use a previously generated one as much as possible. If you use the URL frequently (such as to display on your website), please **do not** make an API request to Chargify every time. - -```go -EnableBillingPortalForCustomer( - ctx context.Context, - customerId int, +In order to prevent abuse & overuse, we ask that you request a new URL only when absolutely necessary. Management URLs are good for 65 days, so you should re-use a previously generated one as much as possible. If you use the URL frequently (such as to display on your website), please **do not** make an API request to Chargify every time. + +```go +EnableBillingPortalForCustomer( + ctx context.Context, + customerId int, autoInvite *models.AutoInvite) ( models.ApiResponse[models.CustomerResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `customerId` | `int` | Template, Required | The Chargify id of the customer | -| `autoInvite` | [`*models.AutoInvite`](../../doc/models/auto-invite.md) | Query, Optional | When set to 1, an Invitation email will be sent to the Customer.
When set to 0, or not sent, an email will not be sent.
Use in query: `auto_invite=1`. | - -## Response Type - -[`models.CustomerResponse`](../../doc/models/customer-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `customerId` | `int` | Template, Required | The Chargify id of the customer | +| `autoInvite` | [`*models.AutoInvite`](../../doc/models/auto-invite.md) | Query, Optional | When set to 1, an Invitation email will be sent to the Customer.
When set to 0, or not sent, an email will not be sent.
Use in query: `auto_invite=1`. | + +## Response Type + +[`models.CustomerResponse`](../../doc/models/customer-response.md) + +## Example Usage + +```go ctx := context.Background() customerId := 150 @@ -67,18 +67,18 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Read Billing Portal Link - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Read Billing Portal Link + This method will provide to the API user the exact URL required for a subscriber to access the Billing Portal. ## Rules for Management Link API @@ -87,29 +87,29 @@ This method will provide to the API user the exact URL required for a subscriber + We will not generate a new URL for 15 days + You must cache and remember this URL if you are going to need it again within 15 days + Only request a new URL after the `new_link_available_at` date -+ You are limited to 15 requests for the same URL. If you make more than 15 requests before `new_link_available_at`, you will be blocked from further Management URL requests (with a response code `429`) - -```go -ReadBillingPortalLink( - ctx context.Context, ++ You are limited to 15 requests for the same URL. If you make more than 15 requests before `new_link_available_at`, you will be blocked from further Management URL requests (with a response code `429`) + +```go +ReadBillingPortalLink( + ctx context.Context, customerId int) ( models.ApiResponse[models.PortalManagementLink], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `customerId` | `int` | Template, Required | The Chargify id of the customer | - -## Response Type - -[`models.PortalManagementLink`](../../doc/models/portal-management-link.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `customerId` | `int` | Template, Required | The Chargify id of the customer | + +## Response Type + +[`models.PortalManagementLink`](../../doc/models/portal-management-link.md) + +## Example Usage + +```go ctx := context.Background() customerId := 150 @@ -120,32 +120,32 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "url": "https://www.billingportal.com/manage/19804639/1517596469/bd16498719a7d3e6", - "fetch_count": 1, - "created_at": "2018-02-02T18:34:29Z", - "new_link_available_at": "2018-02-17T18:34:29Z", - "expires_at": "2018-04-08T17:34:29Z", - "last_invite_sent_at": "2018-02-02T18:34:29Z" -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -| 429 | Too Many Requests | [`TooManyManagementLinkRequestsErrorException`](../../doc/models/too-many-management-link-requests-error-exception.md) | - - -# Resend Billing Portal Invitation - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "url": "https://www.billingportal.com/manage/19804639/1517596469/bd16498719a7d3e6", + "fetch_count": 1, + "created_at": "2018-02-02T18:34:29Z", + "new_link_available_at": "2018-02-17T18:34:29Z", + "expires_at": "2018-04-08T17:34:29Z", + "last_invite_sent_at": "2018-02-02T18:34:29Z" +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +| 429 | Too Many Requests | [`TooManyManagementLinkRequestsErrorException`](../../doc/models/too-many-management-link-requests-error-exception.md) | + + +# Resend Billing Portal Invitation + You can resend a customer's Billing Portal invitation. If you attempt to resend an invitation 5 times within 30 minutes, you will receive a `422` response with `error` message in the body. @@ -158,29 +158,29 @@ If you attempt to resend an invitation when the Customer does not exist a Custom ## Limitations -This endpoint will only return a JSON response. - -```go -ResendBillingPortalInvitation( - ctx context.Context, +This endpoint will only return a JSON response. + +```go +ResendBillingPortalInvitation( + ctx context.Context, customerId int) ( models.ApiResponse[models.ResentInvitation], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `customerId` | `int` | Template, Required | The Chargify id of the customer | - -## Response Type - -[`models.ResentInvitation`](../../doc/models/resent-invitation.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `customerId` | `int` | Template, Required | The Chargify id of the customer | + +## Response Type + +[`models.ResentInvitation`](../../doc/models/resent-invitation.md) + +## Example Usage + +```go ctx := context.Background() customerId := 150 @@ -191,59 +191,59 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "last_sent_at": "enim Duis esse dolore", - "last_accepted_at": "adipisicing magna do in irure", - "send_invite_link_text": "veniam sit", - "uninvited_count": 66254678 -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Revoke Billing Portal Access - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "last_sent_at": "enim Duis esse dolore", + "last_accepted_at": "adipisicing magna do in irure", + "send_invite_link_text": "veniam sit", + "uninvited_count": 66254678 +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Revoke Billing Portal Access + You can revoke a customer's Billing Portal invitation. If you attempt to revoke an invitation when the Billing Portal is already disabled for a Customer, you will receive a 422 error response. ## Limitations -This endpoint will only return a JSON response. - -```go -RevokeBillingPortalAccess( - ctx context.Context, +This endpoint will only return a JSON response. + +```go +RevokeBillingPortalAccess( + ctx context.Context, customerId int) ( models.ApiResponse[models.RevokedInvitation], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `customerId` | `int` | Template, Required | The Chargify id of the customer | - -## Response Type - -[`models.RevokedInvitation`](../../doc/models/revoked-invitation.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `customerId` | `int` | Template, Required | The Chargify id of the customer | + +## Response Type + +[`models.RevokedInvitation`](../../doc/models/revoked-invitation.md) + +## Example Usage + +```go ctx := context.Background() customerId := 150 @@ -254,16 +254,16 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "last_sent_at": "Not Invited", - "last_accepted_at": "Invite Revoked", - "uninvited_count": 8 -} -``` - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "last_sent_at": "Not Invited", + "last_accepted_at": "Invite Revoked", + "uninvited_count": 8 +} +``` + diff --git a/doc/controllers/components.md b/doc/controllers/components.md index 1b48dc06..9397a5f4 100644 --- a/doc/controllers/components.md +++ b/doc/controllers/components.md @@ -1,15 +1,15 @@ -# Components - -```go -componentsController := client.ComponentsController() -``` - -## Class Name - -`ComponentsController` - -## Methods - +# Components + +```go +componentsController := client.ComponentsController() +``` + +## Class Name + +`ComponentsController` + +## Methods + * [Create Metered Component](../../doc/controllers/components.md#create-metered-component) * [Create Quantity Based Component](../../doc/controllers/components.md#create-quantity-based-component) * [Create on Off Component](../../doc/controllers/components.md#create-on-off-component) @@ -31,48 +31,52 @@ componentsController := client.ComponentsController() * [Unarchive Component Price Point](../../doc/controllers/components.md#unarchive-component-price-point) * [Create Currency Prices](../../doc/controllers/components.md#create-currency-prices) * [Update Currency Prices](../../doc/controllers/components.md#update-currency-prices) -* [List All Component Price Points](../../doc/controllers/components.md#list-all-component-price-points) - - -# Create Metered Component - +* [List All Component Price Points](../../doc/controllers/components.md#list-all-component-price-points) + + +# Create Metered Component + This request will create a component definition of kind **metered_component** under the specified product family. Metered component can then be added and “allocated” for a subscription. Metered components are used to bill for any type of unit that resets to 0 at the end of the billing period (think daily Google Adwords clicks or monthly cell phone minutes). This is most commonly associated with usage-based billing and many other pricing schemes. Note that this is different from recurring quantity-based components, which DO NOT reset to zero at the start of every billing period. If you want to bill for a quantity of something that does not change unless you change it, then you want quantity components, instead. -For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). - -```go -CreateMeteredComponent( - ctx context.Context, - productFamilyId int, +For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + +```go +CreateMeteredComponent( + ctx context.Context, + productFamilyId int, body *models.CreateMeteredComponent) ( models.ApiResponse[models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `body` | [`*models.CreateMeteredComponent`](../../doc/models/create-metered-component.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `body` | [`*models.CreateMeteredComponent`](../../doc/models/create-metered-component.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 +bodyMeteredComponentPrices0StartingQuantity := models.PriceStartingQuantityContainer.FromNumber(1) + +bodyMeteredComponentPrices0UnitPrice := models.PriceUnitPriceContainer.FromPrecision(float64(1)) + bodyMeteredComponentPrices0 := models.Price{ - StartingQuantity: interface{}("[key1, val1][key2, val2]"), - UnitPrice: interface{}("[key1, val1][key2, val2]"), + StartingQuantity: bodyMeteredComponentPrices0StartingQuantity, + UnitPrice: bodyMeteredComponentPrices0UnitPrice, } bodyMeteredComponentPrices := []models.Price{bodyMeteredComponentPrices0} @@ -94,69 +98,69 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "id": 292609, - "name": "Text messages", - "handle": "text-messages", - "pricing_scheme": "per_unit", - "unit_name": "unit", - "unit_price": "10.0", - "product_family_id": 528484, - "product_family_name": "Cloud Compute Servers", - "price_per_unit_in_cents": null, - "kind": "metered_component", - "archived": false, - "taxable": false, - "description": null, - "default_price_point_id": 2944263, - "prices": [ - { - "id": 55423, - "component_id": 30002, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "10.0", - "price_point_id": 2944263, - "formatted_unit_price": "$10.00", - "segment_id": null - } - ], - "price_point_count": 1, - "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", - "default_price_point_name": "Original", - "tax_code": null, - "recurring": false, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2024-01-23T06:08:05-05:00", - "updated_at": "2024-01-23T06:08:05-05:00", - "archived_at": null, - "hide_date_range_on_invoice": false, - "allow_fractional_quantities": false, - "use_site_exchange_rate": true, - "item_category": null, - "accounting_code": null - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Create Quantity Based Component - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 292609, + "name": "Text messages", + "handle": "text-messages", + "pricing_scheme": "per_unit", + "unit_name": "unit", + "unit_price": "10.0", + "product_family_id": 528484, + "product_family_name": "Cloud Compute Servers", + "price_per_unit_in_cents": null, + "kind": "metered_component", + "archived": false, + "taxable": false, + "description": null, + "default_price_point_id": 2944263, + "prices": [ + { + "id": 55423, + "component_id": 30002, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "10.0", + "price_point_id": 2944263, + "formatted_unit_price": "$10.00", + "segment_id": null + } + ], + "price_point_count": 1, + "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", + "default_price_point_name": "Original", + "tax_code": null, + "recurring": false, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2024-01-23T06:08:05-05:00", + "updated_at": "2024-01-23T06:08:05-05:00", + "archived_at": null, + "hide_date_range_on_invoice": false, + "allow_fractional_quantities": false, + "use_site_exchange_rate": true, + "item_category": null, + "accounting_code": null + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Create Quantity Based Component + This request will create a component definition of kind **quantity_based_component** under the specified product family. Quantity Based component can then be added and “allocated” for a subscription. When defining Quantity Based component, You can choose one of 2 types: @@ -171,44 +175,46 @@ One-time quantity-based components are used to create ad hoc usage charges that The allocated quantity for one-time quantity-based components immediately gets reset back to zero after the allocation is made. -For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). - -```go -CreateQuantityBasedComponent( - ctx context.Context, - productFamilyId int, +For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + +```go +CreateQuantityBasedComponent( + ctx context.Context, + productFamilyId int, body *models.CreateQuantityBasedComponent) ( models.ApiResponse[models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `body` | [`*models.CreateQuantityBasedComponent`](../../doc/models/create-quantity-based-component.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `body` | [`*models.CreateQuantityBasedComponent`](../../doc/models/create-quantity-based-component.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 +bodyQuantityBasedComponentUnitPrice := models.QuantityBasedComponentUnitPriceContainer.FromString("10") + bodyQuantityBasedComponent := models.QuantityBasedComponent{ Name: "Quantity Based Component", UnitName: "Component", Description: models.ToPointer("Example of JSON per-unit component example"), Taxable: models.ToPointer(true), PricingScheme: models.PricingScheme("per_unit"), - UnitPrice: models.ToPointer(interface{}("[key1, val1][key2, val2]")), DisplayOnHostedPage: models.ToPointer(true), AllowFractionalQuantities: models.ToPointer(true), PublicSignupPageIds: []int{323397}, + UnitPrice: models.ToPointer(bodyQuantityBasedComponentUnitPrice), } body := models.CreateQuantityBasedComponent{ @@ -222,104 +228,108 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "id": 292609, - "name": "Text messages", - "handle": "text-messages", - "pricing_scheme": "per_unit", - "unit_name": "unit", - "unit_price": "10.0", - "product_family_id": 528484, - "product_family_name": "Cloud Compute Servers", - "price_per_unit_in_cents": null, - "kind": "quantity_based_component", - "archived": false, - "taxable": false, - "description": null, - "default_price_point_id": 2944263, - "prices": [ - { - "id": 55423, - "component_id": 30002, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "10.0", - "price_point_id": 2944263, - "formatted_unit_price": "$10.00", - "segment_id": null - } - ], - "price_point_count": 1, - "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", - "default_price_point_name": "Original", - "tax_code": null, - "recurring": false, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2024-01-23T06:08:05-05:00", - "updated_at": "2024-01-23T06:08:05-05:00", - "archived_at": null, - "hide_date_range_on_invoice": false, - "allow_fractional_quantities": false, - "use_site_exchange_rate": true, - "item_category": null, - "accounting_code": null - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Create on Off Component - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 292609, + "name": "Text messages", + "handle": "text-messages", + "pricing_scheme": "per_unit", + "unit_name": "unit", + "unit_price": "10.0", + "product_family_id": 528484, + "product_family_name": "Cloud Compute Servers", + "price_per_unit_in_cents": null, + "kind": "quantity_based_component", + "archived": false, + "taxable": false, + "description": null, + "default_price_point_id": 2944263, + "prices": [ + { + "id": 55423, + "component_id": 30002, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "10.0", + "price_point_id": 2944263, + "formatted_unit_price": "$10.00", + "segment_id": null + } + ], + "price_point_count": 1, + "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", + "default_price_point_name": "Original", + "tax_code": null, + "recurring": false, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2024-01-23T06:08:05-05:00", + "updated_at": "2024-01-23T06:08:05-05:00", + "archived_at": null, + "hide_date_range_on_invoice": false, + "allow_fractional_quantities": false, + "use_site_exchange_rate": true, + "item_category": null, + "accounting_code": null + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Create on Off Component + This request will create a component definition of kind **on_off_component** under the specified product family. On/Off component can then be added and “allocated” for a subscription. On/off components are used for any flat fee, recurring add on (think $99/month for tech support or a flat add on shipping fee). -For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). - -```go -CreateOnOffComponent( - ctx context.Context, - productFamilyId int, +For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + +```go +CreateOnOffComponent( + ctx context.Context, + productFamilyId int, body *models.CreateOnOffComponent) ( models.ApiResponse[models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `body` | [`*models.CreateOnOffComponent`](../../doc/models/create-on-off-component.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `body` | [`*models.CreateOnOffComponent`](../../doc/models/create-on-off-component.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 +bodyOnOffComponentPrices0StartingQuantity := models.PriceStartingQuantityContainer.FromString("0") + +bodyOnOffComponentPrices0UnitPrice := models.PriceUnitPriceContainer.FromString("100.00") + bodyOnOffComponentPrices0 := models.Price{ - StartingQuantity: interface{}("[key1, val1][key2, val2]"), - UnitPrice: interface{}("[key1, val1][key2, val2]"), + StartingQuantity: bodyOnOffComponentPrices0StartingQuantity, + UnitPrice: bodyOnOffComponentPrices0UnitPrice, } bodyOnOffComponentPrices := []models.Price{bodyOnOffComponentPrices0} @@ -343,98 +353,108 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "id": 292609, - "name": "Test On-Off Component 46124", - "handle": "test-on-off-component-4612422802", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "10.0", - "product_family_id": 528484, - "product_family_name": "Cloud Compute Servers", - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": false, - "description": null, - "default_price_point_id": 2944263, - "price_point_count": 1, - "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", - "default_price_point_name": "Original", - "tax_code": null, - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2024-01-23T06:08:05-05:00", - "updated_at": "2024-01-23T06:08:05-05:00", - "archived_at": null, - "hide_date_range_on_invoice": false, - "allow_fractional_quantities": false, - "use_site_exchange_rate": true, - "item_category": null, - "accounting_code": null - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Create Prepaid Usage Component - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 292609, + "name": "Test On-Off Component 46124", + "handle": "test-on-off-component-4612422802", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "10.0", + "product_family_id": 528484, + "product_family_name": "Cloud Compute Servers", + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": false, + "description": null, + "default_price_point_id": 2944263, + "price_point_count": 1, + "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", + "default_price_point_name": "Original", + "tax_code": null, + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2024-01-23T06:08:05-05:00", + "updated_at": "2024-01-23T06:08:05-05:00", + "archived_at": null, + "hide_date_range_on_invoice": false, + "allow_fractional_quantities": false, + "use_site_exchange_rate": true, + "item_category": null, + "accounting_code": null + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Create Prepaid Usage Component + This request will create a component definition of kind **prepaid_usage_component** under the specified product family. Prepaid component can then be added and “allocated” for a subscription. Prepaid components allow customers to pre-purchase units that can be used up over time on their subscription. In a sense, they are the mirror image of metered components; while metered components charge at the end of the period for the amount of units used, prepaid components are charged for at the time of purchase, and we subsequently keep track of the usage against the amount purchased. -For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). - -```go -CreatePrepaidUsageComponent( - ctx context.Context, - productFamilyId int, +For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + +```go +CreatePrepaidUsageComponent( + ctx context.Context, + productFamilyId int, body *models.CreatePrepaidComponent) ( models.ApiResponse[models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `body` | [`*models.CreatePrepaidComponent`](../../doc/models/create-prepaid-component.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `body` | [`*models.CreatePrepaidComponent`](../../doc/models/create-prepaid-component.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 +bodyPrepaidUsageComponentOveragePricingPrices0StartingQuantity := models.PriceStartingQuantityContainer.FromNumber(1) + +bodyPrepaidUsageComponentOveragePricingPrices0EndingQuantity := models.PriceEndingQuantityContainer.FromNumber(100) + +bodyPrepaidUsageComponentOveragePricingPrices0UnitPrice := models.PriceUnitPriceContainer.FromPrecision(float64(3)) + bodyPrepaidUsageComponentOveragePricingPrices0 := models.Price{ - StartingQuantity: interface{}("[key1, val1][key2, val2]"), - EndingQuantity: models.NewOptional(models.ToPointer(interface{}("[key1, val1][key2, val2]"))), - UnitPrice: interface{}("[key1, val1][key2, val2]"), + StartingQuantity: bodyPrepaidUsageComponentOveragePricingPrices0StartingQuantity, + EndingQuantity: models.NewOptional(models.ToPointer(bodyPrepaidUsageComponentOveragePricingPrices0EndingQuantity)), + UnitPrice: bodyPrepaidUsageComponentOveragePricingPrices0UnitPrice, } +bodyPrepaidUsageComponentOveragePricingPrices1StartingQuantity := models.PriceStartingQuantityContainer.FromNumber(101) + +bodyPrepaidUsageComponentOveragePricingPrices1UnitPrice := models.PriceUnitPriceContainer.FromPrecision(float64(5)) + bodyPrepaidUsageComponentOveragePricingPrices1 := models.Price{ - StartingQuantity: interface{}("[key1, val1][key2, val2]"), - UnitPrice: interface{}("[key1, val1][key2, val2]"), + StartingQuantity: bodyPrepaidUsageComponentOveragePricingPrices1StartingQuantity, + UnitPrice: bodyPrepaidUsageComponentOveragePricingPrices1UnitPrice, } bodyPrepaidUsageComponentOveragePricingPrices := []models.Price{bodyPrepaidUsageComponentOveragePricingPrices0, bodyPrepaidUsageComponentOveragePricingPrices1} @@ -443,16 +463,18 @@ bodyPrepaidUsageComponentOveragePricing := models.OveragePricing{ Prices: bodyPrepaidUsageComponentOveragePricingPrices, } +bodyPrepaidUsageComponentUnitPrice := models.PrepaidUsageComponentUnitPriceContainer.FromPrecision(float64(2)) + bodyPrepaidUsageComponent := models.PrepaidUsageComponent{ Name: "Minutes", UnitName: models.ToPointer("minutes"), PricingScheme: models.ToPointer(models.PricingScheme("per_unit")), - UnitPrice: models.ToPointer(interface{}("[key1, val1][key2, val2]")), RolloverPrepaidRemainder: models.ToPointer(true), RenewPrepaidAllocation: models.ToPointer(true), ExpirationInterval: models.ToPointer(float64(15)), ExpirationIntervalUnit: models.ToPointer(models.IntervalUnit("day")), OveragePricing: models.ToPointer(bodyPrepaidUsageComponentOveragePricing), + UnitPrice: models.ToPointer(bodyPrepaidUsageComponentUnitPrice), } body := models.CreatePrepaidComponent{ @@ -466,118 +488,122 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "id": 292609, - "name": "Test Prepaid Component 98505", - "handle": "test-prepaid-component-9850584842", - "pricing_scheme": "per_unit", - "unit_name": "unit", - "unit_price": "10.0", - "product_family_id": 528484, - "product_family_name": "Test Product Family 27791", - "price_per_unit_in_cents": null, - "kind": "prepaid_usage_component", - "archived": false, - "taxable": false, - "description": "Description for: Test Prepaid Component 98505", - "default_price_point_id": 2944263, - "overage_prices": [ - { - "id": 55964, - "component_id": 30427, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "1.0", - "price_point_id": 2944756, - "formatted_unit_price": "$1.00", - "segment_id": null - } - ], - "prices": [ - { - "id": 55963, - "component_id": 30427, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "1.0", - "price_point_id": 2944756, - "formatted_unit_price": "$1.00", - "segment_id": null - } - ], - "price_point_count": 1, - "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", - "default_price_point_name": "Original", - "tax_code": null, - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2024-01-23T06:08:05-05:00", - "updated_at": "2024-01-23T06:08:05-05:00", - "archived_at": null, - "hide_date_range_on_invoice": false, - "allow_fractional_quantities": false, - "use_site_exchange_rate": true, - "item_category": null, - "accounting_code": null - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Create Event Based Component - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 292609, + "name": "Test Prepaid Component 98505", + "handle": "test-prepaid-component-9850584842", + "pricing_scheme": "per_unit", + "unit_name": "unit", + "unit_price": "10.0", + "product_family_id": 528484, + "product_family_name": "Test Product Family 27791", + "price_per_unit_in_cents": null, + "kind": "prepaid_usage_component", + "archived": false, + "taxable": false, + "description": "Description for: Test Prepaid Component 98505", + "default_price_point_id": 2944263, + "overage_prices": [ + { + "id": 55964, + "component_id": 30427, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "1.0", + "price_point_id": 2944756, + "formatted_unit_price": "$1.00", + "segment_id": null + } + ], + "prices": [ + { + "id": 55963, + "component_id": 30427, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "1.0", + "price_point_id": 2944756, + "formatted_unit_price": "$1.00", + "segment_id": null + } + ], + "price_point_count": 1, + "price_points_url": "https://demo-3238403362.chargify.com/components/30002/price_points", + "default_price_point_name": "Original", + "tax_code": null, + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2024-01-23T06:08:05-05:00", + "updated_at": "2024-01-23T06:08:05-05:00", + "archived_at": null, + "hide_date_range_on_invoice": false, + "allow_fractional_quantities": false, + "use_site_exchange_rate": true, + "item_category": null, + "accounting_code": null + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Create Event Based Component + This request will create a component definition of kind **event_based_component** under the specified product family. Event-based component can then be added and “allocated” for a subscription. Event-based components are similar to other component types, in that you define the component parameters (such as name and taxability) and the pricing. A key difference for the event-based component is that it must be attached to a metric. This is because the metric provides the component with the actual quantity used in computing what and how much will be billed each period for each subscription. So, instead of reporting usage directly for each component (as you would with metered components), the usage is derived from analysis of your events. -For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). - -```go -CreateEventBasedComponent( - ctx context.Context, - productFamilyId int, +For more information on components, please see our documentation [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677). + +```go +CreateEventBasedComponent( + ctx context.Context, + productFamilyId int, body *models.CreateEBBComponent) ( models.ApiResponse[models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `body` | [`*models.CreateEBBComponent`](../../doc/models/create-ebb-component.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `body` | [`*models.CreateEBBComponent`](../../doc/models/create-ebb-component.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 +bodyEventBasedComponentPrices0StartingQuantity := models.PriceStartingQuantityContainer.FromNumber(1) + +bodyEventBasedComponentPrices0UnitPrice := models.PriceUnitPriceContainer.FromString("0.49") + bodyEventBasedComponentPrices0 := models.Price{ - StartingQuantity: interface{}("[key1, val1][key2, val2]"), - UnitPrice: interface{}("[key1, val1][key2, val2]"), + StartingQuantity: bodyEventBasedComponentPrices0StartingQuantity, + UnitPrice: bodyEventBasedComponentPrices0UnitPrice, } bodyEventBasedComponentPrices := []models.Price{bodyEventBasedComponentPrices0} @@ -603,82 +629,82 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "id": 1489581, - "name": "stripeCharges", - "handle": null, - "pricing_scheme": null, - "unit_name": "charge", - "unit_price": null, - "product_family_id": 1517093, - "product_family_name": "Billing Plans", - "price_per_unit_in_cents": null, - "kind": "event_based_component", - "archived": false, - "taxable": false, - "description": null, - "default_price_point_id": null, - "prices": [], - "price_point_count": 0, - "price_points_url": "https://staging.chargify.com/components/1489581/price_points", - "default_price_point_name": "Original", - "tax_code": null, - "recurring": false, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2021-10-12T07:33:24-05:00", - "updated_at": "2021-10-12T07:33:24-05:00", - "archived_at": null, - "hide_date_range_on_invoice": false, - "allow_fractional_quantities": false, - "use_site_exchange_rate": null, - "item_category": null, - "accounting_code": null, - "event_based_billing_metric_id": 1163 - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Find Component - -This request will return information regarding a component having the handle you provide. You can identify your components with a handle so you don't have to save or reference the IDs we generate. - -```go -FindComponent( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 1489581, + "name": "stripeCharges", + "handle": null, + "pricing_scheme": null, + "unit_name": "charge", + "unit_price": null, + "product_family_id": 1517093, + "product_family_name": "Billing Plans", + "price_per_unit_in_cents": null, + "kind": "event_based_component", + "archived": false, + "taxable": false, + "description": null, + "default_price_point_id": null, + "prices": [], + "price_point_count": 0, + "price_points_url": "https://staging.chargify.com/components/1489581/price_points", + "default_price_point_name": "Original", + "tax_code": null, + "recurring": false, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2021-10-12T07:33:24-05:00", + "updated_at": "2021-10-12T07:33:24-05:00", + "archived_at": null, + "hide_date_range_on_invoice": false, + "allow_fractional_quantities": false, + "use_site_exchange_rate": null, + "item_category": null, + "accounting_code": null, + "event_based_billing_metric_id": 1163 + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Find Component + +This request will return information regarding a component having the handle you provide. You can identify your components with a handle so you don't have to save or reference the IDs we generate. + +```go +FindComponent( + ctx context.Context, handle string) ( models.ApiResponse[models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `handle` | `string` | Query, Required | The handle of the component to find | - -## Response Type - -[`models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `handle` | `string` | Query, Required | The handle of the component to find | + +## Response Type + +[`models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() handle := "handle6" @@ -689,69 +715,69 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "id": 399853, - "name": "Annual Support Services", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "100.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": true, - "description": "Prepay for support services", - "default_price_point_id": 121003, - "price_point_count": 4, - "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", - "tax_code": "D0000000", - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-02T05:54:53-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify" - } -} -``` - - -# Read Component - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 399853, + "name": "Annual Support Services", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "100.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": true, + "description": "Prepay for support services", + "default_price_point_id": 121003, + "price_point_count": 4, + "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", + "tax_code": "D0000000", + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-02T05:54:53-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify" + } +} +``` + + +# Read Component + This request will return information regarding a component from a specific product family. -You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. - -```go -ReadComponent( - ctx context.Context, - productFamilyId int, +You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. + +```go +ReadComponent( + ctx context.Context, + productFamilyId int, componentId string) ( models.ApiResponse[models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | - -## Response Type - -[`models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | + +## Response Type + +[`models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 componentId := "component_id8" @@ -763,71 +789,71 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "id": 399853, - "name": "Annual Support Services", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "100.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": true, - "description": "Prepay for support services", - "default_price_point_id": 121003, - "price_point_count": 4, - "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", - "tax_code": "D0000000", - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-02T05:54:53-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify" - } -} -``` - - -# Update Product Family Component - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 399853, + "name": "Annual Support Services", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "100.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": true, + "description": "Prepay for support services", + "default_price_point_id": 121003, + "price_point_count": 4, + "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", + "tax_code": "D0000000", + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-02T05:54:53-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify" + } +} +``` + + +# Update Product Family Component + This request will update a component from a specific product family. -You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. - -```go -UpdateProductFamilyComponent( - ctx context.Context, - productFamilyId int, - componentId string, +You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. + +```go +UpdateProductFamilyComponent( + ctx context.Context, + productFamilyId int, + componentId string, body *models.UpdateComponentRequest) ( models.ApiResponse[models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | -| `body` | [`*models.UpdateComponentRequest`](../../doc/models/update-component-request.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | +| `body` | [`*models.UpdateComponentRequest`](../../doc/models/update-component-request.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 componentId := "component_id8" @@ -847,73 +873,73 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "id": 399853, - "name": "Annual Support Services", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "100.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": true, - "description": "Prepay for support services", - "default_price_point_id": 121003, - "price_point_count": 4, - "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", - "tax_code": "D0000000", - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-02T05:54:53-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Archive Component - -Sending a DELETE request to this endpoint will archive the component. All current subscribers will be unffected; their subscription/purchase will continue to be charged as usual. - -```go -ArchiveComponent( - ctx context.Context, - productFamilyId int, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 399853, + "name": "Annual Support Services", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "100.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": true, + "description": "Prepay for support services", + "default_price_point_id": 121003, + "price_point_count": 4, + "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", + "tax_code": "D0000000", + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-02T05:54:53-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Archive Component + +Sending a DELETE request to this endpoint will archive the component. All current subscribers will be unffected; their subscription/purchase will continue to be charged as usual. + +```go +ArchiveComponent( + ctx context.Context, + productFamilyId int, componentId string) ( models.ApiResponse[models.Component], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | -| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | - -## Response Type - -[`models.Component`](../../doc/models/component.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the component belongs | +| `componentId` | `string` | Template, Required | Either the Chargify id of the component or the handle for the component prefixed with `handle:` | + +## Response Type + +[`models.Component`](../../doc/models/component.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 componentId := "component_id8" @@ -925,216 +951,220 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "id": 25407138, - "name": "cillum aute", - "pricing_scheme": "stairstep", - "unit_name": "nulla in", - "unit_price": "Excepteur veniam", - "product_family_id": -56705047, - "kind": "prepaid_usage_component", - "archived": true, - "taxable": false, - "description": "reprehenderit laborum qui fugiat", - "default_price_point_id": -64328176, - "price_point_count": 15252407, - "price_points_url": "dolor mollit consequat", - "tax_code": "ea nisi", - "recurring": false, - "created_at": "2016-11-08T16:22:26-05:00", - "default_price_point_name": "cupidatat Lorem non aliqua", - "product_family_name": "do elit", - "hide_date_range_on_invoice": false -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Components - -This request will return a list of components for a site. - -```go -ListComponents( - ctx context.Context,input ListComponentsInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "id": 25407138, + "name": "cillum aute", + "pricing_scheme": "stairstep", + "unit_name": "nulla in", + "unit_price": "Excepteur veniam", + "product_family_id": -56705047, + "kind": "prepaid_usage_component", + "archived": true, + "taxable": false, + "description": "reprehenderit laborum qui fugiat", + "default_price_point_id": -64328176, + "price_point_count": 15252407, + "price_points_url": "dolor mollit consequat", + "tax_code": "ea nisi", + "recurring": false, + "created_at": "2016-11-08T16:22:26-05:00", + "default_price_point_name": "cupidatat Lorem non aliqua", + "product_family_name": "do elit", + "hide_date_range_on_invoice": false +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Components + +This request will return a list of components for a site. + +```go +ListComponents( + ctx context.Context, + input ListComponentsInput) ( models.ApiResponse[[]models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. | -| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. optional | -| `includeArchived` | `*bool` | Query, Optional | Include archived items | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `filterIds` | `[]string` | Query, Optional | Allows fetching components with matching id based on provided value. Use in query `filter[ids]=1,2,3`. | -| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching components with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | - -## Response Type - -[`[]models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. | +| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. optional | +| `includeArchived` | `*bool` | Query, Optional | Include archived items | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `filterIds` | `[]string` | Query, Optional | Allows fetching components with matching id based on provided value. Use in query `filter[ids]=1,2,3`. | +| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching components with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | + +## Response Type + +[`[]models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() -dateField := models.BasicDateField("updated_at") -page := 2 -perPage := 50Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') -apiResponse, err := componentsController.ListComponents(ctx, &dateField, nil, nil, nil, nil, nil, &page, &perPage, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key')) +collectedInput := advancedbilling.ListComponentsInput{ + DateField: models.ToPointer(models.BasicDateField("updated_at")), + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := componentsController.ListComponents(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "component": { - "id": 399850, - "name": "$1.00 component", - "pricing_scheme": "per_unit", - "unit_name": "Component", - "unit_price": "1.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "quantity_based_component", - "archived": false, - "taxable": false, - "description": "Component", - "default_price_point_id": 121000, - "prices": [ - { - "id": 630687, - "component_id": 399850, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "1.0", - "price_point_id": 121000, - "formatted_unit_price": "$1.00" - } - ], - "price_point_count": 2, - "price_points_url": "https://general-goods.chargify.com/components/399850/price_points", - "tax_code": null, - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-01T09:35:38-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify", - "use_site_exchange_rate": true - } - }, - { - "component": { - "id": 399853, - "name": "Annual Support Services", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "100.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": true, - "description": "Prepay for support services", - "default_price_point_id": 121003, - "price_point_count": 4, - "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", - "tax_code": "D0000000", - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-01T09:35:37-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify", - "use_site_exchange_rate": true - } - }, - { - "component": { - "id": 386937, - "name": "Cancellation fee", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "35.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": false, - "description": "", - "default_price_point_id": 108307, - "price_point_count": 1, - "price_points_url": "https://general-goods.chargify.com/components/386937/price_points", - "tax_code": null, - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-01T09:35:38-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify", - "use_site_exchange_rate": true - } - } -] -``` - - -# Update Component - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "component": { + "id": 399850, + "name": "$1.00 component", + "pricing_scheme": "per_unit", + "unit_name": "Component", + "unit_price": "1.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "quantity_based_component", + "archived": false, + "taxable": false, + "description": "Component", + "default_price_point_id": 121000, + "prices": [ + { + "id": 630687, + "component_id": 399850, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "1.0", + "price_point_id": 121000, + "formatted_unit_price": "$1.00" + } + ], + "price_point_count": 2, + "price_points_url": "https://general-goods.chargify.com/components/399850/price_points", + "tax_code": null, + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-01T09:35:38-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify", + "use_site_exchange_rate": true + } + }, + { + "component": { + "id": 399853, + "name": "Annual Support Services", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "100.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": true, + "description": "Prepay for support services", + "default_price_point_id": 121003, + "price_point_count": 4, + "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", + "tax_code": "D0000000", + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-01T09:35:37-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify", + "use_site_exchange_rate": true + } + }, + { + "component": { + "id": 386937, + "name": "Cancellation fee", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "35.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": false, + "description": "", + "default_price_point_id": 108307, + "price_point_count": 1, + "price_points_url": "https://general-goods.chargify.com/components/386937/price_points", + "tax_code": null, + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-01T09:35:38-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify", + "use_site_exchange_rate": true + } + } +] +``` + + +# Update Component + This request will update a component. -You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. - -```go -UpdateComponent( - ctx context.Context, - componentId string, +You may read the component by either the component's id or handle. When using the handle, it must be prefixed with `handle:`. + +```go +UpdateComponent( + ctx context.Context, + componentId string, body *models.UpdateComponentRequest) ( models.ApiResponse[models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | The id or handle of the component | -| `body` | [`*models.UpdateComponentRequest`](../../doc/models/update-component-request.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `string` | Template, Required | The id or handle of the component | +| `body` | [`*models.UpdateComponentRequest`](../../doc/models/update-component-request.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() componentId := "component_id8" @@ -1153,77 +1183,77 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "id": 399853, - "name": "Annual Support Services", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "100.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": true, - "description": "Prepay for support services", - "default_price_point_id": 121003, - "price_point_count": 4, - "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", - "tax_code": "D0000000", - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-02T05:54:53-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Promote Component Price Point to Default - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 399853, + "name": "Annual Support Services", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "100.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": true, + "description": "Prepay for support services", + "default_price_point_id": 121003, + "price_point_count": 4, + "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", + "tax_code": "D0000000", + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-02T05:54:53-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Promote Component Price Point to Default + Sets a new default price point for the component. This new default will apply to all new subscriptions going forward - existing subscriptions will remain on their current price point. See [Price Points Documentation](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-points) for more information on price points and moving subscriptions between price points. -Note: Custom price points are not able to be set as the default for a component. - -```go -PromoteComponentPricePointToDefault( - ctx context.Context, - componentId int, +Note: Custom price points are not able to be set as the default for a component. + +```go +PromoteComponentPricePointToDefault( + ctx context.Context, + componentId int, pricePointId int) ( models.ApiResponse[models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | -| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | - -## Response Type - -[`models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | +| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | + +## Response Type + +[`models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() componentId := 222 pricePointId := 10 @@ -1235,239 +1265,255 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "id": 292609, - "name": "Text messages", - "pricing_scheme": "stairstep", - "unit_name": "text message", - "unit_price": null, - "product_family_id": 528484, - "price_per_unit_in_cents": null, - "kind": "metered_component", - "archived": false, - "taxable": false, - "description": null, - "created_at": "2019-08-02T05:54:53-04:00", - "prices": [ - { - "id": 47, - "component_id": 292609, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "1.0", - "price_point_id": 173, - "formatted_unit_price": "$1.00" - } - ], - "default_price_point_name": "Original" - } -} -``` - - -# List Components for Product Family - -This request will return a list of components for a particular product family. - -```go -ListComponentsForProductFamily( - ctx context.Context,input ListComponentsForProductFamilyInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "id": 292609, + "name": "Text messages", + "pricing_scheme": "stairstep", + "unit_name": "text message", + "unit_price": null, + "product_family_id": 528484, + "price_per_unit_in_cents": null, + "kind": "metered_component", + "archived": false, + "taxable": false, + "description": null, + "created_at": "2019-08-02T05:54:53-04:00", + "prices": [ + { + "id": 47, + "component_id": 292609, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "1.0", + "price_point_id": 173, + "formatted_unit_price": "$1.00" + } + ], + "default_price_point_name": "Original" + } +} +``` + + +# List Components for Product Family + +This request will return a list of components for a particular product family. + +```go +ListComponentsForProductFamily( + ctx context.Context, + input ListComponentsForProductFamilyInput) ( models.ApiResponse[[]models.ComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family | -| `includeArchived` | `*bool` | Query, Optional | Include archived items. | -| `filterIds` | `[]int` | Query, Optional | Allows fetching components with matching id based on provided value. Use in query `filter[ids]=1,2`. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `date_field=created_at`. | -| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. optional. | -| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching components with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | - -## Response Type - -[`[]models.ComponentResponse`](../../doc/models/component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family | +| `includeArchived` | `*bool` | Query, Optional | Include archived items. | +| `filterIds` | `[]int` | Query, Optional | Allows fetching components with matching id based on provided value. Use in query `filter[ids]=1,2`. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `date_field=created_at`. | +| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. optional. | +| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching components with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | + +## Response Type + +[`[]models.ComponentResponse`](../../doc/models/component-response.md) + +## Example Usage + +```go ctx := context.Background() -productFamilyId := 140Liquid error: Value cannot be null. (Parameter 'key') -page := 2 -perPage := 50 -dateField := models.BasicDateField("updated_at")Liquid error: Value cannot be null. (Parameter 'key') -apiResponse, err := componentsController.ListComponentsForProductFamily(ctx, productFamilyId, nil, Liquid error: Value cannot be null. (Parameter 'key'), &page, &perPage, &dateField, nil, nil, nil, nil, Liquid error: Value cannot be null. (Parameter 'key')) +collectedInput := advancedbilling.ListComponentsForProductFamilyInput{ + ProductFamilyId: 140, +Liquid error: Value cannot be null. (Parameter 'key') Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + DateField: models.ToPointer(models.BasicDateField("updated_at")), +Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := componentsController.ListComponentsForProductFamily(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "component": { - "id": 399850, - "name": "$1.00 component", - "pricing_scheme": "per_unit", - "unit_name": "Component", - "unit_price": "1.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "quantity_based_component", - "archived": false, - "taxable": false, - "description": "Component", - "default_price_point_id": 121000, - "prices": [ - { - "id": 630687, - "component_id": 399850, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "1.0", - "price_point_id": 121000, - "formatted_unit_price": "$1.00" - } - ], - "price_point_count": 2, - "price_points_url": "https://general-goods.chargify.com/components/399850/price_points", - "tax_code": null, - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-01T09:35:38-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify", - "use_site_exchange_rate": true - } - }, - { - "component": { - "id": 399853, - "name": "Annual Support Services", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "100.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": true, - "description": "Prepay for support services", - "default_price_point_id": 121003, - "price_point_count": 4, - "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", - "tax_code": "D0000000", - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-01T09:35:37-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify", - "use_site_exchange_rate": true - } - }, - { - "component": { - "id": 386937, - "name": "Cancellation fee", - "pricing_scheme": null, - "unit_name": "on/off", - "unit_price": "35.0", - "product_family_id": 997233, - "price_per_unit_in_cents": null, - "kind": "on_off_component", - "archived": false, - "taxable": false, - "description": "", - "default_price_point_id": 108307, - "price_point_count": 1, - "price_points_url": "https://general-goods.chargify.com/components/386937/price_points", - "tax_code": null, - "recurring": true, - "upgrade_charge": null, - "downgrade_credit": null, - "created_at": "2019-08-01T09:35:38-04:00", - "default_price_point_name": "Original", - "product_family_name": "Chargify", - "use_site_exchange_rate": true - } - } -] -``` - - -# Create Component Price Point - -This endpoint can be used to create a new price point for an existing component. - -```go -CreateComponentPricePoint( - ctx context.Context, - componentId int, +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "component": { + "id": 399850, + "name": "$1.00 component", + "pricing_scheme": "per_unit", + "unit_name": "Component", + "unit_price": "1.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "quantity_based_component", + "archived": false, + "taxable": false, + "description": "Component", + "default_price_point_id": 121000, + "prices": [ + { + "id": 630687, + "component_id": 399850, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "1.0", + "price_point_id": 121000, + "formatted_unit_price": "$1.00" + } + ], + "price_point_count": 2, + "price_points_url": "https://general-goods.chargify.com/components/399850/price_points", + "tax_code": null, + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-01T09:35:38-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify", + "use_site_exchange_rate": true + } + }, + { + "component": { + "id": 399853, + "name": "Annual Support Services", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "100.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": true, + "description": "Prepay for support services", + "default_price_point_id": 121003, + "price_point_count": 4, + "price_points_url": "https://general-goods.chargify.com/components/399853/price_points", + "tax_code": "D0000000", + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-01T09:35:37-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify", + "use_site_exchange_rate": true + } + }, + { + "component": { + "id": 386937, + "name": "Cancellation fee", + "pricing_scheme": null, + "unit_name": "on/off", + "unit_price": "35.0", + "product_family_id": 997233, + "price_per_unit_in_cents": null, + "kind": "on_off_component", + "archived": false, + "taxable": false, + "description": "", + "default_price_point_id": 108307, + "price_point_count": 1, + "price_points_url": "https://general-goods.chargify.com/components/386937/price_points", + "tax_code": null, + "recurring": true, + "upgrade_charge": null, + "downgrade_credit": null, + "created_at": "2019-08-01T09:35:38-04:00", + "default_price_point_name": "Original", + "product_family_name": "Chargify", + "use_site_exchange_rate": true + } + } +] +``` + + +# Create Component Price Point + +This endpoint can be used to create a new price point for an existing component. + +```go +CreateComponentPricePoint( + ctx context.Context, + componentId int, body *models.CreateComponentPricePointRequest) ( models.ApiResponse[models.ComponentPricePointResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `int` | Template, Required | The Chargify id of the component | -| `body` | [`*models.CreateComponentPricePointRequest`](../../doc/models/create-component-price-point-request.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentPricePointResponse`](../../doc/models/component-price-point-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `int` | Template, Required | The Chargify id of the component | +| `body` | [`*models.CreateComponentPricePointRequest`](../../doc/models/create-component-price-point-request.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentPricePointResponse`](../../doc/models/component-price-point-response.md) + +## Example Usage + +```go ctx := context.Background() componentId := 222 -bodyPricePointPrices0 := models.Price{ - StartingQuantity: interface{}("[key1, val1][key2, val2]"), - EndingQuantity: models.NewOptional(models.ToPointer(interface{}("[key1, val1][key2, val2]"))), - UnitPrice: interface{}("[key1, val1][key2, val2]"), +bodyPricePointCreateComponentPricePointPrices0StartingQuantity := models.PriceStartingQuantityContainer.FromString("1") + +bodyPricePointCreateComponentPricePointPrices0EndingQuantity := models.PriceEndingQuantityContainer.FromString("100") + +bodyPricePointCreateComponentPricePointPrices0UnitPrice := models.PriceUnitPriceContainer.FromString("5.00") + +bodyPricePointCreateComponentPricePointPrices0 := models.Price{ + StartingQuantity: bodyPricePointCreateComponentPricePointPrices0StartingQuantity, + EndingQuantity: models.NewOptional(models.ToPointer(bodyPricePointCreateComponentPricePointPrices0EndingQuantity)), + UnitPrice: bodyPricePointCreateComponentPricePointPrices0UnitPrice, } -bodyPricePointPrices1 := models.Price{ - StartingQuantity: interface{}("[key1, val1][key2, val2]"), - UnitPrice: interface{}("[key1, val1][key2, val2]"), +bodyPricePointCreateComponentPricePointPrices1StartingQuantity := models.PriceStartingQuantityContainer.FromString("101") + +bodyPricePointCreateComponentPricePointPrices1UnitPrice := models.PriceUnitPriceContainer.FromString("4.00") + +bodyPricePointCreateComponentPricePointPrices1 := models.Price{ + StartingQuantity: bodyPricePointCreateComponentPricePointPrices1StartingQuantity, + UnitPrice: bodyPricePointCreateComponentPricePointPrices1UnitPrice, } -bodyPricePointPrices := []models.Price{bodyPricePointPrices0, bodyPricePointPrices1} -bodyPricePoint := models.PricePoint{ - Name: models.ToPointer("Wholesale"), - Handle: models.ToPointer("wholesale-handle"), - PricingScheme: models.ToPointer(models.PricingScheme("stairstep")), - Prices: bodyPricePointPrices, +bodyPricePointCreateComponentPricePointPrices := []models.Price{bodyPricePointCreateComponentPricePointPrices0, bodyPricePointCreateComponentPricePointPrices1} +bodyPricePointCreateComponentPricePoint := models.CreateComponentPricePoint{ + Name: "Wholesale", + Handle: models.ToPointer("wholesale-handle"), + PricingScheme: models.PricingScheme("stairstep"), + Prices: bodyPricePointCreateComponentPricePointPrices, } +bodyPricePoint := models.CreateComponentPricePointRequestPricePointContainer.FromCreateComponentPricePoint(bodyPricePointCreateComponentPricePoint) + body := models.CreateComponentPricePointRequest{ PricePoint: bodyPricePoint, } @@ -1479,179 +1525,201 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# List Component Price Points - +} +``` + + +# List Component Price Points + Use this endpoint to read current price points that are associated with a component. You may specify the component by using either the numeric id or the `handle:gold` syntax. When fetching a component's price points, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. -If the price point is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - -```go -ListComponentPricePoints( - ctx context.Context,input ListComponentPricePointsInput) ( +If the price point is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + +```go +ListComponentPricePoints( + ctx context.Context, + input ListComponentPricePointsInput) ( models.ApiResponse[models.ComponentPricePointsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `int` | Template, Required | The Chargify id of the component | -| `currencyPrices` | `*bool` | Query, Optional | Include an array of currency price data | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `filterType` | [`[]models.PricePointType`](../../doc/models/price-point-type.md) | Query, Optional | Use in query: `filter[type]=catalog,default`. | - -## Response Type - -[`models.ComponentPricePointsResponse`](../../doc/models/component-price-points-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `int` | Template, Required | The Chargify id of the component | +| `currencyPrices` | `*bool` | Query, Optional | Include an array of currency price data | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `filterType` | [`[]models.PricePointType`](../../doc/models/price-point-type.md) | Query, Optional | Use in query: `filter[type]=catalog,default`. | + +## Response Type + +[`models.ComponentPricePointsResponse`](../../doc/models/component-price-points-response.md) + +## Example Usage + +```go ctx := context.Background() -componentId := 222 -page := 2 -perPage := 50Liquid error: Value cannot be null. (Parameter 'key') -apiResponse, err := componentsController.ListComponentPricePoints(ctx, componentId, nil, &page, &perPage, Liquid error: Value cannot be null. (Parameter 'key')) +collectedInput := advancedbilling.ListComponentPricePointsInput{ + ComponentId: 222, + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := componentsController.ListComponentPricePoints(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_points": [ - { - "id": 80, - "default": false, - "name": "Wholesale Two", - "pricing_scheme": "per_unit", - "component_id": 74, - "handle": "wholesale-two", - "archived_at": null, - "created_at": "2017-07-05T13:55:40-04:00", - "updated_at": "2017-07-05T13:55:40-04:00", - "prices": [ - { - "id": 121, - "component_id": 74, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "5.0" - } - ] - }, - { - "id": 81, - "default": false, - "name": "MSRP", - "pricing_scheme": "per_unit", - "component_id": 74, - "handle": "msrp", - "archived_at": null, - "created_at": "2017-07-05T13:55:40-04:00", - "updated_at": "2017-07-05T13:55:40-04:00", - "prices": [ - { - "id": 122, - "component_id": 74, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "4.0" - } - ] - } - ] -} -``` - - -# Bulk Create Component Price Points - -Use this endpoint to create multiple component price points in one request. - -```go -BulkCreateComponentPricePoints( - ctx context.Context, - componentId string, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_points": [ + { + "id": 80, + "default": false, + "name": "Wholesale Two", + "pricing_scheme": "per_unit", + "component_id": 74, + "handle": "wholesale-two", + "archived_at": null, + "created_at": "2017-07-05T13:55:40-04:00", + "updated_at": "2017-07-05T13:55:40-04:00", + "prices": [ + { + "id": 121, + "component_id": 74, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "5.0" + } + ] + }, + { + "id": 81, + "default": false, + "name": "MSRP", + "pricing_scheme": "per_unit", + "component_id": 74, + "handle": "msrp", + "archived_at": null, + "created_at": "2017-07-05T13:55:40-04:00", + "updated_at": "2017-07-05T13:55:40-04:00", + "prices": [ + { + "id": 122, + "component_id": 74, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "4.0" + } + ] + } + ] +} +``` + + +# Bulk Create Component Price Points + +Use this endpoint to create multiple component price points in one request. + +```go +BulkCreateComponentPricePoints( + ctx context.Context, + componentId string, body *models.CreateComponentPricePointsRequest) ( models.ApiResponse[models.ComponentPricePointsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | The Chargify id of the component for which you want to fetch price points. | -| `body` | [`*models.CreateComponentPricePointsRequest`](../../doc/models/create-component-price-points-request.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentPricePointsResponse`](../../doc/models/component-price-points-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `string` | Template, Required | The Chargify id of the component for which you want to fetch price points. | +| `body` | [`*models.CreateComponentPricePointsRequest`](../../doc/models/create-component-price-points-request.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentPricePointsResponse`](../../doc/models/component-price-points-response.md) + +## Example Usage + +```go ctx := context.Background() componentId := "component_id8" -bodyPricePoints0Prices0 := models.Price{ - StartingQuantity: interface{}("[key1, val1][key2, val2]"), - UnitPrice: interface{}("[key1, val1][key2, val2]"), +bodyPricePoints0CreateComponentPricePointPrices0StartingQuantity := models.PriceStartingQuantityContainer.FromNumber(1) + +bodyPricePoints0CreateComponentPricePointPrices0UnitPrice := models.PriceUnitPriceContainer.FromPrecision(float64(5)) + +bodyPricePoints0CreateComponentPricePointPrices0 := models.Price{ + StartingQuantity: bodyPricePoints0CreateComponentPricePointPrices0StartingQuantity, + UnitPrice: bodyPricePoints0CreateComponentPricePointPrices0UnitPrice, } -bodyPricePoints0Prices := []models.Price{bodyPricePoints0Prices0} -bodyPricePoints0 := models.PricePoint{ - Name: models.ToPointer("Wholesale"), - Handle: models.ToPointer("wholesale"), - PricingScheme: models.ToPointer(models.PricingScheme("per_unit")), - Prices: bodyPricePoints0Prices, +bodyPricePoints0CreateComponentPricePointPrices := []models.Price{bodyPricePoints0CreateComponentPricePointPrices0} +bodyPricePoints0CreateComponentPricePoint := models.CreateComponentPricePoint{ + Name: "Wholesale", + Handle: models.ToPointer("wholesale"), + PricingScheme: models.PricingScheme("per_unit"), + Prices: bodyPricePoints0CreateComponentPricePointPrices, } -bodyPricePoints1Prices0 := models.Price{ - StartingQuantity: interface{}("[key1, val1][key2, val2]"), - UnitPrice: interface{}("[key1, val1][key2, val2]"), +bodyPricePoints0 := models.CreateComponentPricePointsRequestPricePointsContainer.FromCreateComponentPricePoint(bodyPricePoints0CreateComponentPricePoint) + +bodyPricePoints1CreateComponentPricePointPrices0StartingQuantity := models.PriceStartingQuantityContainer.FromNumber(1) + +bodyPricePoints1CreateComponentPricePointPrices0UnitPrice := models.PriceUnitPriceContainer.FromPrecision(float64(4)) + +bodyPricePoints1CreateComponentPricePointPrices0 := models.Price{ + StartingQuantity: bodyPricePoints1CreateComponentPricePointPrices0StartingQuantity, + UnitPrice: bodyPricePoints1CreateComponentPricePointPrices0UnitPrice, } -bodyPricePoints1Prices := []models.Price{bodyPricePoints1Prices0} -bodyPricePoints1 := models.PricePoint{ - Name: models.ToPointer("MSRP"), - Handle: models.ToPointer("msrp"), - PricingScheme: models.ToPointer(models.PricingScheme("per_unit")), - Prices: bodyPricePoints1Prices, +bodyPricePoints1CreateComponentPricePointPrices := []models.Price{bodyPricePoints1CreateComponentPricePointPrices0} +bodyPricePoints1CreateComponentPricePoint := models.CreateComponentPricePoint{ + Name: "MSRP", + Handle: models.ToPointer("msrp"), + PricingScheme: models.PricingScheme("per_unit"), + Prices: bodyPricePoints1CreateComponentPricePointPrices, } -bodyPricePoints2Prices0 := models.Price{ - StartingQuantity: interface{}("[key1, val1][key2, val2]"), - UnitPrice: interface{}("[key1, val1][key2, val2]"), +bodyPricePoints1 := models.CreateComponentPricePointsRequestPricePointsContainer.FromCreateComponentPricePoint(bodyPricePoints1CreateComponentPricePoint) + +bodyPricePoints2CreateComponentPricePointPrices0StartingQuantity := models.PriceStartingQuantityContainer.FromNumber(1) + +bodyPricePoints2CreateComponentPricePointPrices0UnitPrice := models.PriceUnitPriceContainer.FromPrecision(float64(5)) + +bodyPricePoints2CreateComponentPricePointPrices0 := models.Price{ + StartingQuantity: bodyPricePoints2CreateComponentPricePointPrices0StartingQuantity, + UnitPrice: bodyPricePoints2CreateComponentPricePointPrices0UnitPrice, } -bodyPricePoints2Prices := []models.Price{bodyPricePoints2Prices0} -bodyPricePoints2 := models.PricePoint{ - Name: models.ToPointer("Special Pricing"), - Handle: models.ToPointer("special"), - PricingScheme: models.ToPointer(models.PricingScheme("per_unit")), - Prices: bodyPricePoints2Prices, +bodyPricePoints2CreateComponentPricePointPrices := []models.Price{bodyPricePoints2CreateComponentPricePointPrices0} +bodyPricePoints2CreateComponentPricePoint := models.CreateComponentPricePoint{ + Name: "Special Pricing", + Handle: models.ToPointer("special"), + PricingScheme: models.PricingScheme("per_unit"), + Prices: bodyPricePoints2CreateComponentPricePointPrices, } -bodyPricePoints := []models.PricePoint{bodyPricePoints0, bodyPricePoints1, bodyPricePoints2} +bodyPricePoints2 := models.CreateComponentPricePointsRequestPricePointsContainer.FromCreateComponentPricePoint(bodyPricePoints2CreateComponentPricePoint) + +bodyPricePoints := []models.CreateComponentPricePointsRequestPricePoints{bodyPricePoints0, bodyPricePoints1, bodyPricePoints2} body := models.CreateComponentPricePointsRequest{ PricePoints: bodyPricePoints, } @@ -1663,102 +1731,106 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_points": [ - { - "id": 80, - "default": false, - "name": "Wholesale Two", - "pricing_scheme": "per_unit", - "component_id": 74, - "handle": "wholesale-two", - "archived_at": null, - "created_at": "2017-07-05T13:55:40-04:00", - "updated_at": "2017-07-05T13:55:40-04:00", - "prices": [ - { - "id": 121, - "component_id": 74, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "5.0" - } - ] - }, - { - "id": 81, - "default": false, - "name": "MSRP", - "pricing_scheme": "per_unit", - "component_id": 74, - "handle": "msrp", - "archived_at": null, - "created_at": "2017-07-05T13:55:40-04:00", - "updated_at": "2017-07-05T13:55:40-04:00", - "prices": [ - { - "id": 122, - "component_id": 74, - "starting_quantity": 1, - "ending_quantity": null, - "unit_price": "4.0" - } - ] - } - ] -} -``` - - -# Update Component Price Point - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_points": [ + { + "id": 80, + "default": false, + "name": "Wholesale Two", + "pricing_scheme": "per_unit", + "component_id": 74, + "handle": "wholesale-two", + "archived_at": null, + "created_at": "2017-07-05T13:55:40-04:00", + "updated_at": "2017-07-05T13:55:40-04:00", + "prices": [ + { + "id": 121, + "component_id": 74, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "5.0" + } + ] + }, + { + "id": 81, + "default": false, + "name": "MSRP", + "pricing_scheme": "per_unit", + "component_id": 74, + "handle": "msrp", + "archived_at": null, + "created_at": "2017-07-05T13:55:40-04:00", + "updated_at": "2017-07-05T13:55:40-04:00", + "prices": [ + { + "id": 122, + "component_id": 74, + "starting_quantity": 1, + "ending_quantity": null, + "unit_price": "4.0" + } + ] + } + ] +} +``` + + +# Update Component Price Point + When updating a price point, it's prices can be updated as well by creating new prices or editing / removing existing ones. Passing in a price bracket without an `id` will attempt to create a new price. Including an `id` will update the corresponding price, and including the `_destroy` flag set to true along with the `id` will remove that price. -Note: Custom price points cannot be updated directly. They must be edited through the Subscription. - -```go -UpdateComponentPricePoint( - ctx context.Context, - componentId int, - pricePointId int, +Note: Custom price points cannot be updated directly. They must be edited through the Subscription. + +```go +UpdateComponentPricePoint( + ctx context.Context, + componentId int, + pricePointId int, body *models.UpdateComponentPricePointRequest) ( models.ApiResponse[models.ComponentPricePointResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | -| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | -| `body` | [`*models.UpdateComponentPricePointRequest`](../../doc/models/update-component-price-point-request.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentPricePointResponse`](../../doc/models/component-price-point-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | +| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | +| `body` | [`*models.UpdateComponentPricePointRequest`](../../doc/models/update-component-price-point-request.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentPricePointResponse`](../../doc/models/component-price-point-response.md) + +## Example Usage + +```go ctx := context.Background() componentId := 222 pricePointId := 10 +bodyPricePointPrices0EndingQuantity := models.UpdatePriceEndingQuantityContainer.FromNumber(100) + +bodyPricePointPrices0UnitPrice := models.UpdatePriceUnitPriceContainer.FromPrecision(float64(5)) + bodyPricePointPrices0 := models.UpdatePrice{ Id: models.ToPointer(1), - EndingQuantity: models.ToPointer(interface{}("[key1, val1][key2, val2]")), - UnitPrice: models.ToPointer(interface{}("[key1, val1][key2, val2]")), + EndingQuantity: models.ToPointer(bodyPricePointPrices0EndingQuantity), + UnitPrice: models.ToPointer(bodyPricePointPrices0UnitPrice), } bodyPricePointPrices1 := models.UpdatePrice{ @@ -1766,9 +1838,13 @@ bodyPricePointPrices1 := models.UpdatePrice{ Destroy: models.ToPointer(true), } +bodyPricePointPrices2UnitPrice := models.UpdatePriceUnitPriceContainer.FromPrecision(float64(4)) + +bodyPricePointPrices2StartingQuantity := models.UpdatePriceStartingQuantityContainer.FromNumber(101) + bodyPricePointPrices2 := models.UpdatePrice{ - UnitPrice: models.ToPointer(interface{}("[key1, val1][key2, val2]")), - StartingQuantity: models.ToPointer(interface{}("[key1, val1][key2, val2]")), + UnitPrice: models.ToPointer(bodyPricePointPrices2UnitPrice), + StartingQuantity: models.ToPointer(bodyPricePointPrices2StartingQuantity), } bodyPricePointPrices := []models.UpdatePrice{bodyPricePointPrices0, bodyPricePointPrices1, bodyPricePointPrices2} @@ -1788,43 +1864,43 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | - - -# Archive Component Price Point - -A price point can be archived at any time. Subscriptions using a price point that has been archived will continue using it until they're moved to another price point. - -```go -ArchiveComponentPricePoint( - ctx context.Context, - componentId int, +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + + +# Archive Component Price Point + +A price point can be archived at any time. Subscriptions using a price point that has been archived will continue using it until they're moved to another price point. + +```go +ArchiveComponentPricePoint( + ctx context.Context, + componentId int, pricePointId int) ( models.ApiResponse[models.ComponentPricePointResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | -| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | - -## Response Type - -[`models.ComponentPricePointResponse`](../../doc/models/component-price-point-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | +| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | + +## Response Type + +[`models.ComponentPricePointResponse`](../../doc/models/component-price-point-response.md) + +## Example Usage + +```go ctx := context.Background() componentId := 222 pricePointId := 10 @@ -1836,77 +1912,77 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_point": { - "id": 79, - "default": false, - "name": "Wholesale", - "pricing_scheme": "stairstep", - "component_id": 74, - "handle": "wholesale-handle", - "archived_at": "2017-07-06T15:04:00-04:00", - "created_at": "2017-07-05T13:44:30-04:00", - "updated_at": "2017-07-05T13:44:30-04:00", - "prices": [ - { - "id": 119, - "component_id": 74, - "starting_quantity": 1, - "ending_quantity": 100, - "unit_price": "5.0" - }, - { - "id": 120, - "component_id": 74, - "starting_quantity": 101, - "ending_quantity": null, - "unit_price": "4.0" - } - ] - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Unarchive Component Price Point - -Use this endpoint to unarchive a component price point. - -```go -UnarchiveComponentPricePoint( - ctx context.Context, - componentId int, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_point": { + "id": 79, + "default": false, + "name": "Wholesale", + "pricing_scheme": "stairstep", + "component_id": 74, + "handle": "wholesale-handle", + "archived_at": "2017-07-06T15:04:00-04:00", + "created_at": "2017-07-05T13:44:30-04:00", + "updated_at": "2017-07-05T13:44:30-04:00", + "prices": [ + { + "id": 119, + "component_id": 74, + "starting_quantity": 1, + "ending_quantity": 100, + "unit_price": "5.0" + }, + { + "id": 120, + "component_id": 74, + "starting_quantity": 101, + "ending_quantity": null, + "unit_price": "4.0" + } + ] + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Unarchive Component Price Point + +Use this endpoint to unarchive a component price point. + +```go +UnarchiveComponentPricePoint( + ctx context.Context, + componentId int, pricePointId int) ( models.ApiResponse[models.ComponentPricePointResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | -| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | - -## Response Type - -[`models.ComponentPricePointResponse`](../../doc/models/component-price-point-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `int` | Template, Required | The Chargify id of the component to which the price point belongs | +| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | + +## Response Type + +[`models.ComponentPricePointResponse`](../../doc/models/component-price-point-response.md) + +## Example Usage + +```go ctx := context.Background() componentId := 222 pricePointId := 10 @@ -1918,75 +1994,75 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_point": { - "id": 79, - "default": false, - "name": "Wholesale", - "pricing_scheme": "stairstep", - "component_id": 74, - "handle": "wholesale-handle", - "archived_at": null, - "created_at": "2017-07-05T13:44:30-04:00", - "updated_at": "2017-07-05T13:44:30-04:00", - "prices": [ - { - "id": 119, - "component_id": 74, - "starting_quantity": 1, - "ending_quantity": 100, - "unit_price": "5.0" - }, - { - "id": 120, - "component_id": 74, - "starting_quantity": 101, - "ending_quantity": null, - "unit_price": "4.0" - } - ] - } -} -``` - - -# Create Currency Prices - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_point": { + "id": 79, + "default": false, + "name": "Wholesale", + "pricing_scheme": "stairstep", + "component_id": 74, + "handle": "wholesale-handle", + "archived_at": null, + "created_at": "2017-07-05T13:44:30-04:00", + "updated_at": "2017-07-05T13:44:30-04:00", + "prices": [ + { + "id": 119, + "component_id": 74, + "starting_quantity": 1, + "ending_quantity": 100, + "unit_price": "5.0" + }, + { + "id": 120, + "component_id": 74, + "starting_quantity": 101, + "ending_quantity": null, + "unit_price": "4.0" + } + ] + } +} +``` + + +# Create Currency Prices + This endpoint allows you to create currency prices for a given currency that has been defined on the site level in your settings. When creating currency prices, they need to mirror the structure of your primary pricing. For each price level defined on the component price point, there should be a matching price level created in the given currency. -Note: Currency Prices are not able to be created for custom price points. - -```go -CreateCurrencyPrices( - ctx context.Context, - pricePointId int, +Note: Currency Prices are not able to be created for custom price points. + +```go +CreateCurrencyPrices( + ctx context.Context, + pricePointId int, body *models.CreateCurrencyPricesRequest) ( models.ApiResponse[models.ComponentCurrencyPricesResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | -| `body` | [`*models.CreateCurrencyPricesRequest`](../../doc/models/create-currency-prices-request.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentCurrencyPricesResponse`](../../doc/models/component-currency-prices-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | +| `body` | [`*models.CreateCurrencyPricesRequest`](../../doc/models/create-currency-prices-request.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentCurrencyPricesResponse`](../../doc/models/component-currency-prices-response.md) + +## Example Usage + +```go ctx := context.Background() pricePointId := 10 @@ -2014,62 +2090,62 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "currency_prices": [ - { - "id": 100, - "currency": "EUR", - "price": "123", - "formatted_price": "€123,00", - "price_id": 32669, - "price_point_id": 25554 - } - ] -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | - - -# Update Currency Prices - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "currency_prices": [ + { + "id": 100, + "currency": "EUR", + "price": "123", + "formatted_price": "€123,00", + "price_id": 32669, + "price_point_id": 25554 + } + ] +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + + +# Update Currency Prices + This endpoint allows you to update currency prices for a given currency that has been defined on the site level in your settings. -Note: Currency Prices are not able to be updated for custom price points. - -```go -UpdateCurrencyPrices( - ctx context.Context, - pricePointId int, +Note: Currency Prices are not able to be updated for custom price points. + +```go +UpdateCurrencyPrices( + ctx context.Context, + pricePointId int, body *models.UpdateCurrencyPricesRequest) ( models.ApiResponse[models.ComponentCurrencyPricesResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | -| `body` | [`*models.UpdateCurrencyPricesRequest`](../../doc/models/update-currency-prices-request.md) | Body, Optional | - | - -## Response Type - -[`models.ComponentCurrencyPricesResponse`](../../doc/models/component-currency-prices-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `pricePointId` | `int` | Template, Required | The Chargify id of the price point | +| `body` | [`*models.UpdateCurrencyPricesRequest`](../../doc/models/update-currency-prices-request.md) | Body, Optional | - | + +## Response Type + +[`models.ComponentCurrencyPricesResponse`](../../doc/models/component-currency-prices-response.md) + +## Example Usage + +```go ctx := context.Background() pricePointId := 10 @@ -2095,119 +2171,123 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "currency_prices": [ - { - "id": 100, - "currency": "EUR", - "price": "123", - "formatted_price": "€123,00", - "price_id": 32669, - "price_point_id": 25554 - } - ] -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | - - -# List All Component Price Points - -This method allows to retrieve a list of Components Price Points belonging to a Site. - -```go -ListAllComponentPricePoints( - ctx context.Context,input ListAllComponentPricePointsInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "currency_prices": [ + { + "id": 100, + "currency": "EUR", + "price": "123", + "formatted_price": "€123,00", + "price_id": 32669, + "price_point_id": 25554 + } + ] +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + + +# List All Component Price Points + +This method allows to retrieve a list of Components Price Points belonging to a Site. + +```go +ListAllComponentPricePoints( + ctx context.Context, + input ListAllComponentPricePointsInput) ( models.ApiResponse[models.ListComponentsPricePointsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `filterDateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query: `filter[date_field]=created_at`. | -| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `filterEndDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | -| `include` | [`*models.ListComponentsPricePointsInclude`](../../doc/models/list-components-price-points-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include=currency_prices`. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `filterStartDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `filterType` | [`[]models.PricePointType`](../../doc/models/price-point-type.md) | Query, Optional | Allows fetching price points with matching type. Use in query: `filter[type]=custom,catalog`. | -| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | -| `filterIds` | `[]int` | Query, Optional | Allows fetching price points with matching id based on provided values. Use in query: `filter[ids]=1,2,3`. | -| `filterArchivedAt` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching price points only if archived_at is present or not. Use in query: `filter[archived_at]=not_null`. | - -## Response Type - -[`models.ListComponentsPricePointsResponse`](../../doc/models/list-components-price-points-response.md) - -## Example Usage - -```go -ctx := context.Background()Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') -include := models.ListComponentsPricePointsInclude("currency_prices") -page := 2 -perPage := 50Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') - -apiResponse, err := componentsController.ListAllComponentPricePoints(ctx, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), &include, &page, &perPage, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), nil, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key')) + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `filterDateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query: `filter[date_field]=created_at`. | +| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `filterEndDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | +| `include` | [`*models.ListComponentsPricePointsInclude`](../../doc/models/list-components-price-points-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include=currency_prices`. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `filterStartDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `filterType` | [`[]models.PricePointType`](../../doc/models/price-point-type.md) | Query, Optional | Allows fetching price points with matching type. Use in query: `filter[type]=custom,catalog`. | +| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | +| `filterIds` | `[]int` | Query, Optional | Allows fetching price points with matching id based on provided values. Use in query: `filter[ids]=1,2,3`. | +| `filterArchivedAt` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching price points only if archived_at is present or not. Use in query: `filter[archived_at]=not_null`. | + +## Response Type + +[`models.ListComponentsPricePointsResponse`](../../doc/models/list-components-price-points-response.md) + +## Example Usage + +```go +ctx := context.Background() +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') +collectedInput := advancedbilling.ListAllComponentPricePointsInput{ +Liquid error: Value cannot be null. (Parameter 'key') Include: models.ToPointer(models.ListComponentsPricePointsInclude("currency_prices")), + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := componentsController.ListAllComponentPricePoints(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_points": [ - { - "id": 1, - "name": "Auto-created", - "type": "default", - "pricing_scheme": "per_unit", - "component_id": 2, - "handle": "auto-created", - "archived_at": null, - "created_at": "2021-02-21T11:05:57-05:00", - "updated_at": "2021-02-21T11:05:57-05:00", - "prices": [ - { - "id": 3, - "component_id": 2, - "starting_quantity": 0, - "ending_quantity": null, - "unit_price": "1.0", - "price_point_id": 1, - "formatted_unit_price": "$1.00", - "segment_id": null - } - ], - "tax_included": false - } - ] -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_points": [ + { + "id": 1, + "name": "Auto-created", + "type": "default", + "pricing_scheme": "per_unit", + "component_id": 2, + "handle": "auto-created", + "archived_at": null, + "created_at": "2021-02-21T11:05:57-05:00", + "updated_at": "2021-02-21T11:05:57-05:00", + "prices": [ + { + "id": 3, + "component_id": 2, + "starting_quantity": 0, + "ending_quantity": null, + "unit_price": "1.0", + "price_point_id": 1, + "formatted_unit_price": "$1.00", + "segment_id": null + } + ], + "tax_included": false + } + ] +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/controllers/coupons.md b/doc/controllers/coupons.md index 9068dfec..10f1bcab 100644 --- a/doc/controllers/coupons.md +++ b/doc/controllers/coupons.md @@ -1,15 +1,15 @@ -# Coupons - -```go -couponsController := client.CouponsController() -``` - -## Class Name - -`CouponsController` - -## Methods - +# Coupons + +```go +couponsController := client.CouponsController() +``` + +## Class Name + +`CouponsController` + +## Methods + * [Create Coupon](../../doc/controllers/coupons.md#create-coupon) * [List Coupons for Product Family](../../doc/controllers/coupons.md#list-coupons-for-product-family) * [Find Coupon](../../doc/controllers/coupons.md#find-coupon) @@ -23,11 +23,11 @@ couponsController := client.CouponsController() * [Create Coupon Subcodes](../../doc/controllers/coupons.md#create-coupon-subcodes) * [List Coupon Subcodes](../../doc/controllers/coupons.md#list-coupon-subcodes) * [Update Coupon Subcodes](../../doc/controllers/coupons.md#update-coupon-subcodes) -* [Delete Coupon Subcode](../../doc/controllers/coupons.md#delete-coupon-subcode) - - -# Create Coupon - +* [Delete Coupon Subcode](../../doc/controllers/coupons.md#delete-coupon-subcode) + + +# Create Coupon + ## Coupons Documentation Coupons can be administered in the Chargify application or created via API. Please view our section on [creating coupons](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404742830733) for more information. @@ -41,43 +41,64 @@ This request will create a coupon, based on the provided information. When creating a coupon, you must specify a product family using the `product_family_id`. If no `product_family_id` is passed, the first product family available is used. You will also need to formulate your URL to cite the Product Family ID in your request. You can restrict a coupon to only apply to specific products / components by optionally passing in hashes of `restricted_products` and/or `restricted_components` in the format: -`{ "": boolean_value }` - -```go -CreateCoupon( - ctx context.Context, - productFamilyId int, +`{ "": boolean_value }` + +```go +CreateCoupon( + ctx context.Context, + productFamilyId int, body *models.CreateOrUpdateCoupon) ( models.ApiResponse[models.CouponResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | -| `body` | [`*models.CreateOrUpdateCoupon`](../../doc/models/create-or-update-coupon.md) | Body, Optional | - | - -## Response Type - -[`models.CouponResponse`](../../doc/models/coupon-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | +| `body` | [`*models.CreateOrUpdateCoupon`](../../doc/models/create-or-update-coupon.md) | Body, Optional | - | + +## Response Type + +[`models.CouponResponse`](../../doc/models/coupon-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 +bodyCouponCreateOrUpdatePercentageCouponEndDate, err := time.Parse(time.RFC3339, "2012-08-29T12:00:00-04:00") +if err != nil { + log.Fatalln(err) +} +bodyCouponCreateOrUpdatePercentageCouponPercentage := models.CreateOrUpdatePercentageCouponPercentageContainer.FromPrecision(float64(15)) + +bodyCouponCreateOrUpdatePercentageCoupon := models.CreateOrUpdatePercentageCoupon{ + Name: "15% off", + Code: "15OFF", + Description: models.ToPointer("15% off for life"), + ProductFamilyId: models.ToPointer("2"), + Stackable: models.ToPointer(true), + CompoundingStrategy: models.ToPointer(models.CompoundingStrategy("compound")), + ExcludeMidPeriodAllocations: models.ToPointer(true), + ApplyOnCancelAtEndOfPeriod: models.ToPointer(true), + EndDate: models.ToPointer(bodyCouponCreateOrUpdatePercentageCouponEndDate), + Percentage: bodyCouponCreateOrUpdatePercentageCouponPercentage, +} + +bodyCoupon := models.CreateOrUpdateCouponCouponContainer.FromCreateOrUpdatePercentageCoupon(bodyCouponCreateOrUpdatePercentageCoupon) + body := models.CreateOrUpdateCoupon{ - Coupon: models.ToPointer(interface{}("[name, 15% off][code, 15OFF][description, 15% off for life][percentage, 15][allow_negative_balance, False][recurring, False][end_date, 2012-08-29T12:00:00-04:00][product_family_id, 2][stackable, True][compounding_strategy, compound][exclude_mid_period_allocations, True][apply_on_cancel_at_end_of_period, True]")), RestrictedProducts: map[string]bool{ -"1" : true, + "1" : true, }, RestrictedComponents: map[string]bool{ -"1" : true, -"2" : false, + "1" : true, + "2" : false, }, + Coupon: models.ToPointer(bodyCoupon), } apiResponse, err := couponsController.CreateCoupon(ctx, productFamilyId, &body) @@ -87,192 +108,196 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Coupons for Product Family - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Coupons for Product Family + List coupons for a specific Product Family in a Site. -If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - -```go -ListCouponsForProductFamily( - ctx context.Context,input ListCouponsForProductFamilyInput) ( +If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + +```go +ListCouponsForProductFamily( + ctx context.Context, + input ListCouponsForProductFamilyInput) ( models.ApiResponse[[]models.CouponResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `filterDateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `filter[date_field]=created_at`. | -| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `filter[date_field]=2011-12-15`. | -| `filterEndDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `?filter[end_datetime]=2011-12-1T10:15:30+01:00`. | -| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `filter[start_date]=2011-12-17`. | -| `filterStartDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `filter[start_datetime]=2011-12-19T10:15:30+01:00`. | -| `filterIds` | `[]int` | Query, Optional | Allows fetching coupons with matching id based on provided values. Use in query `filter[ids]=1,2,3`. | -| `filterCodes` | `[]string` | Query, Optional | Allows fetching coupons with matching codes based on provided values. Use in query `filter[codes]=free,free_trial`. | -| `currencyPrices` | `*bool` | Query, Optional | When fetching coupons, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. Use in query `currency_prices=true`. | -| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching coupons with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | - -## Response Type - -[`[]models.CouponResponse`](../../doc/models/coupon-response.md) - -## Example Usage - -```go -ctx := context.Background() -productFamilyId := 140 -page := 2 -perPage := 50Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') -currencyPrices := trueLiquid error: Value cannot be null. (Parameter 'key') + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `filterDateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `filter[date_field]=created_at`. | +| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `filter[date_field]=2011-12-15`. | +| `filterEndDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `?filter[end_datetime]=2011-12-1T10:15:30+01:00`. | +| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `filter[start_date]=2011-12-17`. | +| `filterStartDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `filter[start_datetime]=2011-12-19T10:15:30+01:00`. | +| `filterIds` | `[]int` | Query, Optional | Allows fetching coupons with matching id based on provided values. Use in query `filter[ids]=1,2,3`. | +| `filterCodes` | `[]string` | Query, Optional | Allows fetching coupons with matching codes based on provided values. Use in query `filter[codes]=free,free_trial`. | +| `currencyPrices` | `*bool` | Query, Optional | When fetching coupons, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. Use in query `currency_prices=true`. | +| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching coupons with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | + +## Response Type + +[`[]models.CouponResponse`](../../doc/models/coupon-response.md) -apiResponse, err := couponsController.ListCouponsForProductFamily(ctx, productFamilyId, &page, &perPage, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), ¤cyPrices, Liquid error: Value cannot be null. (Parameter 'key')) +## Example Usage + +```go +ctx := context.Background() +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') +collectedInput := advancedbilling.ListCouponsForProductFamilyInput{ + ProductFamilyId: 140, + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') CurrencyPrices: models.ToPointer(true), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := couponsController.ListCouponsForProductFamily(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "coupon": { - "id": 999999, - "name": "50% coupon", - "code": "50PERCENT", - "description": "50 PERCENT OFF", - "amount_in_cents": null, - "product_family_id": 527890, - "created_at": "2016-10-21T17:02:08-04:00", - "updated_at": "2016-10-21T17:06:11-04:00", - "start_date": "2016-10-21T17:02:08-04:00", - "end_date": null, - "percentage": "50", - "recurring": true, - "duration_period_count": null, - "duration_interval": 1, - "duration_interval_unit": "day", - "allow_negative_balance": true, - "archived_at": null, - "conversion_limit": "100", - "stackable": false, - "compounding_strategy": "compound", - "coupon_restrictions": [], - "use_site_exchange_rate": true - } - }, - { - "coupon": { - "id": 123456, - "name": "100% coupon", - "code": "100PERCENT", - "description": "100 PERCENT OFF", - "amount_in_cents": null, - "product_family_id": 527890, - "created_at": "2016-10-21T17:02:08-04:00", - "updated_at": "2016-10-21T17:06:11-04:00", - "start_date": "2016-10-21T17:02:08-04:00", - "end_date": null, - "percentage": "50", - "recurring": true, - "duration_period_count": null, - "duration_interval": 1, - "duration_interval_unit": "day", - "allow_negative_balance": true, - "archived_at": null, - "conversion_limit": "100", - "stackable": false, - "compounding_strategy": "compound", - "coupon_restrictions": [], - "use_site_exchange_rate": true - } - }, - { - "coupon": { - "id": 888888, - "name": "25% coupon", - "code": "25PERCENT", - "description": "25 PERCENT OFF", - "amount_in_cents": null, - "product_family_id": 527890, - "created_at": "2016-10-21T17:02:08-04:00", - "updated_at": "2016-10-21T17:06:11-04:00", - "start_date": "2016-10-21T17:02:08-04:00", - "end_date": null, - "percentage": "25", - "recurring": true, - "duration_period_count": null, - "duration_interval": 1, - "duration_interval_unit": "day", - "allow_negative_balance": true, - "archived_at": null, - "conversion_limit": "100", - "stackable": false, - "compounding_strategy": "compound", - "coupon_restrictions": [ - { - "id": 37, - "item_type": "Component", - "item_id": 519, - "name": "test", - "handle": null - } - ], - "use_site_exchange_rate": true - } - } -] -``` - - -# Find Coupon - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "coupon": { + "id": 999999, + "name": "50% coupon", + "code": "50PERCENT", + "description": "50 PERCENT OFF", + "amount_in_cents": null, + "product_family_id": 527890, + "created_at": "2016-10-21T17:02:08-04:00", + "updated_at": "2016-10-21T17:06:11-04:00", + "start_date": "2016-10-21T17:02:08-04:00", + "end_date": null, + "percentage": "50", + "recurring": true, + "duration_period_count": null, + "duration_interval": 1, + "duration_interval_unit": "day", + "allow_negative_balance": true, + "archived_at": null, + "conversion_limit": "100", + "stackable": false, + "compounding_strategy": "compound", + "coupon_restrictions": [], + "use_site_exchange_rate": true + } + }, + { + "coupon": { + "id": 123456, + "name": "100% coupon", + "code": "100PERCENT", + "description": "100 PERCENT OFF", + "amount_in_cents": null, + "product_family_id": 527890, + "created_at": "2016-10-21T17:02:08-04:00", + "updated_at": "2016-10-21T17:06:11-04:00", + "start_date": "2016-10-21T17:02:08-04:00", + "end_date": null, + "percentage": "50", + "recurring": true, + "duration_period_count": null, + "duration_interval": 1, + "duration_interval_unit": "day", + "allow_negative_balance": true, + "archived_at": null, + "conversion_limit": "100", + "stackable": false, + "compounding_strategy": "compound", + "coupon_restrictions": [], + "use_site_exchange_rate": true + } + }, + { + "coupon": { + "id": 888888, + "name": "25% coupon", + "code": "25PERCENT", + "description": "25 PERCENT OFF", + "amount_in_cents": null, + "product_family_id": 527890, + "created_at": "2016-10-21T17:02:08-04:00", + "updated_at": "2016-10-21T17:06:11-04:00", + "start_date": "2016-10-21T17:02:08-04:00", + "end_date": null, + "percentage": "25", + "recurring": true, + "duration_period_count": null, + "duration_interval": 1, + "duration_interval_unit": "day", + "allow_negative_balance": true, + "archived_at": null, + "conversion_limit": "100", + "stackable": false, + "compounding_strategy": "compound", + "coupon_restrictions": [ + { + "id": 37, + "item_type": "Component", + "item_id": 519, + "name": "test", + "handle": null + } + ], + "use_site_exchange_rate": true + } + } +] +``` + + +# Find Coupon + You can search for a coupon via the API with the find method. By passing a code parameter, the find will attempt to locate a coupon that matches that code. If no coupon is found, a 404 is returned. -If you have more than one product family and if the coupon you are trying to find does not belong to the default product family in your site, then you will need to specify (either in the url or as a query string param) the product family id. - -```go -FindCoupon( - ctx context.Context, - productFamilyId *int, +If you have more than one product family and if the coupon you are trying to find does not belong to the default product family in your site, then you will need to specify (either in the url or as a query string param) the product family id. + +```go +FindCoupon( + ctx context.Context, + productFamilyId *int, code *string) ( models.ApiResponse[models.CouponResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `*int` | Query, Optional | The Chargify id of the product family to which the coupon belongs | -| `code` | `*string` | Query, Optional | The code of the coupon | - -## Response Type - -[`models.CouponResponse`](../../doc/models/coupon-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `*int` | Query, Optional | The Chargify id of the product family to which the coupon belongs | +| `code` | `*string` | Query, Optional | The code of the coupon | + +## Response Type + +[`models.CouponResponse`](../../doc/models/coupon-response.md) + +## Example Usage + +```go ctx := context.Background() apiResponse, err := couponsController.FindCoupon(ctx, nil, nil) @@ -282,42 +307,42 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Read Coupon - +} +``` + + +# Read Coupon + You can retrieve the Coupon via the API with the Show method. You must identify the Coupon in this call by the ID parameter that Chargify assigns. If instead you would like to find a Coupon using a Coupon code, see the Coupon Find method. When fetching a coupon, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. -If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - -```go -ReadCoupon( - ctx context.Context, - productFamilyId int, +If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + +```go +ReadCoupon( + ctx context.Context, + productFamilyId int, couponId int) ( models.ApiResponse[models.CouponResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon | - -## Response Type - -[`models.CouponResponse`](../../doc/models/coupon-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon | + +## Response Type + +[`models.CouponResponse`](../../doc/models/coupon-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 couponId := 162 @@ -329,87 +354,106 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "coupon": { - "id": 67, - "name": "Foo Bar", - "code": "YEPPER99934", - "description": "my cool coupon", - "amount_in_cents": null, - "product_family_id": 4, - "product_family_name": "Billing Plans", - "created_at": "2017-11-08T10:01:15-05:00", - "updated_at": "2017-11-08T10:01:15-05:00", - "start_date": "2017-11-08T10:01:15-05:00", - "end_date": null, - "percentage": "33.3333", - "duration_period_count": null, - "duration_interval": null, - "duration_interval_unit": null, - "allow_negative_balance": false, - "archived_at": null, - "conversion_limit": null, - "stackable": true, - "compounding_strategy": "compound", - "coupon_restrictions": [] - } -} -``` - - -# Update Coupon - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "coupon": { + "id": 67, + "name": "Foo Bar", + "code": "YEPPER99934", + "description": "my cool coupon", + "amount_in_cents": null, + "product_family_id": 4, + "product_family_name": "Billing Plans", + "created_at": "2017-11-08T10:01:15-05:00", + "updated_at": "2017-11-08T10:01:15-05:00", + "start_date": "2017-11-08T10:01:15-05:00", + "end_date": null, + "percentage": "33.3333", + "duration_period_count": null, + "duration_interval": null, + "duration_interval_unit": null, + "allow_negative_balance": false, + "archived_at": null, + "conversion_limit": null, + "stackable": true, + "compounding_strategy": "compound", + "coupon_restrictions": [] + } +} +``` + + +# Update Coupon + ## Update Coupon You can update a Coupon via the API with a PUT request to the resource endpoint. You can restrict a coupon to only apply to specific products / components by optionally passing in hashes of `restricted_products` and/or `restricted_components` in the format: -`{ "": boolean_value }` - -```go -UpdateCoupon( - ctx context.Context, - productFamilyId int, - couponId int, +`{ "": boolean_value }` + +```go +UpdateCoupon( + ctx context.Context, + productFamilyId int, + couponId int, body *models.CreateOrUpdateCoupon) ( models.ApiResponse[models.CouponResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon | -| `body` | [`*models.CreateOrUpdateCoupon`](../../doc/models/create-or-update-coupon.md) | Body, Optional | - | - -## Response Type - -[`models.CouponResponse`](../../doc/models/coupon-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon | +| `body` | [`*models.CreateOrUpdateCoupon`](../../doc/models/create-or-update-coupon.md) | Body, Optional | - | + +## Response Type + +[`models.CouponResponse`](../../doc/models/coupon-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 couponId := 162 +bodyCouponCreateOrUpdatePercentageCouponEndDate, err := time.Parse(time.RFC3339, "2012-08-29T12:00:00-04:00") +if err != nil { + log.Fatalln(err) +} +bodyCouponCreateOrUpdatePercentageCouponPercentage := models.CreateOrUpdatePercentageCouponPercentageContainer.FromPrecision(float64(15)) + +bodyCouponCreateOrUpdatePercentageCoupon := models.CreateOrUpdatePercentageCoupon{ + Name: "15% off", + Code: "15OFF", + Description: models.ToPointer("15% off for life"), + ProductFamilyId: models.ToPointer("2"), + Stackable: models.ToPointer(true), + CompoundingStrategy: models.ToPointer(models.CompoundingStrategy("compound")), + EndDate: models.ToPointer(bodyCouponCreateOrUpdatePercentageCouponEndDate), + Percentage: bodyCouponCreateOrUpdatePercentageCouponPercentage, +} + +bodyCoupon := models.CreateOrUpdateCouponCouponContainer.FromCreateOrUpdatePercentageCoupon(bodyCouponCreateOrUpdatePercentageCoupon) + body := models.CreateOrUpdateCoupon{ - Coupon: models.ToPointer(interface{}("[name, 15% off][code, 15OFF][description, 15% off for life][percentage, 15][allow_negative_balance, False][recurring, False][end_date, 2012-08-29T12:00:00-04:00][product_family_id, 2][stackable, True][compounding_strategy, compound]")), RestrictedProducts: map[string]bool{ -"1" : true, + "1" : true, }, RestrictedComponents: map[string]bool{ -"1" : true, -"2" : false, + "1" : true, + "2" : false, }, + Coupon: models.ToPointer(bodyCoupon), } apiResponse, err := couponsController.UpdateCoupon(ctx, productFamilyId, couponId, &body) @@ -419,69 +463,69 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "coupon": { - "id": 67, - "name": "Foo Bar", - "code": "YEPPER99934", - "description": "my cool coupon", - "amount_in_cents": 10000, - "product_family_id": 4, - "created_at": "2017-11-08T10:01:15-05:00", - "updated_at": "2017-11-08T10:01:15-05:00", - "start_date": "2017-11-08T10:01:15-05:00", - "end_date": null, - "percentage": null, - "recurring": false, - "duration_period_count": null, - "duration_interval": null, - "duration_interval_unit": null, - "allow_negative_balance": false, - "archived_at": null, - "conversion_limit": null, - "stackable": true, - "compounding_strategy": "compound", - "coupon_restrictions": [] - } -} -``` - - -# Archive Coupon - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "coupon": { + "id": 67, + "name": "Foo Bar", + "code": "YEPPER99934", + "description": "my cool coupon", + "amount_in_cents": 10000, + "product_family_id": 4, + "created_at": "2017-11-08T10:01:15-05:00", + "updated_at": "2017-11-08T10:01:15-05:00", + "start_date": "2017-11-08T10:01:15-05:00", + "end_date": null, + "percentage": null, + "recurring": false, + "duration_period_count": null, + "duration_interval": null, + "duration_interval_unit": null, + "allow_negative_balance": false, + "archived_at": null, + "conversion_limit": null, + "stackable": true, + "compounding_strategy": "compound", + "coupon_restrictions": [] + } +} +``` + + +# Archive Coupon + You can archive a Coupon via the API with the archive method. Archiving makes that Coupon unavailable for future use, but allows it to remain attached and functional on existing Subscriptions that are using it. -The `archived_at` date and time will be assigned. - -```go -ArchiveCoupon( - ctx context.Context, - productFamilyId int, +The `archived_at` date and time will be assigned. + +```go +ArchiveCoupon( + ctx context.Context, + productFamilyId int, couponId int) ( models.ApiResponse[models.CouponResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon | - -## Response Type - -[`models.CouponResponse`](../../doc/models/coupon-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon | + +## Response Type + +[`models.CouponResponse`](../../doc/models/coupon-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 couponId := 162 @@ -493,185 +537,192 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "coupon": { - "id": 67, - "name": "Foo Bar", - "code": "YEPPER99934", - "description": "my cool coupon", - "amount_in_cents": 10000, - "product_family_id": 4, - "created_at": "2017-11-08T10:01:15-05:00", - "updated_at": "2017-11-08T10:01:15-05:00", - "start_date": "2017-11-08T10:01:15-05:00", - "end_date": null, - "percentage": null, - "recurring": false, - "duration_period_count": null, - "duration_interval": null, - "duration_interval_unit": null, - "allow_negative_balance": false, - "archived_at": "2016-12-02T13:09:33-05:00", - "conversion_limit": null, - "stackable": true, - "compounding_strategy": "compound", - "coupon_restrictions": [] - } -} -``` - - -# List Coupons - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "coupon": { + "id": 67, + "name": "Foo Bar", + "code": "YEPPER99934", + "description": "my cool coupon", + "amount_in_cents": 10000, + "product_family_id": 4, + "created_at": "2017-11-08T10:01:15-05:00", + "updated_at": "2017-11-08T10:01:15-05:00", + "start_date": "2017-11-08T10:01:15-05:00", + "end_date": null, + "percentage": null, + "recurring": false, + "duration_period_count": null, + "duration_interval": null, + "duration_interval_unit": null, + "allow_negative_balance": false, + "archived_at": "2016-12-02T13:09:33-05:00", + "conversion_limit": null, + "stackable": true, + "compounding_strategy": "compound", + "coupon_restrictions": [] + } +} +``` + + +# List Coupons + You can retrieve a list of coupons. -If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. - -```go -ListCoupons( - ctx context.Context,input ListCouponsInput) ( +If the coupon is set to `use_site_exchange_rate: true`, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + +```go +ListCoupons( + ctx context.Context, + input ListCouponsInput) ( models.ApiResponse[[]models.CouponResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The field was deprecated: on January 20, 2022. We recommend using filter[date_field] instead to achieve the same result. The type of filter you would like to apply to your search. | -| `startDate` | `*time.Time` | Query, Optional | The field was deprecated: on January 20, 2022. We recommend using filter[start_date] instead to achieve the same result. The start date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `endDate` | `*time.Time` | Query, Optional | The field was deprecated: on January 20, 2022. We recommend using filter[end_date] instead to achieve the same result. The end date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `startDatetime` | `*time.Time` | Query, Optional | The field was deprecated: on January 20, 2022. We recommend using filter[start_datetime] instead to achieve the same result. The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `endDatetime` | `*time.Time` | Query, Optional | The field was deprecated: on January 20, 2022. We recommend using filter[end_datetime] instead to achieve the same result. The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | -| `filterIds` | `[]int` | Query, Optional | Allows fetching coupons with matching id based on provided values. Use in query `filter[ids]=1,2,3`. | -| `filterCodes` | `[]string` | Query, Optional | Allows fetching coupons with matching code based on provided values. Use in query `filter[ids]=1,2,3`. | -| `currencyPrices` | `*bool` | Query, Optional | When fetching coupons, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. Use in query `currency_prices=true`. | -| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `filter[end_date]=2011-12-17`. | -| `filterEndDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `filter[end_datetime]=2011-12-19T10:15:30+01:00`. | -| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `filter[start_date]=2011-12-19`. | -| `filterStartDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `filter[start_datetime]=2011-12-19T10:15:30+01:00`. | -| `filterDateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `filter[date_field]=updated_at`. | -| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching coupons with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | - -## Response Type - -[`[]models.CouponResponse`](../../doc/models/coupon-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The field was deprecated: on January 20, 2022. We recommend using filter[date_field] instead to achieve the same result. The type of filter you would like to apply to your search. | +| `startDate` | `*time.Time` | Query, Optional | The field was deprecated: on January 20, 2022. We recommend using filter[start_date] instead to achieve the same result. The start date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `endDate` | `*time.Time` | Query, Optional | The field was deprecated: on January 20, 2022. We recommend using filter[end_date] instead to achieve the same result. The end date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `startDatetime` | `*time.Time` | Query, Optional | The field was deprecated: on January 20, 2022. We recommend using filter[start_datetime] instead to achieve the same result. The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `endDatetime` | `*time.Time` | Query, Optional | The field was deprecated: on January 20, 2022. We recommend using filter[end_datetime] instead to achieve the same result. The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | +| `filterIds` | `[]int` | Query, Optional | Allows fetching coupons with matching id based on provided values. Use in query `filter[ids]=1,2,3`. | +| `filterCodes` | `[]string` | Query, Optional | Allows fetching coupons with matching code based on provided values. Use in query `filter[ids]=1,2,3`. | +| `currencyPrices` | `*bool` | Query, Optional | When fetching coupons, if you have defined multiple currencies at the site level, you can optionally pass the `?currency_prices=true` query param to include an array of currency price data in the response. Use in query `currency_prices=true`. | +| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `filter[end_date]=2011-12-17`. | +| `filterEndDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `filter[end_datetime]=2011-12-19T10:15:30+01:00`. | +| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns coupons with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `filter[start_date]=2011-12-19`. | +| `filterStartDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns coupons with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `filter[start_datetime]=2011-12-19T10:15:30+01:00`. | +| `filterDateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `filter[date_field]=updated_at`. | +| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching coupons with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | + +## Response Type + +[`[]models.CouponResponse`](../../doc/models/coupon-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -dateField := models.BasicDateField("updated_at") -startDate, err := time.Parse(time.RFC3339, "2011-12-17") + +collectedInputStartDate, err := time.Parse(time.RFC3339, "2011-12-17") if err != nil { log.Fatalln(err) } -startDatetime, err := time.Parse(time.RFC3339, "06/07/2019 17:20:06") +collectedInputStartDatetime, err := time.Parse(time.RFC3339, "06/07/2019 17:20:06") if err != nil { log.Fatalln(err) } -endDatetime, err := time.Parse(time.RFC3339, "06/07/2019 17:20:06") +collectedInputEndDatetime, err := time.Parse(time.RFC3339, "06/07/2019 17:20:06") if err != nil { log.Fatalln(err) -}Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') -currencyPrices := trueLiquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') - -apiResponse, err := couponsController.ListCoupons(ctx, &page, &perPage, &dateField, &startDate, nil, &startDatetime, &endDatetime, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), ¤cyPrices, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key')) +}Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') +collectedInput := advancedbilling.ListCouponsInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + DateField: models.ToPointer(models.BasicDateField("updated_at")), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') CurrencyPrices: models.ToPointer(true), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') StartDate: models.ToPointer(collectedInputStartDate), + StartDatetime: models.ToPointer(collectedInputStartDatetime), + EndDatetime: models.ToPointer(collectedInputEndDatetime), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := couponsController.ListCoupons(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "coupon": { - "id": 0, - "name": "string", - "code": "string", - "description": "string", - "amount": 0, - "amount_in_cents": 0, - "product_family_id": 0, - "product_family_name": "string", - "start_date": "2021-05-03T16:00:21-04:00", - "end_date": "2023-05-05T16:00:21-04:00", - "percentage": "10", - "recurring": true, - "recurring_scheme": "do_not_recur", - "duration_period_count": 0, - "duration_interval": 0, - "duration_interval_unit": "string", - "duration_interval_span": "string", - "allow_negative_balance": true, - "archived_at": null, - "conversion_limit": "string", - "stackable": true, - "compounding_strategy": "compound", - "use_site_exchange_rate": true, - "created_at": "2021-05-05T16:00:21-04:00", - "updated_at": "2021-05-05T16:00:21-04:00", - "discount_type": "amount", - "exclude_mid_period_allocations": true, - "apply_on_cancel_at_end_of_period": true, - "coupon_restrictions": [ - { - "id": 0, - "item_type": "Component", - "item_id": 0, - "name": "string", - "handle": "string" - } - ] - } - } -] -``` - - -# Read Coupon Usage - -This request will provide details about the coupon usage as an array of data hashes, one per product. - -```go -ReadCouponUsage( - ctx context.Context, - productFamilyId int, +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "coupon": { + "id": 0, + "name": "string", + "code": "string", + "description": "string", + "amount": 0, + "amount_in_cents": 0, + "product_family_id": 0, + "product_family_name": "string", + "start_date": "2021-05-03T16:00:21-04:00", + "end_date": "2023-05-05T16:00:21-04:00", + "percentage": "10", + "recurring": true, + "recurring_scheme": "do_not_recur", + "duration_period_count": 0, + "duration_interval": 0, + "duration_interval_unit": "string", + "duration_interval_span": "string", + "allow_negative_balance": true, + "archived_at": null, + "conversion_limit": "string", + "stackable": true, + "compounding_strategy": "compound", + "use_site_exchange_rate": true, + "created_at": "2021-05-05T16:00:21-04:00", + "updated_at": "2021-05-05T16:00:21-04:00", + "discount_type": "amount", + "exclude_mid_period_allocations": true, + "apply_on_cancel_at_end_of_period": true, + "coupon_restrictions": [ + { + "id": 0, + "item_type": "Component", + "item_id": 0, + "name": "string", + "handle": "string" + } + ] + } + } +] +``` + + +# Read Coupon Usage + +This request will provide details about the coupon usage as an array of data hashes, one per product. + +```go +ReadCouponUsage( + ctx context.Context, + productFamilyId int, couponId int) ( models.ApiResponse[[]models.CouponUsage], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon | - -## Response Type - -[`[]models.CouponUsage`](../../doc/models/coupon-usage.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the coupon belongs | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon | + +## Response Type + +[`[]models.CouponUsage`](../../doc/models/coupon-usage.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 couponId := 162 @@ -683,46 +734,46 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "name": "No cost product", - "id": 3903594, - "signups": 0, - "savings": 0, - "savings_in_cents": 0, - "revenue": 0, - "revenue_in_cents": 0 - }, - { - "name": "Product that expires", - "id": 3853680, - "signups": 0, - "savings": 0, - "savings_in_cents": 0, - "revenue": 0, - "revenue_in_cents": 0 - }, - { - "name": "Trial Product", - "id": 3861800, - "signups": 1, - "savings": 30, - "savings_in_cents": 3000, - "revenue": 20, - "revenue_in_cents": 2000 - } -] -``` - - -# Validate Coupon - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "name": "No cost product", + "id": 3903594, + "signups": 0, + "savings": 0, + "savings_in_cents": 0, + "revenue": 0, + "revenue_in_cents": 0 + }, + { + "name": "Product that expires", + "id": 3853680, + "signups": 0, + "savings": 0, + "savings_in_cents": 0, + "revenue": 0, + "revenue_in_cents": 0 + }, + { + "name": "Trial Product", + "id": 3861800, + "signups": 1, + "savings": 30, + "savings_in_cents": 3000, + "revenue": 20, + "revenue_in_cents": 2000 + } +] +``` + + +# Validate Coupon + You can verify if a specific coupon code is valid using the `validate` method. This method is useful for validating coupon codes that are entered by a customer. If the coupon is found and is valid, the coupon will be returned with a 200 status code. If the coupon is invalid, the status code will be 404 and the response will say why it is invalid. If the coupon is valid, the status code will be 200 and the coupon will be returned. The following reasons for invalidity are supported: @@ -743,31 +794,31 @@ Or: ``` https://.chargify.com/coupons/validate.?code=&product_family_id= -``` - -```go -ValidateCoupon( - ctx context.Context, - code string, +``` + +```go +ValidateCoupon( + ctx context.Context, + code string, productFamilyId *int) ( models.ApiResponse[models.CouponResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `code` | `string` | Query, Required | The code of the coupon | -| `productFamilyId` | `*int` | Query, Optional | The Chargify id of the product family to which the coupon belongs | - -## Response Type - -[`models.CouponResponse`](../../doc/models/coupon-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `code` | `string` | Query, Required | The code of the coupon | +| `productFamilyId` | `*int` | Query, Optional | The Chargify id of the product family to which the coupon belongs | + +## Response Type + +[`models.CouponResponse`](../../doc/models/coupon-response.md) + +## Example Usage + +```go ctx := context.Background() code := "code8" @@ -778,75 +829,75 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "coupon": { - "id": 66, - "name": "Foo Bar", - "code": "YEPPER9993", - "description": "my cool coupon", - "amount_in_cents": 10000, - "product_family_id": 4, - "created_at": "2017-11-07T14:51:52-05:00", - "updated_at": "2017-11-07T15:14:24-05:00", - "start_date": "2017-11-07T14:51:52-05:00", - "end_date": null, - "percentage": null, - "recurring": false, - "duration_period_count": null, - "duration_interval": null, - "duration_interval_unit": null, - "allow_negative_balance": false, - "archived_at": null, - "conversion_limit": null, - "stackable": true, - "compounding_strategy": "full-price", - "coupon_restrictions": [] - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | [`SingleStringErrorResponseException`](../../doc/models/single-string-error-response-exception.md) | - - -# Create or Update Coupon Currency Prices - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "coupon": { + "id": 66, + "name": "Foo Bar", + "code": "YEPPER9993", + "description": "my cool coupon", + "amount_in_cents": 10000, + "product_family_id": 4, + "created_at": "2017-11-07T14:51:52-05:00", + "updated_at": "2017-11-07T15:14:24-05:00", + "start_date": "2017-11-07T14:51:52-05:00", + "end_date": null, + "percentage": null, + "recurring": false, + "duration_period_count": null, + "duration_interval": null, + "duration_interval_unit": null, + "allow_negative_balance": false, + "archived_at": null, + "conversion_limit": null, + "stackable": true, + "compounding_strategy": "full-price", + "coupon_restrictions": [] + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | [`SingleStringErrorResponseException`](../../doc/models/single-string-error-response-exception.md) | + + +# Create or Update Coupon Currency Prices + This endpoint allows you to create and/or update currency prices for an existing coupon. Multiple prices can be created or updated in a single request but each of the currencies must be defined on the site level already and the coupon must be an amount-based coupon, not percentage. -Currency pricing for coupons must mirror the setup of the primary coupon pricing - if the primary coupon is percentage based, you will not be able to define pricing in non-primary currencies. - -```go -CreateOrUpdateCouponCurrencyPrices( - ctx context.Context, - couponId int, +Currency pricing for coupons must mirror the setup of the primary coupon pricing - if the primary coupon is percentage based, you will not be able to define pricing in non-primary currencies. + +```go +CreateOrUpdateCouponCurrencyPrices( + ctx context.Context, + couponId int, body *models.CouponCurrencyRequest) ( models.ApiResponse[models.CouponCurrencyResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon | -| `body` | [`*models.CouponCurrencyRequest`](../../doc/models/coupon-currency-request.md) | Body, Optional | - | - -## Response Type - -[`models.CouponCurrencyResponse`](../../doc/models/coupon-currency-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon | +| `body` | [`*models.CouponCurrencyRequest`](../../doc/models/coupon-currency-request.md) | Body, Optional | - | + +## Response Type + +[`models.CouponCurrencyResponse`](../../doc/models/coupon-currency-response.md) + +## Example Usage + +```go ctx := context.Background() couponId := 162 @@ -872,12 +923,12 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Create Coupon Subcodes - +} +``` + + +# Create Coupon Subcodes + ## Coupon Subcodes Intro Coupon Subcodes allow you to create a set of unique codes that allow you to expand the use of one coupon. @@ -917,31 +968,31 @@ This request allows you to create specific subcodes underneath an existing coupo _ to %5F . to %2E -So, if the coupon subcode is `20%OFF`, the URL to delete this coupon subcode would be: `https://.chargify.com/coupons/567/codes/20%25OFF.` - -```go -CreateCouponSubcodes( - ctx context.Context, - couponId int, +So, if the coupon subcode is `20%OFF`, the URL to delete this coupon subcode would be: `https://.chargify.com/coupons/567/codes/20%25OFF.` + +```go +CreateCouponSubcodes( + ctx context.Context, + couponId int, body *models.CouponSubcodes) ( models.ApiResponse[models.CouponSubcodesResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon | -| `body` | [`*models.CouponSubcodes`](../../doc/models/coupon-subcodes.md) | Body, Optional | - | - -## Response Type - -[`models.CouponSubcodesResponse`](../../doc/models/coupon-subcodes-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon | +| `body` | [`*models.CouponSubcodes`](../../doc/models/coupon-subcodes.md) | Body, Optional | - | + +## Response Type + +[`models.CouponSubcodesResponse`](../../doc/models/coupon-subcodes-response.md) + +## Example Usage + +```go ctx := context.Background() couponId := 162 @@ -956,97 +1007,101 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "created_codes": [ - "BALTIMOREFALL", - "ORLANDOFALL", - "DETROITFALL" - ], - "duplicate_codes": [], - "invalid_codes": [] -} -``` - - -# List Coupon Subcodes - -This request allows you to request the subcodes that are attached to a coupon. - -```go -ListCouponSubcodes( - ctx context.Context,input ListCouponSubcodesInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "created_codes": [ + "BALTIMOREFALL", + "ORLANDOFALL", + "DETROITFALL" + ], + "duplicate_codes": [], + "invalid_codes": [] +} +``` + + +# List Coupon Subcodes + +This request allows you to request the subcodes that are attached to a coupon. + +```go +ListCouponSubcodes( + ctx context.Context, + input ListCouponSubcodesInput) ( models.ApiResponse[models.CouponSubcodes], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | - -## Response Type - -[`models.CouponSubcodes`](../../doc/models/coupon-subcodes.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | + +## Response Type + +[`models.CouponSubcodes`](../../doc/models/coupon-subcodes.md) + +## Example Usage + +```go ctx := context.Background() -couponId := 162 -page := 2 -perPage := 50 -apiResponse, err := couponsController.ListCouponSubcodes(ctx, couponId, &page, &perPage) +collectedInput := advancedbilling.ListCouponSubcodesInput{ + CouponId: 162, + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +} + +apiResponse, err := couponsController.ListCouponSubcodes(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "codes": [ - "3JU6PR", - "9RO6MP", - "8OG1VV", - "5FL7VV", - "2SV8XK", - "4LW8LH", - "3VL4GZ", - "9UI9XO", - "0LZ0CC", - "8XI9JV", - "9UV5YE", - "3UI4GX", - "6SL5ST", - "9WC8IJ", - "2KA3PZ", - "7WR1VR", - "3VY7MN", - "6KC3KB", - "7DF7YT", - "9FH1ED" - ] -} -``` - - -# Update Coupon Subcodes - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "codes": [ + "3JU6PR", + "9RO6MP", + "8OG1VV", + "5FL7VV", + "2SV8XK", + "4LW8LH", + "3VL4GZ", + "9UI9XO", + "0LZ0CC", + "8XI9JV", + "9UV5YE", + "3UI4GX", + "6SL5ST", + "9WC8IJ", + "2KA3PZ", + "7WR1VR", + "3VY7MN", + "6KC3KB", + "7DF7YT", + "9FH1ED" + ] +} +``` + + +# Update Coupon Subcodes + You can update the subcodes for the given Coupon via the API with a PUT request to the resource endpoint. Send an array of new coupon subcodes. @@ -1057,31 +1112,31 @@ The response will contain: + Subcodes that were not created because they already exist, -+ Any subcodes not created because they are invalid. - -```go -UpdateCouponSubcodes( - ctx context.Context, - couponId int, ++ Any subcodes not created because they are invalid. + +```go +UpdateCouponSubcodes( + ctx context.Context, + couponId int, body *models.CouponSubcodes) ( models.ApiResponse[models.CouponSubcodesResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon | -| `body` | [`*models.CouponSubcodes`](../../doc/models/coupon-subcodes.md) | Body, Optional | - | - -## Response Type - -[`models.CouponSubcodesResponse`](../../doc/models/coupon-subcodes-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon | +| `body` | [`*models.CouponSubcodes`](../../doc/models/coupon-subcodes.md) | Body, Optional | - | + +## Response Type + +[`models.CouponSubcodesResponse`](../../doc/models/coupon-subcodes-response.md) + +## Example Usage + +```go ctx := context.Background() couponId := 162 @@ -1096,12 +1151,12 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Delete Coupon Subcode - +} +``` + + +# Delete Coupon Subcode + ## Example Given a coupon with an ID of 567, and a coupon subcode of 20OFF, the URL to `DELETE` this coupon subcode would be: @@ -1123,31 +1178,31 @@ Note: If you are using any of the allowed special characters (“%”, “@”, ## Percent Encoding Example -Or if the coupon subcode is 20%OFF, the URL to delete this coupon subcode would be: @https://.chargify.com/coupons/567/codes/20%25OFF. - -```go -DeleteCouponSubcode( - ctx context.Context, - couponId int, +Or if the coupon subcode is 20%OFF, the URL to delete this coupon subcode would be: @https://.chargify.com/coupons/567/codes/20%25OFF. + +```go +DeleteCouponSubcode( + ctx context.Context, + couponId int, subcode string) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `couponId` | `int` | Template, Required | The Chargify id of the coupon to which the subcode belongs | -| `subcode` | `string` | Template, Required | The subcode of the coupon | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `couponId` | `int` | Template, Required | The Chargify id of the coupon to which the subcode belongs | +| `subcode` | `string` | Template, Required | The subcode of the coupon | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() couponId := 162 subcode := "subcode4" @@ -1157,12 +1212,12 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + diff --git a/doc/controllers/custom-fields.md b/doc/controllers/custom-fields.md index 489c65b6..627cf348 100644 --- a/doc/controllers/custom-fields.md +++ b/doc/controllers/custom-fields.md @@ -1,15 +1,15 @@ -# Custom Fields - -```go -customFieldsController := client.CustomFieldsController() -``` - -## Class Name - -`CustomFieldsController` - -## Methods - +# Custom Fields + +```go +customFieldsController := client.CustomFieldsController() +``` + +## Class Name + +`CustomFieldsController` + +## Methods + * [Create Metafields](../../doc/controllers/custom-fields.md#create-metafields) * [List Metafields](../../doc/controllers/custom-fields.md#list-metafields) * [Update Metafield](../../doc/controllers/custom-fields.md#update-metafield) @@ -18,11 +18,11 @@ customFieldsController := client.CustomFieldsController() * [List Metadata](../../doc/controllers/custom-fields.md#list-metadata) * [Update Metadata](../../doc/controllers/custom-fields.md#update-metadata) * [Delete Metadata](../../doc/controllers/custom-fields.md#delete-metadata) -* [List Metadata for Resource Type](../../doc/controllers/custom-fields.md#list-metadata-for-resource-type) - - -# Create Metafields - +* [List Metadata for Resource Type](../../doc/controllers/custom-fields.md#list-metadata-for-resource-type) + + +# Create Metafields + ## Custom Fields: Metafield Intro **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. @@ -46,36 +46,50 @@ It is possible to create Metafields “on the fly” when you create your Metada ### Metafield Scope Warning -If configuring metafields in the Admin UI or via the API, be careful sending updates to metafields with the scope attribute – **if a partial update is sent it will overwrite the current configuration**. - -```go -CreateMetafields( - ctx context.Context, - resourceType models.ResourceType, +If configuring metafields in the Admin UI or via the API, be careful sending updates to metafields with the scope attribute – **if a partial update is sent it will overwrite the current configuration**. + +```go +CreateMetafields( + ctx context.Context, + resourceType models.ResourceType, body *models.CreateMetafieldsRequest) ( models.ApiResponse[[]models.Metafield], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `body` | [`*models.CreateMetafieldsRequest`](../../doc/models/create-metafields-request.md) | Body, Optional | - | - -## Response Type - -[`[]models.Metafield`](../../doc/models/metafield.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | +| `body` | [`*models.CreateMetafieldsRequest`](../../doc/models/create-metafields-request.md) | Body, Optional | - | + +## Response Type + +[`[]models.Metafield`](../../doc/models/metafield.md) + +## Example Usage + +```go ctx := context.Background() resourceType := models.ResourceType("subscriptions") +bodyMetafieldsCreateMetafieldScope := models.MetafieldScope{ + PublicShow: models.ToPointer(models.IncludeOption("1")), + PublicEdit: models.ToPointer(models.IncludeOption("1")), +} + +bodyMetafieldsCreateMetafield := models.CreateMetafield{ + Name: models.ToPointer("Dropdown field"), + InputType: models.ToPointer(models.MetafieldInput("dropdown")), + Enum: []string{"option 1", "option 2"}, + Scope: models.ToPointer(bodyMetafieldsCreateMetafieldScope), +} + +bodyMetafields := models.CreateMetafieldsRequestMetafieldsContainer.FromCreateMetafield(bodyMetafieldsCreateMetafield) + body := models.CreateMetafieldsRequest{ - Metafields: interface{}("[name, Dropdown field][input_type, dropdown][enum, System.Object[]][scope, DotLiquid.Hash]"), + Metafields: bodyMetafields, } apiResponse, err := customFieldsController.CreateMetafields(ctx, resourceType, &body) @@ -85,148 +99,152 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "name": "Color", - "scope": { - "hosted": [], - "csv": "0", - "statements": "0", - "invoices": "0", - "portal": "0" - }, - "data_count": 0, - "input_type": "text", - "enum": null - }, - { - "name": "Brand", - "scope": { - "hosted": [], - "csv": "0", - "statements": "0", - "invoices": "0", - "portal": "0" - }, - "data_count": 0, - "input_type": "text", - "enum": null - } -] -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | - - -# List Metafields - -This endpoint lists metafields associated with a site. The metafield description and usage is contained in the response. - -```go -ListMetafields( - ctx context.Context,input ListMetafieldsInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "name": "Color", + "scope": { + "hosted": [], + "csv": "0", + "statements": "0", + "invoices": "0", + "portal": "0" + }, + "data_count": 0, + "input_type": "text", + "enum": null + }, + { + "name": "Brand", + "scope": { + "hosted": [], + "csv": "0", + "statements": "0", + "invoices": "0", + "portal": "0" + }, + "data_count": 0, + "input_type": "text", + "enum": null + } +] +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | + + +# List Metafields + +This endpoint lists metafields associated with a site. The metafield description and usage is contained in the response. + +```go +ListMetafields( + ctx context.Context, + input ListMetafieldsInput) ( models.ApiResponse[models.ListMetafieldsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `name` | `*string` | Query, Optional | filter by the name of the metafield | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | - -## Response Type - -[`models.ListMetafieldsResponse`](../../doc/models/list-metafields-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | +| `name` | `*string` | Query, Optional | filter by the name of the metafield | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | + +## Response Type + +[`models.ListMetafieldsResponse`](../../doc/models/list-metafields-response.md) + +## Example Usage + +```go ctx := context.Background() -resourceType := models.ResourceType("subscriptions") -page := 2 -perPage := 50 -apiResponse, err := customFieldsController.ListMetafields(ctx, resourceType, nil, &page, &perPage, nil) +collectedInput := advancedbilling.ListMetafieldsInput{ + ResourceType: models.ResourceType("subscriptions"), + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +} + +apiResponse, err := customFieldsController.ListMetafields(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "total_count": 0, - "current_page": 0, - "total_pages": 0, - "per_page": 0, - "metafields": [ - { - "id": 0, - "name": "string", - "scope": { - "csv": "0", - "statements": "0", - "invoices": "0", - "portal": "0", - "public_show": "0", - "public_edit": "0" - }, - "data_count": 0, - "input_type": "text", - "enum": null - } - ] -} -``` - - -# Update Metafield - -Use the following method to update metafields for your Site. Metafields can be populated with metadata after the fact. - -```go -UpdateMetafield( - ctx context.Context, - resourceType models.ResourceType, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "total_count": 0, + "current_page": 0, + "total_pages": 0, + "per_page": 0, + "metafields": [ + { + "id": 0, + "name": "string", + "scope": { + "csv": "0", + "statements": "0", + "invoices": "0", + "portal": "0", + "public_show": "0", + "public_edit": "0" + }, + "data_count": 0, + "input_type": "text", + "enum": null + } + ] +} +``` + + +# Update Metafield + +Use the following method to update metafields for your Site. Metafields can be populated with metadata after the fact. + +```go +UpdateMetafield( + ctx context.Context, + resourceType models.ResourceType, body *models.UpdateMetafieldsRequest) ( models.ApiResponse[[]models.Metafield], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `body` | [`*models.UpdateMetafieldsRequest`](../../doc/models/update-metafields-request.md) | Body, Optional | - | - -## Response Type - -[`[]models.Metafield`](../../doc/models/metafield.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | +| `body` | [`*models.UpdateMetafieldsRequest`](../../doc/models/update-metafields-request.md) | Body, Optional | - | + +## Response Type + +[`[]models.Metafield`](../../doc/models/metafield.md) + +## Example Usage + +```go ctx := context.Background() resourceType := models.ResourceType("subscriptions") @@ -237,45 +255,45 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | - - -# Delete Metafield - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | + + +# Delete Metafield + Use the following method to delete a metafield. This will remove the metafield from the Site. -Additionally, this will remove the metafield and associated metadata with all Subscriptions on the Site. - -```go -DeleteMetafield( - ctx context.Context, - resourceType models.ResourceType, +Additionally, this will remove the metafield and associated metadata with all Subscriptions on the Site. + +```go +DeleteMetafield( + ctx context.Context, + resourceType models.ResourceType, name *string) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `name` | `*string` | Query, Optional | The name of the metafield to be deleted | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | +| `name` | `*string` | Query, Optional | The name of the metafield to be deleted | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() resourceType := models.ResourceType("subscriptions") @@ -284,18 +302,18 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Create Metadata - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Create Metadata + ## Custom Fields: Metadata Intro **Chargify refers to Custom Fields in the API documentation as metafields and metadata.** Within the Chargify UI, metadata and metafields are grouped together under the umbrella of "Custom Fields." All of our UI-based documentation that references custom fields will not cite the terminology metafields or metadata. @@ -317,33 +335,33 @@ This method will create a metafield for the site on the fly if it does not alrea ### Subscription or Customer Resource -Please pay special attention to the resource you use when creating metadata. - -```go -CreateMetadata( - ctx context.Context, - resourceType models.ResourceType, - resourceId int, +Please pay special attention to the resource you use when creating metadata. + +```go +CreateMetadata( + ctx context.Context, + resourceType models.ResourceType, + resourceId int, body *models.CreateMetadataRequest) ( models.ApiResponse[[]models.Metadata], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `resourceId` | `int` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | -| `body` | [`*models.CreateMetadataRequest`](../../doc/models/create-metadata-request.md) | Body, Optional | - | - -## Response Type - -[`[]models.Metadata`](../../doc/models/metadata.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | +| `resourceId` | `int` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | +| `body` | [`*models.CreateMetadataRequest`](../../doc/models/create-metadata-request.md) | Body, Optional | - | + +## Response Type + +[`[]models.Metadata`](../../doc/models/metadata.md) + +## Example Usage + +```go ctx := context.Background() resourceType := models.ResourceType("subscriptions") resourceId := 60 @@ -370,93 +388,97 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | - - -# List Metadata - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | + + +# List Metadata + This request will list all of the metadata belonging to a particular resource (ie. subscription, customer) that is specified. ## Metadata Data -This endpoint will also display the current stats of your metadata to use as a tool for pagination. - -```go -ListMetadata( - ctx context.Context,input ListMetadataInput) ( +This endpoint will also display the current stats of your metadata to use as a tool for pagination. + +```go +ListMetadata( + ctx context.Context, + input ListMetadataInput) ( models.ApiResponse[models.PaginatedMetadata], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `resourceId` | `int` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | - -## Response Type - -[`models.PaginatedMetadata`](../../doc/models/paginated-metadata.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | +| `resourceId` | `int` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | + +## Response Type + +[`models.PaginatedMetadata`](../../doc/models/paginated-metadata.md) + +## Example Usage + +```go ctx := context.Background() -resourceType := models.ResourceType("subscriptions") -resourceId := 60 -page := 2 -perPage := 50 -apiResponse, err := customFieldsController.ListMetadata(ctx, resourceType, resourceId, &page, &perPage) +collectedInput := advancedbilling.ListMetadataInput{ + ResourceType: models.ResourceType("subscriptions"), + ResourceId: 60, + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +} + +apiResponse, err := customFieldsController.ListMetadata(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Update Metadata - -This method allows you to update the existing metadata associated with a subscription or customer. - -```go -UpdateMetadata( - ctx context.Context, - resourceType models.ResourceType, - resourceId int, +} +``` + + +# Update Metadata + +This method allows you to update the existing metadata associated with a subscription or customer. + +```go +UpdateMetadata( + ctx context.Context, + resourceType models.ResourceType, + resourceId int, body *models.UpdateMetadataRequest) ( models.ApiResponse[[]models.Metadata], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `resourceId` | `int` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | -| `body` | [`*models.UpdateMetadataRequest`](../../doc/models/update-metadata-request.md) | Body, Optional | - | - -## Response Type - -[`[]models.Metadata`](../../doc/models/metadata.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | +| `resourceId` | `int` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | +| `body` | [`*models.UpdateMetadataRequest`](../../doc/models/update-metadata-request.md) | Body, Optional | - | + +## Response Type + +[`[]models.Metadata`](../../doc/models/metadata.md) + +## Example Usage + +```go ctx := context.Background() resourceType := models.ResourceType("subscriptions") resourceId := 60 @@ -468,18 +490,18 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | - - -# Delete Metadata - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | + + +# Delete Metadata + This method removes the metadata from the subscriber/customer cited. ## Query String Usage @@ -502,35 +524,35 @@ For a success, there will be a code `200` and the plain text response `true`. ## Unsuccessful Response -When a failed response is encountered, you will receive a `404` response and the plain text response of `true`. - -```go -DeleteMetadata( - ctx context.Context, - resourceType models.ResourceType, - resourceId int, - name *string, +When a failed response is encountered, you will receive a `404` response and the plain text response of `true`. + +```go +DeleteMetadata( + ctx context.Context, + resourceType models.ResourceType, + resourceId int, + name *string, names []string) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `resourceId` | `int` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | -| `name` | `*string` | Query, Optional | Name of field to be removed. | -| `names` | `[]string` | Query, Optional | Names of fields to be removed. Use in query: `names[]=field1&names[]=my-field&names[]=another-field`. | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | +| `resourceId` | `int` | Template, Required | The Chargify id of the customer or the subscription for which the metadata applies | +| `name` | `*string` | Query, Optional | Name of field to be removed. | +| `names` | `[]string` | Query, Optional | Names of fields to be removed. Use in query: `names[]=field1&names[]=my-field&names[]=another-field`. | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() resourceType := models.ResourceType("subscriptions") resourceId := 60Liquid error: Value cannot be null. (Parameter 'key') @@ -540,18 +562,18 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# List Metadata for Resource Type - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# List Metadata for Resource Type + This method will provide you information on usage of metadata across your selected resource (ie. subscriptions, customers) ## Metadata Data @@ -564,51 +586,55 @@ This endpoint will also display the current stats of your metadata to use as a t ## Read Metadata for a Site -This endpoint will list the number of pages of metadata information that are contained within a site. - -```go -ListMetadataForResourceType( - ctx context.Context,input ListMetadataForResourceTypeInput) ( +This endpoint will list the number of pages of metadata information that are contained within a site. + +```go +ListMetadataForResourceType( + ctx context.Context, + input ListMetadataForResourceTypeInput) ( models.ApiResponse[models.PaginatedMetadata], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. | -| `startDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns metadata with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `endDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns metadata with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `startDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns metadata with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `endDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns metadata with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | -| `withDeleted` | `*bool` | Query, Optional | Allow to fetch deleted metadata. | -| `resourceIds` | `[]int` | Query, Optional | Allow to fetch metadata for multiple records based on provided ids. Use in query: `resource_ids[]=122&resource_ids[]=123&resource_ids[]=124`. | -| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | - -## Response Type - -[`models.PaginatedMetadata`](../../doc/models/paginated-metadata.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `resourceType` | [`models.ResourceType`](../../doc/models/resource-type.md) | Template, Required | the resource type to which the metafields belong | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. | +| `startDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns metadata with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `endDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns metadata with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `startDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns metadata with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `endDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns metadata with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | +| `withDeleted` | `*bool` | Query, Optional | Allow to fetch deleted metadata. | +| `resourceIds` | `[]int` | Query, Optional | Allow to fetch metadata for multiple records based on provided ids. Use in query: `resource_ids[]=122&resource_ids[]=123&resource_ids[]=124`. | +| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | + +## Response Type + +[`models.PaginatedMetadata`](../../doc/models/paginated-metadata.md) + +## Example Usage + +```go ctx := context.Background() -resourceType := models.ResourceType("subscriptions") -page := 2 -perPage := 50 -dateField := models.BasicDateField("updated_at")Liquid error: Value cannot be null. (Parameter 'key') -apiResponse, err := customFieldsController.ListMetadataForResourceType(ctx, resourceType, &page, &perPage, &dateField, nil, nil, nil, nil, nil, Liquid error: Value cannot be null. (Parameter 'key'), nil) +collectedInput := advancedbilling.ListMetadataForResourceTypeInput{ + ResourceType: models.ResourceType("subscriptions"), + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + DateField: models.ToPointer(models.BasicDateField("updated_at")), +Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := customFieldsController.ListMetadataForResourceType(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - +} +``` + diff --git a/doc/controllers/customers.md b/doc/controllers/customers.md index 75c67e11..6af6a718 100644 --- a/doc/controllers/customers.md +++ b/doc/controllers/customers.md @@ -1,26 +1,26 @@ -# Customers - -```go -customersController := client.CustomersController() -``` - -## Class Name - -`CustomersController` - -## Methods - +# Customers + +```go +customersController := client.CustomersController() +``` + +## Class Name + +`CustomersController` + +## Methods + * [Create Customer](../../doc/controllers/customers.md#create-customer) * [List Customers](../../doc/controllers/customers.md#list-customers) * [Read Customer](../../doc/controllers/customers.md#read-customer) * [Update Customer](../../doc/controllers/customers.md#update-customer) * [Delete Customer](../../doc/controllers/customers.md#delete-customer) * [Read Customer by Reference](../../doc/controllers/customers.md#read-customer-by-reference) -* [List Customer Subscriptions](../../doc/controllers/customers.md#list-customer-subscriptions) - - -# Create Customer - +* [List Customer Subscriptions](../../doc/controllers/customers.md#list-customer-subscriptions) + + +# Create Customer + You may create a new Customer at any time, or you may create a Customer at the same time you create a Subscription. The only validation restriction is that you may only create one customer for a given reference value. If provided, the `reference` value must be unique. It represents a unique identifier for the customer from your own app, i.e. the customer’s ID. This allows you to retrieve a given customer via a piece of shared information. Alternatively, you may choose to leave `reference` blank, and store Chargify’s unique ID for the customer, which is in the `id` attribute. @@ -44,29 +44,29 @@ Chargify requires that you use the ISO Standard State codes when formatting stat ## Locale Chargify allows you to attribute a language/region to your customer to deliver invoices in any required language. -For more: [Customer Locale](https://chargify.zendesk.com/hc/en-us/articles/4407870384283#customer-locale) - -```go -CreateCustomer( - ctx context.Context, +For more: [Customer Locale](https://chargify.zendesk.com/hc/en-us/articles/4407870384283#customer-locale) + +```go +CreateCustomer( + ctx context.Context, body *models.CreateCustomerRequest) ( models.ApiResponse[models.CustomerResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.CreateCustomerRequest`](../../doc/models/create-customer-request.md) | Body, Optional | - | - -## Response Type - -[`models.CustomerResponse`](../../doc/models/customer-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.CreateCustomerRequest`](../../doc/models/create-customer-request.md) | Body, Optional | - | + +## Response Type + +[`models.CustomerResponse`](../../doc/models/customer-response.md) + +## Example Usage + +```go ctx := context.Background() bodyCustomer := models.CreateCustomer{ @@ -97,53 +97,53 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "customer": { - "first_name": "Cathryn", - "last_name": "Parisian", - "email": "Stella.McLaughlin6@example.net", - "cc_emails": null, - "organization": "Greenholt - Oberbrunner", - "reference": null, - "id": 76, - "created_at": "2021-03-29T07:47:00-04:00", - "updated_at": "2021-03-29T07:47:00-04:00", - "address": "739 Stephon Bypass", - "address_2": "Apt. 386", - "city": "Sedrickchester", - "state": "KY", - "state_name": "Kentucky", - "zip": "46979-7719", - "country": "US", - "country_name": "United States", - "phone": "230-934-3685", - "verified": false, - "portal_customer_created_at": null, - "portal_invite_last_sent_at": null, - "portal_invite_last_accepted_at": null, - "tax_exempt": false, - "vat_number": null, - "parent_id": null, - "locale": "en-US" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`CustomerErrorResponseException`](../../doc/models/customer-error-response-exception.md) | - - -# List Customers - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "customer": { + "first_name": "Cathryn", + "last_name": "Parisian", + "email": "Stella.McLaughlin6@example.net", + "cc_emails": null, + "organization": "Greenholt - Oberbrunner", + "reference": null, + "id": 76, + "created_at": "2021-03-29T07:47:00-04:00", + "updated_at": "2021-03-29T07:47:00-04:00", + "address": "739 Stephon Bypass", + "address_2": "Apt. 386", + "city": "Sedrickchester", + "state": "KY", + "state_name": "Kentucky", + "zip": "46979-7719", + "country": "US", + "country_name": "United States", + "phone": "230-934-3685", + "verified": false, + "portal_customer_created_at": null, + "portal_invite_last_sent_at": null, + "portal_invite_last_accepted_at": null, + "tax_exempt": false, + "vat_number": null, + "parent_id": null, + "locale": "en-US" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`CustomerErrorResponseException`](../../doc/models/customer-error-response-exception.md) | + + +# List Customers + This request will by default list all customers associated with your Site. ## Find Customer @@ -158,161 +158,165 @@ Common use cases are: + Search by a reference value from your application + Search by a first or last name -To retrieve a single, exact match by reference, please use the [lookup endpoint](https://developers.chargify.com/docs/api-docs/b710d8fbef104-read-customer-by-reference). - -```go -ListCustomers( - ctx context.Context,input ListCustomersInput) ( +To retrieve a single, exact match by reference, please use the [lookup endpoint](https://developers.chargify.com/docs/api-docs/b710d8fbef104-read-customer-by-reference). + +```go +ListCustomers( + ctx context.Context, + input ListCustomersInput) ( models.ApiResponse[[]models.CustomerResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Direction to sort customers by time of creation | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 50. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | -| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | -| `q` | `*string` | Query, Optional | A search query by which to filter customers (can be an email, an ID, a reference, organization) | - -## Response Type - -[`[]models.CustomerResponse`](../../doc/models/customer-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Direction to sort customers by time of creation | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 50. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | +| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | +| `q` | `*string` | Query, Optional | A search query by which to filter customers (can be an email, an ID, a reference, organization) | + +## Response Type + +[`[]models.CustomerResponse`](../../doc/models/customer-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 30 -dateField := models.BasicDateField("updated_at") -apiResponse, err := customersController.ListCustomers(ctx, nil, &page, &perPage, &dateField, nil, nil, nil, nil, nil) +collectedInput := advancedbilling.ListCustomersInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(30), + DateField: models.ToPointer(models.BasicDateField("updated_at")), +} + +apiResponse, err := customersController.ListCustomers(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "customer": { - "first_name": "Kayla", - "last_name": "Test", - "email": "kayla@example.com", - "cc_emails": "john@example.com, sue@example.com", - "organization": "", - "reference": null, - "id": 14126091, - "created_at": "2016-10-04T15:22:27-04:00", - "updated_at": "2016-10-04T15:22:30-04:00", - "address": "", - "address_2": "", - "city": "", - "state": "", - "zip": "", - "country": "", - "phone": "", - "verified": null, - "portal_customer_created_at": "2016-10-04T15:22:29-04:00", - "portal_invite_last_sent_at": "2016-10-04T15:22:30-04:00", - "portal_invite_last_accepted_at": null, - "tax_exempt": false - } - }, - { - "customer": { - "first_name": "Nick ", - "last_name": "Test", - "email": "nick@example.com", - "cc_emails": "john@example.com, sue@example.com", - "organization": "", - "reference": null, - "id": 14254093, - "created_at": "2016-10-13T16:52:51-04:00", - "updated_at": "2016-10-13T16:52:54-04:00", - "address": "", - "address_2": "", - "city": "", - "state": "", - "zip": "", - "country": "", - "phone": "", - "verified": null, - "portal_customer_created_at": "2016-10-13T16:52:54-04:00", - "portal_invite_last_sent_at": "2016-10-13T16:52:54-04:00", - "portal_invite_last_accepted_at": null, - "tax_exempt": false, - "parent_id": 123 - } - }, - { - "customer": { - "first_name": "Don", - "last_name": "Test", - "email": "don@example.com", - "cc_emails": "john@example.com, sue@example.com", - "organization": "", - "reference": null, - "id": 14332342, - "created_at": "2016-10-19T10:49:13-04:00", - "updated_at": "2016-10-19T10:49:19-04:00", - "address": "1737 15th St", - "address_2": "", - "city": "Boulder", - "state": "CO", - "zip": "80302", - "country": "US", - "phone": "", - "verified": null, - "portal_customer_created_at": "2016-10-19T10:49:19-04:00", - "portal_invite_last_sent_at": "2016-10-19T10:49:19-04:00", - "portal_invite_last_accepted_at": null, - "tax_exempt": false, - "parent_id": null - } - } -] -``` - - -# Read Customer - -This method allows to retrieve the Customer properties by Chargify-generated Customer ID. - -```go -ReadCustomer( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "customer": { + "first_name": "Kayla", + "last_name": "Test", + "email": "kayla@example.com", + "cc_emails": "john@example.com, sue@example.com", + "organization": "", + "reference": null, + "id": 14126091, + "created_at": "2016-10-04T15:22:27-04:00", + "updated_at": "2016-10-04T15:22:30-04:00", + "address": "", + "address_2": "", + "city": "", + "state": "", + "zip": "", + "country": "", + "phone": "", + "verified": null, + "portal_customer_created_at": "2016-10-04T15:22:29-04:00", + "portal_invite_last_sent_at": "2016-10-04T15:22:30-04:00", + "portal_invite_last_accepted_at": null, + "tax_exempt": false + } + }, + { + "customer": { + "first_name": "Nick ", + "last_name": "Test", + "email": "nick@example.com", + "cc_emails": "john@example.com, sue@example.com", + "organization": "", + "reference": null, + "id": 14254093, + "created_at": "2016-10-13T16:52:51-04:00", + "updated_at": "2016-10-13T16:52:54-04:00", + "address": "", + "address_2": "", + "city": "", + "state": "", + "zip": "", + "country": "", + "phone": "", + "verified": null, + "portal_customer_created_at": "2016-10-13T16:52:54-04:00", + "portal_invite_last_sent_at": "2016-10-13T16:52:54-04:00", + "portal_invite_last_accepted_at": null, + "tax_exempt": false, + "parent_id": 123 + } + }, + { + "customer": { + "first_name": "Don", + "last_name": "Test", + "email": "don@example.com", + "cc_emails": "john@example.com, sue@example.com", + "organization": "", + "reference": null, + "id": 14332342, + "created_at": "2016-10-19T10:49:13-04:00", + "updated_at": "2016-10-19T10:49:19-04:00", + "address": "1737 15th St", + "address_2": "", + "city": "Boulder", + "state": "CO", + "zip": "80302", + "country": "US", + "phone": "", + "verified": null, + "portal_customer_created_at": "2016-10-19T10:49:19-04:00", + "portal_invite_last_sent_at": "2016-10-19T10:49:19-04:00", + "portal_invite_last_accepted_at": null, + "tax_exempt": false, + "parent_id": null + } + } +] +``` + + +# Read Customer + +This method allows to retrieve the Customer properties by Chargify-generated Customer ID. + +```go +ReadCustomer( + ctx context.Context, id int) ( models.ApiResponse[models.CustomerResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `id` | `int` | Template, Required | The Chargify id of the customer | - -## Response Type - -[`models.CustomerResponse`](../../doc/models/customer-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `id` | `int` | Template, Required | The Chargify id of the customer | + +## Response Type + +[`models.CustomerResponse`](../../doc/models/customer-response.md) + +## Example Usage + +```go ctx := context.Background() id := 112 @@ -323,37 +327,37 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Update Customer - -This method allows to update the Customer. - -```go -UpdateCustomer( - ctx context.Context, - id int, +} +``` + + +# Update Customer + +This method allows to update the Customer. + +```go +UpdateCustomer( + ctx context.Context, + id int, body *models.UpdateCustomerRequest) ( models.ApiResponse[models.CustomerResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `id` | `int` | Template, Required | The Chargify id of the customer | -| `body` | [`*models.UpdateCustomerRequest`](../../doc/models/update-customer-request.md) | Body, Optional | - | - -## Response Type - -[`models.CustomerResponse`](../../doc/models/customer-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `id` | `int` | Template, Required | The Chargify id of the customer | +| `body` | [`*models.UpdateCustomerRequest`](../../doc/models/update-customer-request.md) | Body, Optional | - | + +## Response Type + +[`models.CustomerResponse`](../../doc/models/customer-response.md) + +## Example Usage + +```go ctx := context.Background() id := 112 @@ -374,73 +378,73 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "customer": { - "first_name": "Martha", - "last_name": "Washington", - "email": "martha.washington@example.com", - "cc_emails": "george.washington@example.com", - "organization": null, - "reference": null, - "id": 14967442, - "created_at": "2016-12-05T10:33:07-05:00", - "updated_at": "2016-12-05T10:38:00-05:00", - "address": null, - "address_2": null, - "city": null, - "state": null, - "zip": null, - "country": null, - "phone": null, - "verified": false, - "portal_customer_created_at": null, - "portal_invite_last_sent_at": null, - "portal_invite_last_accepted_at": null, - "tax_exempt": false, - "vat_number": "012345678" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`CustomerErrorResponseException`](../../doc/models/customer-error-response-exception.md) | - - -# Delete Customer - -This method allows you to delete the Customer. - -```go -DeleteCustomer( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "customer": { + "first_name": "Martha", + "last_name": "Washington", + "email": "martha.washington@example.com", + "cc_emails": "george.washington@example.com", + "organization": null, + "reference": null, + "id": 14967442, + "created_at": "2016-12-05T10:33:07-05:00", + "updated_at": "2016-12-05T10:38:00-05:00", + "address": null, + "address_2": null, + "city": null, + "state": null, + "zip": null, + "country": null, + "phone": null, + "verified": false, + "portal_customer_created_at": null, + "portal_invite_last_sent_at": null, + "portal_invite_last_accepted_at": null, + "tax_exempt": false, + "vat_number": "012345678" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`CustomerErrorResponseException`](../../doc/models/customer-error-response-exception.md) | + + +# Delete Customer + +This method allows you to delete the Customer. + +```go +DeleteCustomer( + ctx context.Context, id int) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `id` | `int` | Template, Required | The Chargify id of the customer | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `id` | `int` | Template, Required | The Chargify id of the customer | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() id := 112 @@ -449,35 +453,35 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - - -# Read Customer by Reference - -Use this method to return the customer object if you have the unique **Reference ID (Your App)** value handy. It will return a single match. - -```go -ReadCustomerByReference( - ctx context.Context, +} +``` + + +# Read Customer by Reference + +Use this method to return the customer object if you have the unique **Reference ID (Your App)** value handy. It will return a single match. + +```go +ReadCustomerByReference( + ctx context.Context, reference string) ( models.ApiResponse[models.CustomerResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `reference` | `string` | Query, Required | Customer reference | - -## Response Type - -[`models.CustomerResponse`](../../doc/models/customer-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `reference` | `string` | Query, Required | Customer reference | + +## Response Type + +[`models.CustomerResponse`](../../doc/models/customer-response.md) + +## Example Usage + +```go ctx := context.Background() reference := "reference4" @@ -488,35 +492,35 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# List Customer Subscriptions - -This method lists all subscriptions that belong to a customer. - -```go -ListCustomerSubscriptions( - ctx context.Context, +} +``` + + +# List Customer Subscriptions + +This method lists all subscriptions that belong to a customer. + +```go +ListCustomerSubscriptions( + ctx context.Context, customerId int) ( models.ApiResponse[[]models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `customerId` | `int` | Template, Required | The Chargify id of the customer | - -## Response Type - -[`[]models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `customerId` | `int` | Template, Required | The Chargify id of the customer | + +## Response Type + +[`[]models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() customerId := 150 @@ -527,6 +531,6 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - +} +``` + diff --git a/doc/controllers/events-based-billing-segments.md b/doc/controllers/events-based-billing-segments.md index 788d307e..687cabea 100644 --- a/doc/controllers/events-based-billing-segments.md +++ b/doc/controllers/events-based-billing-segments.md @@ -1,75 +1,83 @@ -# Events-Based Billing Segments - -```go -eventsBasedBillingSegmentsController := client.EventsBasedBillingSegmentsController() -``` - -## Class Name - -`EventsBasedBillingSegmentsController` - -## Methods - +# Events-Based Billing Segments + +```go +eventsBasedBillingSegmentsController := client.EventsBasedBillingSegmentsController() +``` + +## Class Name + +`EventsBasedBillingSegmentsController` + +## Methods + * [Create Segment](../../doc/controllers/events-based-billing-segments.md#create-segment) * [List Segments for Price Point](../../doc/controllers/events-based-billing-segments.md#list-segments-for-price-point) * [Update Segment](../../doc/controllers/events-based-billing-segments.md#update-segment) * [Delete Segment](../../doc/controllers/events-based-billing-segments.md#delete-segment) * [Bulk Create Segments](../../doc/controllers/events-based-billing-segments.md#bulk-create-segments) -* [Bulk Update Segments](../../doc/controllers/events-based-billing-segments.md#bulk-update-segments) - - -# Create Segment - +* [Bulk Update Segments](../../doc/controllers/events-based-billing-segments.md#bulk-update-segments) + + +# Create Segment + This endpoint creates a new Segment for a Component with segmented Metric. It allows you to specify properties to bill upon and prices for each Segment. You can only pass as many "property_values" as the related Metric has segmenting properties defined. -You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. - -```go -CreateSegment( - ctx context.Context, - componentId string, - pricePointId string, +You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. + +```go +CreateSegment( + ctx context.Context, + componentId string, + pricePointId string, body *models.CreateSegmentRequest) ( models.ApiResponse[models.SegmentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | ID or Handle for the Component | -| `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | -| `body` | [`*models.CreateSegmentRequest`](../../doc/models/create-segment-request.md) | Body, Optional | - | - -## Response Type - -[`models.SegmentResponse`](../../doc/models/segment-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `string` | Template, Required | ID or Handle for the Component | +| `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | +| `body` | [`*models.CreateSegmentRequest`](../../doc/models/create-segment-request.md) | Body, Optional | - | + +## Response Type + +[`models.SegmentResponse`](../../doc/models/segment-response.md) + +## Example Usage + +```go ctx := context.Background() componentId := "component_id8" pricePointId := "price_point_id8" +bodySegmentPrices0UnitPrice := models.CreateOrUpdateSegmentPriceUnitPriceContainer.FromPrecision(float64(0.19)) + bodySegmentPrices0 := models.CreateOrUpdateSegmentPrice{ StartingQuantity: models.ToPointer(1), EndingQuantity: models.ToPointer(10000), - UnitPrice: interface{}("[key1, val1][key2, val2]"), + UnitPrice: bodySegmentPrices0UnitPrice, } +bodySegmentPrices1UnitPrice := models.CreateOrUpdateSegmentPriceUnitPriceContainer.FromPrecision(float64(0.09)) + bodySegmentPrices1 := models.CreateOrUpdateSegmentPrice{ StartingQuantity: models.ToPointer(10001), - UnitPrice: interface{}("[key1, val1][key2, val2]"), + UnitPrice: bodySegmentPrices1UnitPrice, } bodySegmentPrices := []models.CreateOrUpdateSegmentPrice{bodySegmentPrices0, bodySegmentPrices1} +bodySegmentSegmentProperty1Value := models.CreateSegmentSegmentProperty1ValueContainer.FromString("France") + +bodySegmentSegmentProperty2Value := models.CreateSegmentSegmentProperty2ValueContainer.FromString("Spain") + bodySegment := models.CreateSegment{ - SegmentProperty1Value: models.ToPointer(interface{}("[key1, val1][key2, val2]")), - SegmentProperty2Value: models.ToPointer(interface{}("[key1, val1][key2, val2]")), PricingScheme: models.PricingScheme("volume"), Prices: bodySegmentPrices, + SegmentProperty1Value: models.ToPointer(bodySegmentSegmentProperty1Value), + SegmentProperty2Value: models.ToPointer(bodySegmentSegmentProperty2Value), } body := models.CreateSegmentRequest{ @@ -83,109 +91,113 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentErrorsException`](../../doc/models/event-based-billing-segment-errors-exception.md) | - - -# List Segments for Price Point - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentErrorsException`](../../doc/models/event-based-billing-segment-errors-exception.md) | + + +# List Segments for Price Point + This endpoint allows you to fetch Segments created for a given Price Point. They will be returned in the order of creation. You can pass `page` and `per_page` parameters in order to access all of the segments. By default it will return `30` records. You can set `per_page` to `200` at most. -You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. - -```go -ListSegmentsForPricePoint( - ctx context.Context,input ListSegmentsForPricePointInput) ( +You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. + +```go +ListSegmentsForPricePoint( + ctx context.Context, + input ListSegmentsForPricePointInput) ( models.ApiResponse[models.ListSegmentsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | ID or Handle for the Component | -| `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `filterSegmentProperty1Value` | `*string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_1` on attached Metric. If empty string is passed, this filter would be rejected. Use in query `filter[segment_property_1_value]=EU`. | -| `filterSegmentProperty2Value` | `*string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_2` on attached Metric. If empty string is passed, this filter would be rejected. | -| `filterSegmentProperty3Value` | `*string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_3` on attached Metric. If empty string is passed, this filter would be rejected. | -| `filterSegmentProperty4Value` | `*string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_4` on attached Metric. If empty string is passed, this filter would be rejected. | - -## Response Type - -[`models.ListSegmentsResponse`](../../doc/models/list-segments-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `string` | Template, Required | ID or Handle for the Component | +| `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `filterSegmentProperty1Value` | `*string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_1` on attached Metric. If empty string is passed, this filter would be rejected. Use in query `filter[segment_property_1_value]=EU`. | +| `filterSegmentProperty2Value` | `*string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_2` on attached Metric. If empty string is passed, this filter would be rejected. | +| `filterSegmentProperty3Value` | `*string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_3` on attached Metric. If empty string is passed, this filter would be rejected. | +| `filterSegmentProperty4Value` | `*string` | Query, Optional | The value passed here would be used to filter segments. Pass a value related to `segment_property_4` on attached Metric. If empty string is passed, this filter would be rejected. | + +## Response Type + +[`models.ListSegmentsResponse`](../../doc/models/list-segments-response.md) + +## Example Usage + +```go ctx := context.Background() -componentId := "component_id8" -pricePointId := "price_point_id8" -page := 2 -perPage := 50Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') -apiResponse, err := eventsBasedBillingSegmentsController.ListSegmentsForPricePoint(ctx, componentId, pricePointId, &page, &perPage, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key')) +collectedInput := advancedbilling.ListSegmentsForPricePointInput{ + ComponentId: "component_id8", + PricePointId: "price_point_id8", + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := eventsBasedBillingSegmentsController.ListSegmentsForPricePoint(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingListSegmentsErrorsException`](../../doc/models/event-based-billing-list-segments-errors-exception.md) | - - -# Update Segment - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingListSegmentsErrorsException`](../../doc/models/event-based-billing-list-segments-errors-exception.md) | + + +# Update Segment + This endpoint updates a single Segment for a Component with a segmented Metric. It allows you to update the pricing for the segment. -You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. - -```go -UpdateSegment( - ctx context.Context, - componentId string, - pricePointId string, - id float64, +You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. + +```go +UpdateSegment( + ctx context.Context, + componentId string, + pricePointId string, + id float64, body *models.UpdateSegmentRequest) ( models.ApiResponse[models.SegmentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | ID or Handle of the Component | -| `pricePointId` | `string` | Template, Required | ID or Handle of the Price Point belonging to the Component | -| `id` | `float64` | Template, Required | The ID of the Segment | -| `body` | [`*models.UpdateSegmentRequest`](../../doc/models/update-segment-request.md) | Body, Optional | - | - -## Response Type - -[`models.SegmentResponse`](../../doc/models/segment-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `string` | Template, Required | ID or Handle of the Component | +| `pricePointId` | `string` | Template, Required | ID or Handle of the Price Point belonging to the Component | +| `id` | `float64` | Template, Required | The ID of the Segment | +| `body` | [`*models.UpdateSegmentRequest`](../../doc/models/update-segment-request.md) | Body, Optional | - | + +## Response Type + +[`models.SegmentResponse`](../../doc/models/segment-response.md) + +## Example Usage + +```go ctx := context.Background() componentId := "component_id8" pricePointId := "price_point_id8" @@ -198,48 +210,48 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentErrorsException`](../../doc/models/event-based-billing-segment-errors-exception.md) | - - -# Delete Segment - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentErrorsException`](../../doc/models/event-based-billing-segment-errors-exception.md) | + + +# Delete Segment + This endpoint allows you to delete a Segment with specified ID. -You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. - -```go -DeleteSegment( - ctx context.Context, - componentId string, - pricePointId string, +You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. + +```go +DeleteSegment( + ctx context.Context, + componentId string, + pricePointId string, id float64) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | ID or Handle of the Component | -| `pricePointId` | `string` | Template, Required | ID or Handle of the Price Point belonging to the Component | -| `id` | `float64` | Template, Required | The ID of the Segment | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `string` | Template, Required | ID or Handle of the Component | +| `pricePointId` | `string` | Template, Required | ID or Handle of the Price Point belonging to the Component | +| `id` | `float64` | Template, Required | The ID of the Segment | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() componentId := "component_id8" pricePointId := "price_point_id8" @@ -250,50 +262,50 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | `ApiError` | - - -# Bulk Create Segments - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | `ApiError` | + + +# Bulk Create Segments + This endpoint allows you to create multiple segments in one request. The array of segments can contain up to `2000` records. If any of the records contain an error the whole request would fail and none of the requested segments get created. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. -You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. - -```go -BulkCreateSegments( - ctx context.Context, - componentId string, - pricePointId string, +You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. + +```go +BulkCreateSegments( + ctx context.Context, + componentId string, + pricePointId string, body *models.BulkCreateSegments) ( models.ApiResponse[models.ListSegmentsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | ID or Handle for the Component | -| `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | -| `body` | [`*models.BulkCreateSegments`](../../doc/models/bulk-create-segments.md) | Body, Optional | - | - -## Response Type - -[`models.ListSegmentsResponse`](../../doc/models/list-segments-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `string` | Template, Required | ID or Handle for the Component | +| `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | +| `body` | [`*models.BulkCreateSegments`](../../doc/models/bulk-create-segments.md) | Body, Optional | - | + +## Response Type + +[`models.ListSegmentsResponse`](../../doc/models/list-segments-response.md) + +## Example Usage + +```go ctx := context.Background() componentId := "component_id8" pricePointId := "price_point_id8" @@ -305,50 +317,50 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentException`](../../doc/models/event-based-billing-segment-exception.md) | - - -# Bulk Update Segments - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentException`](../../doc/models/event-based-billing-segment-exception.md) | + + +# Bulk Update Segments + This endpoint allows you to update multiple segments in one request. The array of segments can contain up to `1000` records. If any of the records contain an error the whole request would fail and none of the requested segments get updated. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. -You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. - -```go -BulkUpdateSegments( - ctx context.Context, - componentId string, - pricePointId string, +You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. + +```go +BulkUpdateSegments( + ctx context.Context, + componentId string, + pricePointId string, body *models.BulkUpdateSegments) ( models.ApiResponse[models.ListSegmentsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `componentId` | `string` | Template, Required | ID or Handle for the Component | -| `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | -| `body` | [`*models.BulkUpdateSegments`](../../doc/models/bulk-update-segments.md) | Body, Optional | - | - -## Response Type - -[`models.ListSegmentsResponse`](../../doc/models/list-segments-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `componentId` | `string` | Template, Required | ID or Handle for the Component | +| `pricePointId` | `string` | Template, Required | ID or Handle for the Price Point belonging to the Component | +| `body` | [`*models.BulkUpdateSegments`](../../doc/models/bulk-update-segments.md) | Body, Optional | - | + +## Response Type + +[`models.ListSegmentsResponse`](../../doc/models/list-segments-response.md) + +## Example Usage + +```go ctx := context.Background() componentId := "component_id8" pricePointId := "price_point_id8" @@ -360,13 +372,13 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentException`](../../doc/models/event-based-billing-segment-exception.md) | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`EventBasedBillingSegmentException`](../../doc/models/event-based-billing-segment-exception.md) | + diff --git a/doc/controllers/events.md b/doc/controllers/events.md index e7e57a07..179641fa 100644 --- a/doc/controllers/events.md +++ b/doc/controllers/events.md @@ -1,22 +1,22 @@ -# Events - -```go -eventsController := client.EventsController() -``` - -## Class Name - -`EventsController` - -## Methods - +# Events + +```go +eventsController := client.EventsController() +``` + +## Class Name + +`EventsController` + +## Methods + * [List Events](../../doc/controllers/events.md#list-events) * [List Subscription Events](../../doc/controllers/events.md#list-subscription-events) -* [Read Events Count](../../doc/controllers/events.md#read-events-count) - - -# List Events - +* [Read Events Count](../../doc/controllers/events.md#read-events-count) + + +# List Events + ## Events Intro Chargify Events include various activity that happens around a Site. This information is **especially** useful to track down issues that arise when subscriptions are not created due to errors. @@ -78,261 +78,273 @@ Here’s an example event for the `subscription_state_change` event: "created_at": "2012-01-30T10:43:33-05:00" } } -``` - -```go -ListEvents( - ctx context.Context,input ListEventsInput) ( +``` + +```go +ListEvents( + ctx context.Context, + input ListEventsInput) ( models.ApiResponse[[]models.EventResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `sinceId` | `*int` | Query, Optional | Returns events with an id greater than or equal to the one specified | -| `maxId` | `*int` | Query, Optional | Returns events with an id less than or equal to the one specified | -| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned events. | -| `filter` | [`[]models.EventType`](../../doc/models/event-type.md) | Query, Optional | You can pass multiple event keys after comma.
Use in query `filter=signup_success,payment_success`. | -| `dateField` | [`*models.ListEventsDateField`](../../doc/models/list-events-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. | -| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | - -## Response Type - -[`[]models.EventResponse`](../../doc/models/event-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `sinceId` | `*int` | Query, Optional | Returns events with an id greater than or equal to the one specified | +| `maxId` | `*int` | Query, Optional | Returns events with an id less than or equal to the one specified | +| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned events. | +| `filter` | [`[]models.EventType`](../../doc/models/event-type.md) | Query, Optional | You can pass multiple event keys after comma.
Use in query `filter=signup_success,payment_success`. | +| `dateField` | [`*models.ListEventsDateField`](../../doc/models/list-events-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. | +| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | + +## Response Type + +[`[]models.EventResponse`](../../doc/models/event-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -direction := models.Direction("desc") -filter := []models.EventType{models.EventType("custom_field_value_change"), models.EventType("payment_success")} -dateField := models.ListEventsDateField("created_at") -apiResponse, err := eventsController.ListEvents(ctx, &page, &perPage, nil, nil, &direction, filter, &dateField, nil, nil, nil, nil) +collectedInput := advancedbilling.ListEventsInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + Direction: models.ToPointer(models.Direction("desc")), + Filter: []models.EventType{models.EventType("custom_field_value_change"), models.EventType("payment_success")}, + DateField: models.ToPointer(models.ListEventsDateField("created_at")), +} + +apiResponse, err := eventsController.ListEvents(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "event": { - "id": 343087780, - "key": "subscription_state_change", - "message": "State changed on Test subscription to Monthly Product from active to past_due", - "subscription_id": 14950962, - "customer_id": 12345678, - "created_at": "2016-10-27T16:42:22-04:00", - "event_specific_data": { - "previous_subscription_state": "active", - "new_subscription_state": "past_due" - } - } - }, - { - "event": { - "id": 343087742, - "key": "billing_date_change", - "message": "Billing date changed on Test's subscription to Monthly Product from 11/27/2016 to 10/27/2016", - "subscription_id": 14950962, - "customer_id": 12345678, - "created_at": "2016-10-27T16:42:19-04:00", - "event_specific_data": null - } - }, - { - "event": { - "id": 343085267, - "key": "statement_closed", - "message": "Statement 79401838 closed (but not settled) for Test's subscription to ANNUAL product", - "subscription_id": 14950975, - "customer_id": 87654321, - "created_at": "2016-10-27T16:40:40-04:00", - "event_specific_data": null - } - }, - { - "event": { - "id": 4481, - "key": "custom_field_value_change", - "message": "Custom field (Extra support included) changed for Subscription 117 from 'Yes' to 'No'.", - "subscription_id": 117, - "customer_id": 22334455, - "created_at": "2022-03-24T07:55:06-04:00", - "event_specific_data": { - "event_type": "updated", - "metafield_name": "Extra support included", - "metafield_id": 2, - "old_value": "Yes", - "new_value": "No", - "resource_type": "Subscription", - "resource_id": 117 - } - } - } -] -``` - - -# List Subscription Events - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "event": { + "id": 343087780, + "key": "subscription_state_change", + "message": "State changed on Test subscription to Monthly Product from active to past_due", + "subscription_id": 14950962, + "customer_id": 12345678, + "created_at": "2016-10-27T16:42:22-04:00", + "event_specific_data": { + "previous_subscription_state": "active", + "new_subscription_state": "past_due" + } + } + }, + { + "event": { + "id": 343087742, + "key": "billing_date_change", + "message": "Billing date changed on Test's subscription to Monthly Product from 11/27/2016 to 10/27/2016", + "subscription_id": 14950962, + "customer_id": 12345678, + "created_at": "2016-10-27T16:42:19-04:00", + "event_specific_data": null + } + }, + { + "event": { + "id": 343085267, + "key": "statement_closed", + "message": "Statement 79401838 closed (but not settled) for Test's subscription to ANNUAL product", + "subscription_id": 14950975, + "customer_id": 87654321, + "created_at": "2016-10-27T16:40:40-04:00", + "event_specific_data": null + } + }, + { + "event": { + "id": 4481, + "key": "custom_field_value_change", + "message": "Custom field (Extra support included) changed for Subscription 117 from 'Yes' to 'No'.", + "subscription_id": 117, + "customer_id": 22334455, + "created_at": "2022-03-24T07:55:06-04:00", + "event_specific_data": { + "event_type": "updated", + "metafield_name": "Extra support included", + "metafield_id": 2, + "old_value": "Yes", + "new_value": "No", + "resource_type": "Subscription", + "resource_id": 117 + } + } + } +] +``` + + +# List Subscription Events + The following request will return a list of events for a subscription. -Each event type has its own `event_specific_data` specified. - -```go -ListSubscriptionEvents( - ctx context.Context,input ListSubscriptionEventsInput) ( +Each event type has its own `event_specific_data` specified. + +```go +ListSubscriptionEvents( + ctx context.Context, + input ListSubscriptionEventsInput) ( models.ApiResponse[[]models.EventResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `sinceId` | `*int` | Query, Optional | Returns events with an id greater than or equal to the one specified | -| `maxId` | `*int` | Query, Optional | Returns events with an id less than or equal to the one specified | -| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned events. | -| `filter` | [`[]models.EventType`](../../doc/models/event-type.md) | Query, Optional | You can pass multiple event keys after comma.
Use in query `filter=signup_success,payment_success`. | - -## Response Type - -[`[]models.EventResponse`](../../doc/models/event-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `sinceId` | `*int` | Query, Optional | Returns events with an id greater than or equal to the one specified | +| `maxId` | `*int` | Query, Optional | Returns events with an id less than or equal to the one specified | +| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned events. | +| `filter` | [`[]models.EventType`](../../doc/models/event-type.md) | Query, Optional | You can pass multiple event keys after comma.
Use in query `filter=signup_success,payment_success`. | + +## Response Type + +[`[]models.EventResponse`](../../doc/models/event-response.md) + +## Example Usage + +```go ctx := context.Background() -subscriptionId := 222 -page := 2 -perPage := 50 -direction := models.Direction("desc") -filter := []models.EventType{models.EventType("custom_field_value_change"), models.EventType("payment_success")} -apiResponse, err := eventsController.ListSubscriptionEvents(ctx, subscriptionId, &page, &perPage, nil, nil, &direction, filter) +collectedInput := advancedbilling.ListSubscriptionEventsInput{ + SubscriptionId: 222, + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + Direction: models.ToPointer(models.Direction("desc")), + Filter: []models.EventType{models.EventType("custom_field_value_change"), models.EventType("payment_success")}, +} + +apiResponse, err := eventsController.ListSubscriptionEvents(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "event": { - "id": 344799837, - "key": "statement_settled", - "message": "Statement 79702531 settled successfully for Amelia Example's subscription to Basic Plan", - "subscription_id": 14900541, - "customer_id": 77223344, - "created_at": "2016-11-01T12:41:29-04:00", - "event_specific_data": null - } - }, - { - "event": { - "id": 344799815, - "key": "renewal_success", - "message": "Successful renewal for Amelia Example's subscription to Basic Plan", - "subscription_id": 14900541, - "customer_id": 77223344, - "created_at": "2016-11-01T12:41:28-04:00", - "event_specific_data": { - "product_id": 3792003, - "account_transaction_id": 7590246 - } - } - }, - { - "event": { - "id": 344799705, - "key": "billing_date_change", - "message": "Billing date changed on Amelia Example's subscription to Basic Plan from 11/26/2016 to 11/01/2016", - "subscription_id": 14900541, - "customer_id": 77223344, - "created_at": "2016-11-01T12:41:25-04:00", - "event_specific_data": null - } - } -] -``` - - -# Read Events Count - -Get a count of all the events for a given site by using this method. - -```go -ReadEventsCount( - ctx context.Context,input ReadEventsCountInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "event": { + "id": 344799837, + "key": "statement_settled", + "message": "Statement 79702531 settled successfully for Amelia Example's subscription to Basic Plan", + "subscription_id": 14900541, + "customer_id": 77223344, + "created_at": "2016-11-01T12:41:29-04:00", + "event_specific_data": null + } + }, + { + "event": { + "id": 344799815, + "key": "renewal_success", + "message": "Successful renewal for Amelia Example's subscription to Basic Plan", + "subscription_id": 14900541, + "customer_id": 77223344, + "created_at": "2016-11-01T12:41:28-04:00", + "event_specific_data": { + "product_id": 3792003, + "account_transaction_id": 7590246 + } + } + }, + { + "event": { + "id": 344799705, + "key": "billing_date_change", + "message": "Billing date changed on Amelia Example's subscription to Basic Plan from 11/26/2016 to 11/01/2016", + "subscription_id": 14900541, + "customer_id": 77223344, + "created_at": "2016-11-01T12:41:25-04:00", + "event_specific_data": null + } + } +] +``` + + +# Read Events Count + +Get a count of all the events for a given site by using this method. + +```go +ReadEventsCount( + ctx context.Context, + input ReadEventsCountInput) ( models.ApiResponse[models.CountResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `sinceId` | `*int` | Query, Optional | Returns events with an id greater than or equal to the one specified | -| `maxId` | `*int` | Query, Optional | Returns events with an id less than or equal to the one specified | -| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned events. | -| `filter` | [`[]models.EventType`](../../doc/models/event-type.md) | Query, Optional | You can pass multiple event keys after comma.
Use in query `filter=signup_success,payment_success`. | - -## Response Type - -[`models.CountResponse`](../../doc/models/count-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `sinceId` | `*int` | Query, Optional | Returns events with an id greater than or equal to the one specified | +| `maxId` | `*int` | Query, Optional | Returns events with an id less than or equal to the one specified | +| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned events. | +| `filter` | [`[]models.EventType`](../../doc/models/event-type.md) | Query, Optional | You can pass multiple event keys after comma.
Use in query `filter=signup_success,payment_success`. | + +## Response Type + +[`models.CountResponse`](../../doc/models/count-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -direction := models.Direction("desc") -filter := []models.EventType{models.EventType("custom_field_value_change"), models.EventType("payment_success")} -apiResponse, err := eventsController.ReadEventsCount(ctx, &page, &perPage, nil, nil, &direction, filter) +collectedInput := advancedbilling.ReadEventsCountInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + Direction: models.ToPointer(models.Direction("desc")), + Filter: []models.EventType{models.EventType("custom_field_value_change"), models.EventType("payment_success")}, +} + +apiResponse, err := eventsController.ReadEventsCount(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "count": 144 -} -``` - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "count": 144 +} +``` + diff --git a/doc/controllers/insights.md b/doc/controllers/insights.md index 739f6751..042360ef 100644 --- a/doc/controllers/insights.md +++ b/doc/controllers/insights.md @@ -1,23 +1,23 @@ -# Insights - -```go -insightsController := client.InsightsController() -``` - -## Class Name - -`InsightsController` - -## Methods - +# Insights + +```go +insightsController := client.InsightsController() +``` + +## Class Name + +`InsightsController` + +## Methods + * [Read Site Stats](../../doc/controllers/insights.md#read-site-stats) * [Read Mrr](../../doc/controllers/insights.md#read-mrr) * [List Mrr Movements](../../doc/controllers/insights.md#list-mrr-movements) -* [List Mrr Per Subscription](../../doc/controllers/insights.md#list-mrr-per-subscription) - - -# Read Site Stats - +* [List Mrr Per Subscription](../../doc/controllers/insights.md#list-mrr-per-subscription) + + +# Read Site Stats + The Stats API is a very basic view of some Site-level stats. This API call only answers with JSON responses. An XML version is not provided. ## Stats Documentation @@ -26,22 +26,22 @@ There currently is not a complimentary matching set of documentation that compli ``` https://subdomain.chargify.com/dashboard -``` - -```go -ReadSiteStats( +``` + +```go +ReadSiteStats( ctx context.Context) ( models.ApiResponse[models.SiteSummary], - error) -``` - -## Response Type - -[`models.SiteSummary`](../../doc/models/site-summary.md) - -## Example Usage - -```go + error) +``` + +## Response Type + +[`models.SiteSummary`](../../doc/models/site-summary.md) + +## Example Usage + +```go ctx := context.Background() apiResponse, err := insightsController.ReadSiteStats(ctx) if err != nil { @@ -50,58 +50,58 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "seller_name": "Acme, Inc.", - "site_name": "Production", - "site_id": 12345, - "site_currency": "USD", - "stats": { - "total_subscriptions": 120, - "subscriptions_today": 4, - "total_revenue": "$45,978.81", - "revenue_today": "$1,405.12", - "revenue_this_month": "$10,000.00", - "revenue_this_year": "$27,935.24" - } -} -``` - - -# Read Mrr - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "seller_name": "Acme, Inc.", + "site_name": "Production", + "site_id": 12345, + "site_currency": "USD", + "stats": { + "total_subscriptions": 120, + "subscriptions_today": 4, + "total_revenue": "$45,978.81", + "revenue_today": "$1,405.12", + "revenue_this_month": "$10,000.00", + "revenue_this_year": "$27,935.24" + } +} +``` + + +# Read Mrr + **This endpoint is deprecated.** -This endpoint returns your site's current MRR, including plan and usage breakouts. - -```go -ReadMrr( - ctx context.Context, - atTime *time.Time, +This endpoint returns your site's current MRR, including plan and usage breakouts. + +```go +ReadMrr( + ctx context.Context, + atTime *time.Time, subscriptionId *int) ( models.ApiResponse[models.MRRResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `atTime` | `*time.Time` | Query, Optional | submit a timestamp in ISO8601 format to request MRR for a historic time | -| `subscriptionId` | `*int` | Query, Optional | submit the id of a subscription in order to limit results | - -## Response Type - -[`models.MRRResponse`](../../doc/models/mrr-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `atTime` | `*time.Time` | Query, Optional | submit a timestamp in ISO8601 format to request MRR for a historic time | +| `subscriptionId` | `*int` | Query, Optional | submit the id of a subscription in order to limit results | + +## Response Type + +[`models.MRRResponse`](../../doc/models/mrr-response.md) + +## Example Usage + +```go ctx := context.Background() apiResponse, err := insightsController.ReadMrr(ctx, nil, nil) @@ -111,32 +111,32 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "mrr": { - "amount_in_cents": 9915593, - "amount_formatted": "$99,155.93", - "currency": "USD", - "currency_symbol": "$", - "at_time": "2021-02-03T14:23:17-05:00", - "breakouts": { - "plan_amount_in_cents": 9913593, - "plan_amount_formatted": "$99,135.93", - "usage_amount_in_cents": 2000, - "usage_amount_formatted": "$20.00" - } - } -} -``` - - -# List Mrr Movements - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "mrr": { + "amount_in_cents": 9915593, + "amount_formatted": "$99,155.93", + "currency": "USD", + "currency_symbol": "$", + "at_time": "2021-02-03T14:23:17-05:00", + "breakouts": { + "plan_amount_in_cents": 9913593, + "plan_amount_formatted": "$99,135.93", + "usage_amount_in_cents": 2000, + "usage_amount_formatted": "$20.00" + } + } +} +``` + + +# List Mrr Movements + **This endpoint is deprecated.** This endpoint returns your site's MRR movements. @@ -162,147 +162,155 @@ Plan includes revenue from: Usage includes revenue from: * Metered Components -* Prepaid Usage Components - -```go -ListMrrMovements( - ctx context.Context,input ListMrrMovementsInput) ( +* Prepaid Usage Components + +```go +ListMrrMovements( + ctx context.Context, + input ListMrrMovementsInput) ( models.ApiResponse[models.ListMRRResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `*int` | Query, Optional | optionally filter results by subscription | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 10. The maximum allowed values is 50; any per_page value over 50 will be changed to 50.
Use in query `per_page=20`. | -| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | - -## Response Type - -[`models.ListMRRResponse`](../../doc/models/list-mrr-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `*int` | Query, Optional | optionally filter results by subscription | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 10. The maximum allowed values is 50; any per_page value over 50 will be changed to 50.
Use in query `per_page=20`. | +| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | + +## Response Type + +[`models.ListMRRResponse`](../../doc/models/list-mrr-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 20 -apiResponse, err := insightsController.ListMrrMovements(ctx, nil, &page, &perPage, nil) +collectedInput := advancedbilling.ListMrrMovementsInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(20), +} + +apiResponse, err := insightsController.ListMrrMovements(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "mrr": { - "page": 0, - "per_page": 10, - "total_pages": 80, - "total_entries": 791, - "currency": "USD", - "currency_symbol": "$", - "movements": [ - { - "timestamp": "2014-12-03T13:59:46-05:00", - "amount_in_cents": 2173, - "amount_formatted": "$21.73", - "description": "Awesome Company signed up for Super Product ($21.73/mo)", - "category": "new_business", - "breakouts": { - "plan_amount_in_cents": 2173, - "plan_amount_formatted": "$21.73", - "usage_amount_in_cents": 0, - "usage_amount_formatted": "$0.00" - }, - "line_items": [ - { - "product_id": 306386, - "component_id": 0, - "price_point_id": 3856987, - "name": "Cached Queries", - "mrr": 2173, - "mrr_movements": [ - { - "amount": 2173, - "category": "new_business", - "subscriber_delta": 0, - "lead_delta": 0 - } - ], - "quantity": 1, - "prev_quantity": 0, - "recurring": true - } - ], - "subscription_id": 12355, - "subscriber_name": "Amy Smith" - } - ] - } -} -``` - - -# List Mrr Per Subscription - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "mrr": { + "page": 0, + "per_page": 10, + "total_pages": 80, + "total_entries": 791, + "currency": "USD", + "currency_symbol": "$", + "movements": [ + { + "timestamp": "2014-12-03T13:59:46-05:00", + "amount_in_cents": 2173, + "amount_formatted": "$21.73", + "description": "Awesome Company signed up for Super Product ($21.73/mo)", + "category": "new_business", + "breakouts": { + "plan_amount_in_cents": 2173, + "plan_amount_formatted": "$21.73", + "usage_amount_in_cents": 0, + "usage_amount_formatted": "$0.00" + }, + "line_items": [ + { + "product_id": 306386, + "component_id": 0, + "price_point_id": 3856987, + "name": "Cached Queries", + "mrr": 2173, + "mrr_movements": [ + { + "amount": 2173, + "category": "new_business", + "subscriber_delta": 0, + "lead_delta": 0 + } + ], + "quantity": 1, + "prev_quantity": 0, + "recurring": true + } + ], + "subscription_id": 12355, + "subscriber_name": "Amy Smith" + } + ] + } +} +``` + + +# List Mrr Per Subscription + **This endpoint is deprecated.** -This endpoint returns your site's current MRR, including plan and usage breakouts split per subscription. - -```go -ListMrrPerSubscription( - ctx context.Context,input ListMrrPerSubscriptionInput) ( +This endpoint returns your site's current MRR, including plan and usage breakouts split per subscription. + +```go +ListMrrPerSubscription( + ctx context.Context, + input ListMrrPerSubscriptionInput) ( models.ApiResponse[models.SubscriptionMRRResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `filterSubscriptionIds` | `[]int` | Query, Optional | Submit ids in order to limit results. Use in query: `filter[subscription_ids]=1,2,3`. | -| `atTime` | `*string` | Query, Optional | Submit a timestamp in ISO8601 format to request MRR for a historic time. Use in query: `at_time=2022-01-10T10:00:00-05:00`. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | Controls the order in which results are returned. Records are ordered by subscription_id in ascending order by default. Use in query `direction=desc`. | - -## Response Type - -[`models.SubscriptionMRRResponse`](../../doc/models/subscription-mrr-response.md) - -## Example Usage - -```go -ctx := context.Background()Liquid error: Value cannot be null. (Parameter 'key') -atTime := "at_time=2022-01-10T10:00:00-05:00" -page := 2 -perPage := 50 -direction := models.Direction("desc") - -apiResponse, err := insightsController.ListMrrPerSubscription(ctx, Liquid error: Value cannot be null. (Parameter 'key'), &atTime, &page, &perPage, &direction) + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `filterSubscriptionIds` | `[]int` | Query, Optional | Submit ids in order to limit results. Use in query: `filter[subscription_ids]=1,2,3`. | +| `atTime` | `*string` | Query, Optional | Submit a timestamp in ISO8601 format to request MRR for a historic time. Use in query: `at_time=2022-01-10T10:00:00-05:00`. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | Controls the order in which results are returned. Records are ordered by subscription_id in ascending order by default. Use in query `direction=desc`. | + +## Response Type + +[`models.SubscriptionMRRResponse`](../../doc/models/subscription-mrr-response.md) + +## Example Usage + +```go +ctx := context.Background() + +collectedInput := advancedbilling.ListMrrPerSubscriptionInput{ +Liquid error: Value cannot be null. (Parameter 'key') AtTime: models.ToPointer("at_time=2022-01-10T10:00:00-05:00"), + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + Direction: models.ToPointer(models.Direction("desc")), +} + +apiResponse, err := insightsController.ListMrrPerSubscription(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 400 | Bad Request | [`SubscriptionsMrrErrorResponseException`](../../doc/models/subscriptions-mrr-error-response-exception.md) | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 400 | Bad Request | [`SubscriptionsMrrErrorResponseException`](../../doc/models/subscriptions-mrr-error-response-exception.md) | + diff --git a/doc/controllers/invoices.md b/doc/controllers/invoices.md index 2e9e2dfd..5726e266 100644 --- a/doc/controllers/invoices.md +++ b/doc/controllers/invoices.md @@ -1,15 +1,15 @@ -# Invoices - -```go -invoicesController := client.InvoicesController() -``` - -## Class Name - -`InvoicesController` - -## Methods - +# Invoices + +```go +invoicesController := client.InvoicesController() +``` + +## Class Name + +`InvoicesController` + +## Methods + * [Refund Invoice](../../doc/controllers/invoices.md#refund-invoice) * [List Invoices](../../doc/controllers/invoices.md#list-invoices) * [Read Invoice](../../doc/controllers/invoices.md#read-invoice) @@ -26,52 +26,54 @@ invoicesController := client.InvoicesController() * [Send Invoice](../../doc/controllers/invoices.md#send-invoice) * [Preview Customer Information Changes](../../doc/controllers/invoices.md#preview-customer-information-changes) * [Update Customer Information](../../doc/controllers/invoices.md#update-customer-information) -* [Issue Invoice](../../doc/controllers/invoices.md#issue-invoice) - - -# Refund Invoice - +* [Issue Invoice](../../doc/controllers/invoices.md#issue-invoice) + + +# Refund Invoice + Refund an invoice, segment, or consolidated invoice. ## Partial Refund for Consolidated Invoice A refund less than the total of a consolidated invoice will be split across its segments. -A $50.00 refund on a $100.00 consolidated invoice with one $60.00 and one $40.00 segment, the refunded amount will be applied as 50% of each ($30.00 and $20.00 respectively). - -```go -RefundInvoice( - ctx context.Context, - uid string, +A $50.00 refund on a $100.00 consolidated invoice with one $60.00 and one $40.00 segment, the refunded amount will be applied as 50% of each ($30.00 and $20.00 respectively). + +```go +RefundInvoice( + ctx context.Context, + uid string, body *models.RefundInvoiceRequest) ( models.ApiResponse[models.Invoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | -| `body` | [`*models.RefundInvoiceRequest`](../../doc/models/refund-invoice-request.md) | Body, Optional | - | - -## Response Type - -[`models.Invoice`](../../doc/models/invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | +| `body` | [`*models.RefundInvoiceRequest`](../../doc/models/refund-invoice-request.md) | Body, Optional | - | + +## Response Type + +[`models.Invoice`](../../doc/models/invoice.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" -bodyRefund := models.Refund{ - Amount: models.ToPointer("100.00"), - Memo: models.ToPointer("Refund for Basic Plan renewal"), - PaymentId: models.ToPointer(12345), +bodyRefundRefundInvoice := models.RefundInvoice{ + Amount: "100.00", + Memo: "Refund for Basic Plan renewal", + PaymentId: 12345, VoidInvoice: models.ToPointer(true), } +bodyRefund := models.RefundInvoiceRequestRefundContainer.FromRefundInvoice(bodyRefundRefundInvoice) + body := models.RefundInvoiceRequest{ Refund: bodyRefund, } @@ -83,387 +85,384 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Invoices - -By default, invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`, or `refunds`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. - -```go -ListInvoices( - ctx context.Context,input ListInvoicesInput) ( +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Invoices + +By default, invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`, or `refunds`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. + +```go +ListInvoices( + ctx context.Context, + input ListInvoicesInput) ( models.ApiResponse[models.ListInvoicesResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns invoices with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns invoices with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `status` | [`*models.InvoiceStatus`](../../doc/models/invoice-status.md) | Query, Optional | The current status of the invoice. Allowed Values: draft, open, paid, pending, voided | -| `subscriptionId` | `*int` | Query, Optional | The subscription's ID. | -| `subscriptionGroupUid` | `*string` | Query, Optional | The UID of the subscription group you want to fetch consolidated invoices for. This will return a paginated list of consolidated invoices for the specified group. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned invoices. | -| `lineItems` | `*bool` | Query, Optional | Include line items data | -| `discounts` | `*bool` | Query, Optional | Include discounts data | -| `taxes` | `*bool` | Query, Optional | Include taxes data | -| `credits` | `*bool` | Query, Optional | Include credits data | -| `payments` | `*bool` | Query, Optional | Include payments data | -| `customFields` | `*bool` | Query, Optional | Include custom fields data | -| `refunds` | `*bool` | Query, Optional | Include refunds data | -| `dateField` | [`*models.InvoiceDateField`](../../doc/models/invoice-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `date_field=issue_date`. | -| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns invoices with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Allowed to be used only along with date_field set to created_at or updated_at. | -| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns invoices with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Allowed to be used only along with date_field set to created_at or updated_at. | -| `customerIds` | `[]int` | Query, Optional | Allows fetching invoices with matching customer id based on provided values. Use in query `customer_ids=1,2,3`. | -| `number` | `[]string` | Query, Optional | Allows fetching invoices with matching invoice number based on provided values. Use in query `number=1234,1235`. | -| `productIds` | `[]int` | Query, Optional | Allows fetching invoices with matching line items product ids based on provided values. Use in query `product_ids=23,34`. | -| `sort` | [`*models.InvoiceSortField`](../../doc/models/invoice-sort-field.md) | Query, Optional | Allows specification of the order of the returned list. Use in query `sort=total_amount`. | - -## Response Type - -[`models.ListInvoicesResponse`](../../doc/models/list-invoices-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns invoices with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns invoices with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `status` | [`*models.InvoiceStatus`](../../doc/models/invoice-status.md) | Query, Optional | The current status of the invoice. Allowed Values: draft, open, paid, pending, voided | +| `subscriptionId` | `*int` | Query, Optional | The subscription's ID. | +| `subscriptionGroupUid` | `*string` | Query, Optional | The UID of the subscription group you want to fetch consolidated invoices for. This will return a paginated list of consolidated invoices for the specified group. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned invoices. | +| `lineItems` | `*bool` | Query, Optional | Include line items data | +| `discounts` | `*bool` | Query, Optional | Include discounts data | +| `taxes` | `*bool` | Query, Optional | Include taxes data | +| `credits` | `*bool` | Query, Optional | Include credits data | +| `payments` | `*bool` | Query, Optional | Include payments data | +| `customFields` | `*bool` | Query, Optional | Include custom fields data | +| `refunds` | `*bool` | Query, Optional | Include refunds data | +| `dateField` | [`*models.InvoiceDateField`](../../doc/models/invoice-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query `date_field=issue_date`. | +| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns invoices with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Allowed to be used only along with date_field set to created_at or updated_at. | +| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns invoices with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Allowed to be used only along with date_field set to created_at or updated_at. | +| `customerIds` | `[]int` | Query, Optional | Allows fetching invoices with matching customer id based on provided values. Use in query `customer_ids=1,2,3`. | +| `number` | `[]string` | Query, Optional | Allows fetching invoices with matching invoice number based on provided values. Use in query `number=1234,1235`. | +| `productIds` | `[]int` | Query, Optional | Allows fetching invoices with matching line items product ids based on provided values. Use in query `product_ids=23,34`. | +| `sort` | [`*models.InvoiceSortField`](../../doc/models/invoice-sort-field.md) | Query, Optional | Allows specification of the order of the returned list. Use in query `sort=total_amount`. | + +## Response Type + +[`models.ListInvoicesResponse`](../../doc/models/list-invoices-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -direction := models.Direction("desc") -lineItems := false -discounts := false -taxes := false -credits := false -payments := false -customFields := false -refunds := false -dateField := models.InvoiceDateField("issue_date") -customerIds := []int{1, 2, 3} -number := []string{"1234", "1235"} -productIds := []int{23, 34} -sort := models.InvoiceSortField("total_amount") - -apiResponse, err := invoicesController.ListInvoices(ctx, nil, nil, nil, nil, nil, &page, &perPage, &direction, &lineItems, &discounts, &taxes, &credits, &payments, &customFields, &refunds, &dateField, nil, nil, customerIds, number, productIds, &sort) + +collectedInput := advancedbilling.ListInvoicesInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + Direction: models.ToPointer(models.Direction("desc")), + DateField: models.ToPointer(models.InvoiceDateField("issue_date")), + CustomerIds: []int{1, 2, 3}, + Number: []string{"1234", "1235"}, + ProductIds: []int{23, 34}, + Sort: models.ToPointer(models.InvoiceSortField("total_amount")), +} + +apiResponse, err := invoicesController.ListInvoices(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "invoices": [ - { - "uid": "inv_8htcd29wcq3q6", - "site_id": 51288, - "customer_id": 20153415, - "subscription_id": 23277588, - "number": "125", - "sequence_number": 125, - "issue_date": "2018-09-20", - "due_date": "2018-09-20", - "paid_date": "2018-09-20", - "status": "paid", - "collection_method": "automatic", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "parent", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": 23277588, - "product_name": "Trial and setup fee", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 20153415, - "first_name": "Meg", - "last_name": "Example", - "organization": "", - "email": "meg@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Boston", - "state": "MA", - "zip": "90210", - "country": "US" - }, - "shipping_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Boston", - "state": "MA", - "zip": "90210", - "country": "US" - }, - "subtotal_amount": "100.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "100.0", - "credit_amount": "0.0", - "paid_amount": "100.0", - "refund_amount": "0.0", - "due_amount": "0.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8htcd29wcq3q6?token=n9fr5fxff5v74c7h9srg3cwd" - }, - { - "uid": "inv_8hr3546xp4h8n", - "site_id": 51288, - "customer_id": 21687686, - "subscription_id": 22007644, - "number": "124", - "sequence_number": 124, - "issue_date": "2018-09-18", - "due_date": "2018-09-18", - "paid_date": null, - "status": "open", - "collection_method": "remittance", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "Trial and setup fee", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 21687686, - "first_name": "Charlene", - "last_name": "Tester", - "organization": "", - "email": "food@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": "", - "line2": "", - "city": "", - "state": "", - "zip": "", - "country": "" - }, - "shipping_address": { - "street": "", - "line2": "", - "city": "", - "state": "", - "zip": "", - "country": "" - }, - "subtotal_amount": "100.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "100.0", - "credit_amount": "0.0", - "paid_amount": "0.0", - "refund_amount": "0.0", - "due_amount": "100.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546xp4h8n?token=n9fr5fxff5v74c7h9srg3cwd" - }, - { - "uid": "inv_8hr3546wdwxkr", - "site_id": 51288, - "customer_id": 21687670, - "subscription_id": 22007627, - "number": "123", - "sequence_number": 123, - "issue_date": "2018-09-18", - "due_date": "2018-09-18", - "paid_date": "2018-09-18", - "status": "paid", - "collection_method": "automatic", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "Trial End - Free", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 21687670, - "first_name": "Hello", - "last_name": "World", - "organization": "123", - "email": "example@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": "123 Anywhere Street", - "line2": "", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "shipping_address": { - "street": "", - "line2": "", - "city": "Boston", - "state": "AL", - "zip": "02120", - "country": "US" - }, - "subtotal_amount": "0.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "0.0", - "credit_amount": "0.0", - "paid_amount": "0.0", - "refund_amount": "0.0", - "due_amount": "0.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546wdwxkr?token=n9fr5fxff5v74c7h9srg3cwd" - }, - { - "uid": "inv_8hjtk8bz56bbp", - "site_id": 51288, - "customer_id": 20137757, - "subscription_id": 20541100, - "number": "122", - "sequence_number": 122, - "issue_date": "2018-09-10", - "due_date": "2018-09-10", - "paid_date": "2018-09-10", - "status": "paid", - "collection_method": "automatic", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "$0 Product", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 20137757, - "first_name": "Sasha", - "last_name": "Example", - "organization": "", - "email": "example@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Catville", - "state": "MA", - "zip": "90210", - "country": "US" - }, - "shipping_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Catville", - "state": "AL", - "zip": "90210", - "country": "US" - }, - "subtotal_amount": "0.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "0.0", - "credit_amount": "0.0", - "paid_amount": "0.0", - "refund_amount": "0.0", - "due_amount": "0.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8hjtk8bz56bbp?token=fb6kpjz5rcr2vttyjs4rcv6y" - } - ] -} -``` - - -# Read Invoice - -Use this endpoint to retrieve the details for an invoice. - -```go -ReadInvoice( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "invoices": [ + { + "uid": "inv_8htcd29wcq3q6", + "site_id": 51288, + "customer_id": 20153415, + "subscription_id": 23277588, + "number": "125", + "sequence_number": 125, + "issue_date": "2018-09-20", + "due_date": "2018-09-20", + "paid_date": "2018-09-20", + "status": "paid", + "collection_method": "automatic", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "parent", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": 23277588, + "product_name": "Trial and setup fee", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 20153415, + "first_name": "Meg", + "last_name": "Example", + "organization": "", + "email": "meg@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Boston", + "state": "MA", + "zip": "90210", + "country": "US" + }, + "shipping_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Boston", + "state": "MA", + "zip": "90210", + "country": "US" + }, + "subtotal_amount": "100.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "100.0", + "credit_amount": "0.0", + "paid_amount": "100.0", + "refund_amount": "0.0", + "due_amount": "0.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8htcd29wcq3q6?token=n9fr5fxff5v74c7h9srg3cwd" + }, + { + "uid": "inv_8hr3546xp4h8n", + "site_id": 51288, + "customer_id": 21687686, + "subscription_id": 22007644, + "number": "124", + "sequence_number": 124, + "issue_date": "2018-09-18", + "due_date": "2018-09-18", + "paid_date": null, + "status": "open", + "collection_method": "remittance", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "Trial and setup fee", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 21687686, + "first_name": "Charlene", + "last_name": "Tester", + "organization": "", + "email": "food@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": "", + "line2": "", + "city": "", + "state": "", + "zip": "", + "country": "" + }, + "shipping_address": { + "street": "", + "line2": "", + "city": "", + "state": "", + "zip": "", + "country": "" + }, + "subtotal_amount": "100.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "100.0", + "credit_amount": "0.0", + "paid_amount": "0.0", + "refund_amount": "0.0", + "due_amount": "100.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546xp4h8n?token=n9fr5fxff5v74c7h9srg3cwd" + }, + { + "uid": "inv_8hr3546wdwxkr", + "site_id": 51288, + "customer_id": 21687670, + "subscription_id": 22007627, + "number": "123", + "sequence_number": 123, + "issue_date": "2018-09-18", + "due_date": "2018-09-18", + "paid_date": "2018-09-18", + "status": "paid", + "collection_method": "automatic", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "Trial End - Free", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 21687670, + "first_name": "Hello", + "last_name": "World", + "organization": "123", + "email": "example@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": "123 Anywhere Street", + "line2": "", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "shipping_address": { + "street": "", + "line2": "", + "city": "Boston", + "state": "AL", + "zip": "02120", + "country": "US" + }, + "subtotal_amount": "0.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "0.0", + "credit_amount": "0.0", + "paid_amount": "0.0", + "refund_amount": "0.0", + "due_amount": "0.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546wdwxkr?token=n9fr5fxff5v74c7h9srg3cwd" + }, + { + "uid": "inv_8hjtk8bz56bbp", + "site_id": 51288, + "customer_id": 20137757, + "subscription_id": 20541100, + "number": "122", + "sequence_number": 122, + "issue_date": "2018-09-10", + "due_date": "2018-09-10", + "paid_date": "2018-09-10", + "status": "paid", + "collection_method": "automatic", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "$0 Product", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 20137757, + "first_name": "Sasha", + "last_name": "Example", + "organization": "", + "email": "example@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Catville", + "state": "MA", + "zip": "90210", + "country": "US" + }, + "shipping_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Catville", + "state": "AL", + "zip": "90210", + "country": "US" + }, + "subtotal_amount": "0.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "0.0", + "credit_amount": "0.0", + "paid_amount": "0.0", + "refund_amount": "0.0", + "due_amount": "0.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8hjtk8bz56bbp?token=fb6kpjz5rcr2vttyjs4rcv6y" + } + ] +} +``` + + +# Read Invoice + +Use this endpoint to retrieve the details for an invoice. + +```go +ReadInvoice( + ctx context.Context, uid string) ( models.ApiResponse[models.Invoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | - -## Response Type - -[`models.Invoice`](../../doc/models/invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | + +## Response Type + +[`models.Invoice`](../../doc/models/invoice.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -474,125 +473,125 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "uid": "inv_8gd8tdhtd3hgr", - "site_id": 51288, - "customer_id": 20194505, - "subscription_id": 20597774, - "number": "117", - "sequence_number": 117, - "issue_date": "2018-07-26", - "due_date": "2018-07-26", - "paid_date": "2018-07-26", - "status": "paid", - "collection_method": "automatic", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "Monthly Product", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 20194505, - "first_name": "Joe", - "last_name": "Example", - "organization": null, - "email": "joe@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null - }, - "shipping_address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null - }, - "subtotal_amount": "100.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "100.0", - "credit_amount": "0.0", - "paid_amount": "100.0", - "refund_amount": "0.0", - "due_amount": "0.0", - "line_items": [ - { - "uid": "li_8gd8tdhhgk55k", - "title": "Monthly Product", - "description": "Jul 26, 2018 - Aug 26, 2018", - "quantity": "1.0", - "unit_price": "100.0", - "subtotal_amount": "100.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "100.0", - "tiered_unit_price": false, - "period_range_start": "2018-07-26", - "period_range_end": "2018-08-26", - "product_id": 4607632, - "product_version": 1, - "component_id": null, - "price_point_id": null - } - ], - "discounts": [], - "taxes": [], - "credits": [], - "payments": [ - { - "transaction_time": "2018-07-26T15:22:02Z", - "memo": "Joe Example - Monthly Product: Renewal payment", - "original_amount": "100.0", - "applied_amount": "100.0", - "payment_method": { - "card_brand": "bogus", - "card_expiration": "10/2020", - "last_four": null, - "masked_card_number": "XXXX-XXXX-XXXX-1", - "type": "credit_card" - }, - "transaction_id": 253028955, - "prepayment": false - } - ], - "refunds": [], - "custom_fields": [], - "public_url": "https://www.chargifypay.com/invoice/inv_8jzrw74xq8kxr?token=fb6kpjz5rcr2vttyjs4rcv6y" -} -``` - - -# List Invoice Events - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "uid": "inv_8gd8tdhtd3hgr", + "site_id": 51288, + "customer_id": 20194505, + "subscription_id": 20597774, + "number": "117", + "sequence_number": 117, + "issue_date": "2018-07-26", + "due_date": "2018-07-26", + "paid_date": "2018-07-26", + "status": "paid", + "collection_method": "automatic", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "Monthly Product", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 20194505, + "first_name": "Joe", + "last_name": "Example", + "organization": null, + "email": "joe@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "shipping_address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "subtotal_amount": "100.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "100.0", + "credit_amount": "0.0", + "paid_amount": "100.0", + "refund_amount": "0.0", + "due_amount": "0.0", + "line_items": [ + { + "uid": "li_8gd8tdhhgk55k", + "title": "Monthly Product", + "description": "Jul 26, 2018 - Aug 26, 2018", + "quantity": "1.0", + "unit_price": "100.0", + "subtotal_amount": "100.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "100.0", + "tiered_unit_price": false, + "period_range_start": "2018-07-26", + "period_range_end": "2018-08-26", + "product_id": 4607632, + "product_version": 1, + "component_id": null, + "price_point_id": null + } + ], + "discounts": [], + "taxes": [], + "credits": [], + "payments": [ + { + "transaction_time": "2018-07-26T15:22:02Z", + "memo": "Joe Example - Monthly Product: Renewal payment", + "original_amount": "100.0", + "applied_amount": "100.0", + "payment_method": { + "card_brand": "bogus", + "card_expiration": "10/2020", + "last_four": null, + "masked_card_number": "XXXX-XXXX-XXXX-1", + "type": "credit_card" + }, + "transaction_id": 253028955, + "prepayment": false + } + ], + "refunds": [], + "custom_fields": [], + "public_url": "https://www.chargifypay.com/invoice/inv_8jzrw74xq8kxr?token=fb6kpjz5rcr2vttyjs4rcv6y" +} +``` + + +# List Invoice Events + This endpoint returns a list of invoice events. Each event contains event "data" (such as an applied payment) as well as a snapshot of the `invoice` at the time of event completion. Exposed event types are: @@ -616,425 +615,429 @@ Invoice events are returned in ascending order. If both a `since_date` and `since_id` are provided in request parameters, the `since_date` will be used. -Note - invoice events that occurred prior to 09/05/2018 __will not__ contain an `invoice` snapshot. - -```go -ListInvoiceEvents( - ctx context.Context,input ListInvoiceEventsInput) ( +Note - invoice events that occurred prior to 09/05/2018 __will not__ contain an `invoice` snapshot. + +```go +ListInvoiceEvents( + ctx context.Context, + input ListInvoiceEventsInput) ( models.ApiResponse[models.ListInvoiceEventsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `sinceDate` | `*string` | Query, Optional | The timestamp in a format `YYYY-MM-DD T HH:MM:SS Z`, or `YYYY-MM-DD`(in this case, it returns data from the beginning of the day). of the event from which you want to start the search. All the events before the `since_date` timestamp are not returned in the response. | -| `sinceId` | `*int` | Query, Optional | The ID of the event from which you want to start the search(ID is not included. e.g. if ID is set to 2, then all events with ID 3 and more will be shown) This parameter is not used if since_date is defined. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. | -| `invoiceUid` | `*string` | Query, Optional | Providing an invoice_uid allows for scoping of the invoice events to a single invoice or credit note. | -| `withChangeInvoiceStatus` | `*string` | Query, Optional | Use this parameter if you want to fetch also invoice events with change_invoice_status type. | -| `eventTypes` | [`[]models.InvoiceEventType`](../../doc/models/invoice-event-type.md) | Query, Optional | Filter results by event_type. Supply a comma separated list of event types (listed above). Use in query: `event_types=void_invoice,void_remainder`. | - -## Response Type - -[`models.ListInvoiceEventsResponse`](../../doc/models/list-invoice-events-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `sinceDate` | `*string` | Query, Optional | The timestamp in a format `YYYY-MM-DD T HH:MM:SS Z`, or `YYYY-MM-DD`(in this case, it returns data from the beginning of the day). of the event from which you want to start the search. All the events before the `since_date` timestamp are not returned in the response. | +| `sinceId` | `*int` | Query, Optional | The ID of the event from which you want to start the search(ID is not included. e.g. if ID is set to 2, then all events with ID 3 and more will be shown) This parameter is not used if since_date is defined. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. | +| `invoiceUid` | `*string` | Query, Optional | Providing an invoice_uid allows for scoping of the invoice events to a single invoice or credit note. | +| `withChangeInvoiceStatus` | `*string` | Query, Optional | Use this parameter if you want to fetch also invoice events with change_invoice_status type. | +| `eventTypes` | [`[]models.InvoiceEventType`](../../doc/models/invoice-event-type.md) | Query, Optional | Filter results by event_type. Supply a comma separated list of event types (listed above). Use in query: `event_types=void_invoice,void_remainder`. | + +## Response Type + +[`models.ListInvoiceEventsResponse`](../../doc/models/list-invoice-events-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 100 -apiResponse, err := invoicesController.ListInvoiceEvents(ctx, nil, nil, &page, &perPage, nil, nil, nil) +collectedInput := advancedbilling.ListInvoiceEventsInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(100), +} + +apiResponse, err := invoicesController.ListInvoiceEvents(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "events": [ - { - "id": 83, - "event_type": "apply_payment", - "event_data": { - "memo": "Non-Resumable Canceled On Purpose - Standard Plan: Renewal payment", - "original_amount": "168.61", - "applied_amount": "168.61", - "transaction_time": "2018-08-01T16:00:00Z", - "payment_method": { - "card_brand": "visa", - "card_expiration": "12/2022", - "last_four": null, - "masked_card_number": "XXXX-XXXX-XXXX-1111", - "type": "credit_card" - }, - "consolidation_level": "none" - }, - "timestamp": "2018-08-01T16:00:00Z", - "invoice": { - "id": 614942008934401500, - "uid": "inv_8gk5bwkct3gqt", - "site_id": 20, - "customer_id": 6, - "subscription_id": 10, - "number": "25", - "sequence_number": 25, - "transaction_time": "2018-08-01T16:00:00Z", - "created_at": "2018-08-01T16:00:00Z", - "updated_at": "2018-08-01T16:00:00Z", - "issue_date": "2018-08-01", - "due_date": "2018-08-01", - "paid_date": "2018-08-01", - "status": "paid", - "role": "renewal", - "collection_method": "automatic", - "payment_instructions": "Please make checks payable to \"Acme, Inc.\"", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_id": null, - "subscription_group_id": null, - "parent_invoice_number": null, - "product_name": "Standard Plan", - "product_family_name": "Cloud Compute Servers", - "seller": { - "name": "Acme, Inc.", - "address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null - }, - "phone": "555-555-1234 x137", - "logo_url": null - }, - "customer": { - "chargify_id": 6, - "first_name": "Non-Resumable", - "last_name": "Canceled On Purpose", - "organization": null, - "email": "evan4@example.com" - }, - "payer": { - "chargify_id": 6, - "first_name": "Non-Resumable", - "last_name": "Canceled On Purpose", - "organization": null, - "email": "evan4@example.com" - }, - "recipient_emails": [], - "net_terms": 0, - "memo": "Thanks for your business! If you have any questions, please contact your account manager.", - "billing_address": { - "street": "200 Billing Rd.", - "line2": "Suite 100", - "city": "Needham", - "state": "MA", - "zip": "02494", - "country": "US" - }, - "shipping_address": { - "street": "100 Shipping St.", - "line2": "Apt 200", - "city": "Pleasantville", - "state": "NC", - "zip": "12345", - "country": "US" - }, - "line_items": [ - { - "uid": "li_8gk5bwkct3gqk", - "title": "Standard Plan", - "description": "08/01/2018 - 09/01/2018", - "quantity": "1.0", - "unit_price": "99.0", - "subtotal_amount": "99.0", - "discount_amount": "9.9", - "tax_amount": "6.01425", - "total_amount": "95.11425", - "tiered_unit_price": false, - "period_range_start": "2018-08-01", - "period_range_end": "2018-09-01", - "transaction_id": 120, - "product_id": 84, - "product_version": 1, - "component_id": null, - "price_point_id": null, - "hide": false - }, - { - "uid": "li_8gk5bwkct3gqm", - "title": "Small Instance (Hourly)", - "description": "07/22/2018 - 08/01/2018", - "quantity": "162.0", - "unit_price": "0.09567901", - "subtotal_amount": "15.5", - "discount_amount": "1.55", - "tax_amount": "0.941625", - "total_amount": "14.891625", - "tiered_unit_price": true, - "period_range_start": "2018-07-22", - "period_range_end": "2018-08-01", - "transaction_id": 121, - "product_id": 84, - "product_version": 1, - "component_id": 76, - "price_point_id": null, - "hide": false, - "component_cost_data": { - "rates": [ - { - "component_code_id": null, - "price_point_id": 160, - "product_id": 84, - "quantity": "162.0", - "amount": "15.5", - "pricing_scheme": "tiered", - "tiers": [ - { - "starting_quantity": 1, - "ending_quantity": 100, - "quantity": "100.0", - "unit_price": "0.0", - "amount": "0.0" - }, - { - "starting_quantity": 101, - "ending_quantity": null, - "quantity": "62.0", - "unit_price": "0.25", - "amount": "15.5" - } - ] - } - ] - } - }, - { - "uid": "li_8gk5bwkct3gqn", - "title": "Large Instance (Hourly)", - "description": "07/22/2018 - 08/01/2018", - "quantity": "194.0", - "unit_price": "0.24226804", - "subtotal_amount": "47.0", - "discount_amount": "4.7", - "tax_amount": "2.85525", - "total_amount": "45.15525", - "tiered_unit_price": true, - "period_range_start": "2018-07-22", - "period_range_end": "2018-08-01", - "transaction_id": 122, - "product_id": 84, - "product_version": 1, - "component_id": 77, - "price_point_id": null, - "hide": false, - "component_cost_data": { - "rates": [ - { - "component_code_id": null, - "price_point_id": 161, - "product_id": 84, - "quantity": "194.0", - "amount": "47.0", - "pricing_scheme": "tiered", - "tiers": [ - { - "starting_quantity": 1, - "ending_quantity": 100, - "quantity": "100.0", - "unit_price": "0.0", - "amount": "0.0" - }, - { - "starting_quantity": 101, - "ending_quantity": null, - "quantity": "94.0", - "unit_price": "0.5", - "amount": "47.0" - } - ] - } - ] - } - }, - { - "uid": "li_8gk5bwkct3gqp", - "title": "IP Addresses", - "description": "08/01/2018 - 09/01/2018", - "quantity": "7.0", - "unit_price": "2.0", - "subtotal_amount": "14.0", - "discount_amount": "1.4", - "tax_amount": "0.8505", - "total_amount": "13.4505", - "tiered_unit_price": false, - "period_range_start": "2018-08-01", - "period_range_end": "2018-09-01", - "transaction_id": 123, - "product_id": 84, - "product_version": 1, - "component_id": 79, - "price_point_id": 163, - "hide": false, - "component_cost_data": { - "rates": [ - { - "component_code_id": null, - "price_point_id": 163, - "product_id": 84, - "quantity": "7.0", - "amount": "14.0", - "pricing_scheme": "per_unit", - "tiers": [ - { - "starting_quantity": 1, - "ending_quantity": null, - "quantity": "7.0", - "unit_price": "2.0", - "amount": "14.0" - } - ] - } - ] - } - } - ], - "subtotal_amount": "175.5", - "discount_amount": "17.55", - "discounts": [ - { - "uid": "dli_8gk5bwkct3gqq", - "title": "Multi-service discount (10%)", - "description": null, - "code": "MULTI3", - "source_type": "Coupon", - "source_id": 40, - "discount_type": "percentage", - "percentage": "10.0", - "eligible_amount": "175.5", - "discount_amount": "17.55", - "transaction_id": 124, - "line_item_breakouts": [ - { - "uid": "li_8gk5bwkct3gqk", - "eligible_amount": "99.0", - "discount_amount": "9.9" - }, - { - "uid": "li_8gk5bwkct3gqm", - "eligible_amount": "15.5", - "discount_amount": "1.55" - }, - { - "uid": "li_8gk5bwkct3gqn", - "eligible_amount": "47.0", - "discount_amount": "4.7" - }, - { - "uid": "li_8gk5bwkct3gqp", - "eligible_amount": "14.0", - "discount_amount": "1.4" - } - ] - } - ], - "tax_amount": "10.66", - "taxes": [ - { - "uid": "tli_8gk5bwkct3gqr", - "title": "NC Sales Tax", - "description": null, - "source_type": "Tax", - "source_id": 1, - "percentage": "6.75", - "taxable_amount": "157.95", - "tax_amount": "10.66", - "transaction_id": 125, - "line_item_breakouts": [ - { - "uid": "li_8gk5bwkct3gqk", - "taxable_amount": "89.1", - "tax_amount": "6.01425" - }, - { - "uid": "li_8gk5bwkct3gqm", - "taxable_amount": "13.95", - "tax_amount": "0.941625" - }, - { - "uid": "li_8gk5bwkct3gqn", - "taxable_amount": "42.3", - "tax_amount": "2.85525" - }, - { - "uid": "li_8gk5bwkct3gqp", - "taxable_amount": "12.6", - "tax_amount": "0.8505" - } - ], - "tax_component_breakouts": [ - { - "tax_rule_id": 1, - "percentage": "6.75", - "country_code": "US", - "subdivision_code": "NC" - } - ] - } - ], - "credit_amount": "0.0", - "refund_amount": "0.0", - "total_amount": "168.61", - "paid_amount": "168.61", - "due_amount": "0.0", - "credits": [], - "refunds": [], - "payments": [ - { - "memo": "Non-Resumable Canceled On Purpose - Standard Plan: Renewal payment", - "original_amount": "168.61", - "applied_amount": "168.61", - "transaction_time": "2018-08-01T16:00:00Z", - "payment_method": { - "card_brand": "visa", - "card_expiration": "12/2022", - "last_four": null, - "masked_card_number": "XXXX-XXXX-XXXX-1111", - "type": "credit_card" - }, - "transaction_id": 126, - "prepayment": false - } - ], - "custom_fields": [], - "display_settings": { - "hide_zero_subtotal_lines": false, - "include_discounts_on_lines": false - } - } - } - ], - "page": 48, - "per_page": 1, - "total_pages": 102 -} -``` - - -# Record Payment for Invoice - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "events": [ + { + "id": 83, + "event_type": "apply_payment", + "event_data": { + "memo": "Non-Resumable Canceled On Purpose - Standard Plan: Renewal payment", + "original_amount": "168.61", + "applied_amount": "168.61", + "transaction_time": "2018-08-01T16:00:00Z", + "payment_method": { + "card_brand": "visa", + "card_expiration": "12/2022", + "last_four": null, + "masked_card_number": "XXXX-XXXX-XXXX-1111", + "type": "credit_card" + }, + "consolidation_level": "none" + }, + "timestamp": "2018-08-01T16:00:00Z", + "invoice": { + "id": 614942008934401500, + "uid": "inv_8gk5bwkct3gqt", + "site_id": 20, + "customer_id": 6, + "subscription_id": 10, + "number": "25", + "sequence_number": 25, + "transaction_time": "2018-08-01T16:00:00Z", + "created_at": "2018-08-01T16:00:00Z", + "updated_at": "2018-08-01T16:00:00Z", + "issue_date": "2018-08-01", + "due_date": "2018-08-01", + "paid_date": "2018-08-01", + "status": "paid", + "role": "renewal", + "collection_method": "automatic", + "payment_instructions": "Please make checks payable to \"Acme, Inc.\"", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_id": null, + "subscription_group_id": null, + "parent_invoice_number": null, + "product_name": "Standard Plan", + "product_family_name": "Cloud Compute Servers", + "seller": { + "name": "Acme, Inc.", + "address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "phone": "555-555-1234 x137", + "logo_url": null + }, + "customer": { + "chargify_id": 6, + "first_name": "Non-Resumable", + "last_name": "Canceled On Purpose", + "organization": null, + "email": "evan4@example.com" + }, + "payer": { + "chargify_id": 6, + "first_name": "Non-Resumable", + "last_name": "Canceled On Purpose", + "organization": null, + "email": "evan4@example.com" + }, + "recipient_emails": [], + "net_terms": 0, + "memo": "Thanks for your business! If you have any questions, please contact your account manager.", + "billing_address": { + "street": "200 Billing Rd.", + "line2": "Suite 100", + "city": "Needham", + "state": "MA", + "zip": "02494", + "country": "US" + }, + "shipping_address": { + "street": "100 Shipping St.", + "line2": "Apt 200", + "city": "Pleasantville", + "state": "NC", + "zip": "12345", + "country": "US" + }, + "line_items": [ + { + "uid": "li_8gk5bwkct3gqk", + "title": "Standard Plan", + "description": "08/01/2018 - 09/01/2018", + "quantity": "1.0", + "unit_price": "99.0", + "subtotal_amount": "99.0", + "discount_amount": "9.9", + "tax_amount": "6.01425", + "total_amount": "95.11425", + "tiered_unit_price": false, + "period_range_start": "2018-08-01", + "period_range_end": "2018-09-01", + "transaction_id": 120, + "product_id": 84, + "product_version": 1, + "component_id": null, + "price_point_id": null, + "hide": false + }, + { + "uid": "li_8gk5bwkct3gqm", + "title": "Small Instance (Hourly)", + "description": "07/22/2018 - 08/01/2018", + "quantity": "162.0", + "unit_price": "0.09567901", + "subtotal_amount": "15.5", + "discount_amount": "1.55", + "tax_amount": "0.941625", + "total_amount": "14.891625", + "tiered_unit_price": true, + "period_range_start": "2018-07-22", + "period_range_end": "2018-08-01", + "transaction_id": 121, + "product_id": 84, + "product_version": 1, + "component_id": 76, + "price_point_id": null, + "hide": false, + "component_cost_data": { + "rates": [ + { + "component_code_id": null, + "price_point_id": 160, + "product_id": 84, + "quantity": "162.0", + "amount": "15.5", + "pricing_scheme": "tiered", + "tiers": [ + { + "starting_quantity": 1, + "ending_quantity": 100, + "quantity": "100.0", + "unit_price": "0.0", + "amount": "0.0" + }, + { + "starting_quantity": 101, + "ending_quantity": null, + "quantity": "62.0", + "unit_price": "0.25", + "amount": "15.5" + } + ] + } + ] + } + }, + { + "uid": "li_8gk5bwkct3gqn", + "title": "Large Instance (Hourly)", + "description": "07/22/2018 - 08/01/2018", + "quantity": "194.0", + "unit_price": "0.24226804", + "subtotal_amount": "47.0", + "discount_amount": "4.7", + "tax_amount": "2.85525", + "total_amount": "45.15525", + "tiered_unit_price": true, + "period_range_start": "2018-07-22", + "period_range_end": "2018-08-01", + "transaction_id": 122, + "product_id": 84, + "product_version": 1, + "component_id": 77, + "price_point_id": null, + "hide": false, + "component_cost_data": { + "rates": [ + { + "component_code_id": null, + "price_point_id": 161, + "product_id": 84, + "quantity": "194.0", + "amount": "47.0", + "pricing_scheme": "tiered", + "tiers": [ + { + "starting_quantity": 1, + "ending_quantity": 100, + "quantity": "100.0", + "unit_price": "0.0", + "amount": "0.0" + }, + { + "starting_quantity": 101, + "ending_quantity": null, + "quantity": "94.0", + "unit_price": "0.5", + "amount": "47.0" + } + ] + } + ] + } + }, + { + "uid": "li_8gk5bwkct3gqp", + "title": "IP Addresses", + "description": "08/01/2018 - 09/01/2018", + "quantity": "7.0", + "unit_price": "2.0", + "subtotal_amount": "14.0", + "discount_amount": "1.4", + "tax_amount": "0.8505", + "total_amount": "13.4505", + "tiered_unit_price": false, + "period_range_start": "2018-08-01", + "period_range_end": "2018-09-01", + "transaction_id": 123, + "product_id": 84, + "product_version": 1, + "component_id": 79, + "price_point_id": 163, + "hide": false, + "component_cost_data": { + "rates": [ + { + "component_code_id": null, + "price_point_id": 163, + "product_id": 84, + "quantity": "7.0", + "amount": "14.0", + "pricing_scheme": "per_unit", + "tiers": [ + { + "starting_quantity": 1, + "ending_quantity": null, + "quantity": "7.0", + "unit_price": "2.0", + "amount": "14.0" + } + ] + } + ] + } + } + ], + "subtotal_amount": "175.5", + "discount_amount": "17.55", + "discounts": [ + { + "uid": "dli_8gk5bwkct3gqq", + "title": "Multi-service discount (10%)", + "description": null, + "code": "MULTI3", + "source_type": "Coupon", + "source_id": 40, + "discount_type": "percentage", + "percentage": "10.0", + "eligible_amount": "175.5", + "discount_amount": "17.55", + "transaction_id": 124, + "line_item_breakouts": [ + { + "uid": "li_8gk5bwkct3gqk", + "eligible_amount": "99.0", + "discount_amount": "9.9" + }, + { + "uid": "li_8gk5bwkct3gqm", + "eligible_amount": "15.5", + "discount_amount": "1.55" + }, + { + "uid": "li_8gk5bwkct3gqn", + "eligible_amount": "47.0", + "discount_amount": "4.7" + }, + { + "uid": "li_8gk5bwkct3gqp", + "eligible_amount": "14.0", + "discount_amount": "1.4" + } + ] + } + ], + "tax_amount": "10.66", + "taxes": [ + { + "uid": "tli_8gk5bwkct3gqr", + "title": "NC Sales Tax", + "description": null, + "source_type": "Tax", + "source_id": 1, + "percentage": "6.75", + "taxable_amount": "157.95", + "tax_amount": "10.66", + "transaction_id": 125, + "line_item_breakouts": [ + { + "uid": "li_8gk5bwkct3gqk", + "taxable_amount": "89.1", + "tax_amount": "6.01425" + }, + { + "uid": "li_8gk5bwkct3gqm", + "taxable_amount": "13.95", + "tax_amount": "0.941625" + }, + { + "uid": "li_8gk5bwkct3gqn", + "taxable_amount": "42.3", + "tax_amount": "2.85525" + }, + { + "uid": "li_8gk5bwkct3gqp", + "taxable_amount": "12.6", + "tax_amount": "0.8505" + } + ], + "tax_component_breakouts": [ + { + "tax_rule_id": 1, + "percentage": "6.75", + "country_code": "US", + "subdivision_code": "NC" + } + ] + } + ], + "credit_amount": "0.0", + "refund_amount": "0.0", + "total_amount": "168.61", + "paid_amount": "168.61", + "due_amount": "0.0", + "credits": [], + "refunds": [], + "payments": [ + { + "memo": "Non-Resumable Canceled On Purpose - Standard Plan: Renewal payment", + "original_amount": "168.61", + "applied_amount": "168.61", + "transaction_time": "2018-08-01T16:00:00Z", + "payment_method": { + "card_brand": "visa", + "card_expiration": "12/2022", + "last_four": null, + "masked_card_number": "XXXX-XXXX-XXXX-1111", + "type": "credit_card" + }, + "transaction_id": 126, + "prepayment": false + } + ], + "custom_fields": [], + "display_settings": { + "hide_zero_subtotal_lines": false, + "include_discounts_on_lines": false + } + } + } + ], + "page": 48, + "per_page": 1, + "total_pages": 102 +} +``` + + +# Record Payment for Invoice + This API call should be used when you want to record a payment of a given type against a specific invoice. If you would like to apply a payment across multiple invoices, you can use the Bulk Payment endpoint. ## Create a Payment from the existing payment profile @@ -1079,39 +1082,41 @@ In order to apply a service credit to an invoice, specify the `type` as `service } ``` -Note that Chargify will attempt to fully pay the invoice's `due_amount` from the Subscription's Service Credit account. At this time, partial payments from a Service Credit Account are only allowed for consolidated invoices (subscription groups). Therefore, for normal invoices the Service Credit account balance must be greater than or equal to the invoice's `due_amount`. - -```go -RecordPaymentForInvoice( - ctx context.Context, - uid string, +Note that Chargify will attempt to fully pay the invoice's `due_amount` from the Subscription's Service Credit account. At this time, partial payments from a Service Credit Account are only allowed for consolidated invoices (subscription groups). Therefore, for normal invoices the Service Credit account balance must be greater than or equal to the invoice's `due_amount`. + +```go +RecordPaymentForInvoice( + ctx context.Context, + uid string, body *models.CreateInvoicePaymentRequest) ( models.ApiResponse[models.Invoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | -| `body` | [`*models.CreateInvoicePaymentRequest`](../../doc/models/create-invoice-payment-request.md) | Body, Optional | - | - -## Response Type - -[`models.Invoice`](../../doc/models/invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | +| `body` | [`*models.CreateInvoicePaymentRequest`](../../doc/models/create-invoice-payment-request.md) | Body, Optional | - | + +## Response Type + +[`models.Invoice`](../../doc/models/invoice.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" +bodyPaymentAmount := models.CreateInvoicePaymentAmountContainer.FromPrecision(float64(124.33)) + bodyPayment := models.CreateInvoicePayment{ - Amount: models.ToPointer(interface{}("[key1, val1][key2, val2]")), Memo: models.ToPointer("for John Smith"), Method: models.ToPointer(models.InvoicePaymentMethodType("check")), Details: models.ToPointer("#0102"), + Amount: models.ToPointer(bodyPaymentAmount), } body := models.CreateInvoicePaymentRequest{ @@ -1125,18 +1130,18 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Record Payment for Multiple Invoices - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Record Payment for Multiple Invoices + This API call should be used when you want to record an external payment against multiple invoices. In order apply a payment to multiple invoices, at minimum, specify the `amount` and `applications` (i.e., `invoice_uid` and `amount`) details. @@ -1162,29 +1167,29 @@ In order apply a payment to multiple invoices, at minimum, specify the `amount` } ``` -Note that the invoice payment amounts must be greater than 0. Total amount must be greater or equal to invoices payment amount sum. - -```go -RecordPaymentForMultipleInvoices( - ctx context.Context, +Note that the invoice payment amounts must be greater than 0. Total amount must be greater or equal to invoices payment amount sum. + +```go +RecordPaymentForMultipleInvoices( + ctx context.Context, body *models.CreateMultiInvoicePaymentRequest) ( models.ApiResponse[models.MultiInvoicePaymentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.CreateMultiInvoicePaymentRequest`](../../doc/models/create-multi-invoice-payment-request.md) | Body, Optional | - | - -## Response Type - -[`models.MultiInvoicePaymentResponse`](../../doc/models/multi-invoice-payment-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.CreateMultiInvoicePaymentRequest`](../../doc/models/create-multi-invoice-payment-request.md) | Body, Optional | - | + +## Response Type + +[`models.MultiInvoicePaymentResponse`](../../doc/models/multi-invoice-payment-response.md) + +## Example Usage + +```go ctx := context.Background() bodyPaymentApplications0 := models.CreateInvoicePaymentApplication{ @@ -1198,12 +1203,14 @@ bodyPaymentApplications1 := models.CreateInvoicePaymentApplication{ } bodyPaymentApplications := []models.CreateInvoicePaymentApplication{bodyPaymentApplications0, bodyPaymentApplications1} +bodyPaymentAmount := models.CreateMultiInvoicePaymentAmountContainer.FromString("100.00") + bodyPayment := models.CreateMultiInvoicePayment{ Memo: models.ToPointer("to pay the bills"), Details: models.ToPointer("check number 8675309"), Method: models.ToPointer(models.InvoicePaymentMethodType("check")), - Amount: interface{}("[key1, val1][key2, val2]"), Applications: bodyPaymentApplications, + Amount: bodyPaymentAmount, } body := models.CreateMultiInvoicePaymentRequest{ @@ -1217,398 +1224,397 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "payment": { - "transaction_id": 1, - "total_amount": "100.00", - "currency_code": "USD", - "applications": [ - { - "invoice_uid": "inv_8gk5bwkct3gqt", - "application_uid": "pmt_1tr0hgsct3ybx", - "applied_amount": "50.00" - }, - { - "invoice_uid": "inv_7bc6bwkct3lyt", - "application_uid": "pmt_2", - "applied_amount": "50.00" - } - ] - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Credit Notes - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "payment": { + "transaction_id": 1, + "total_amount": "100.00", + "currency_code": "USD", + "applications": [ + { + "invoice_uid": "inv_8gk5bwkct3gqt", + "application_uid": "pmt_1tr0hgsct3ybx", + "applied_amount": "50.00" + }, + { + "invoice_uid": "inv_7bc6bwkct3lyt", + "application_uid": "pmt_2", + "applied_amount": "50.00" + } + ] + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Credit Notes + Credit Notes are like inverse invoices. They reduce the amount a customer owes. -By default, the credit notes returned by this endpoint will exclude the arrays of `line_items`, `discounts`, `taxes`, `applications`, or `refunds`. To include these arrays, pass the specific field as a key in the query with a value set to `true`. - -```go -ListCreditNotes( - ctx context.Context,input ListCreditNotesInput) ( +By default, the credit notes returned by this endpoint will exclude the arrays of `line_items`, `discounts`, `taxes`, `applications`, or `refunds`. To include these arrays, pass the specific field as a key in the query with a value set to `true`. + +```go +ListCreditNotes( + ctx context.Context, + input ListCreditNotesInput) ( models.ApiResponse[models.ListCreditNotesResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `*int` | Query, Optional | The subscription's Chargify id | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `lineItems` | `*bool` | Query, Optional | Include line items data | -| `discounts` | `*bool` | Query, Optional | Include discounts data | -| `taxes` | `*bool` | Query, Optional | Include taxes data | -| `refunds` | `*bool` | Query, Optional | Include refunds data | -| `applications` | `*bool` | Query, Optional | Include applications data | - -## Response Type - -[`models.ListCreditNotesResponse`](../../doc/models/list-credit-notes-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `*int` | Query, Optional | The subscription's Chargify id | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `lineItems` | `*bool` | Query, Optional | Include line items data | +| `discounts` | `*bool` | Query, Optional | Include discounts data | +| `taxes` | `*bool` | Query, Optional | Include taxes data | +| `refunds` | `*bool` | Query, Optional | Include refunds data | +| `applications` | `*bool` | Query, Optional | Include applications data | + +## Response Type + +[`models.ListCreditNotesResponse`](../../doc/models/list-credit-notes-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -lineItems := false -discounts := false -taxes := false -refunds := false -applications := false - -apiResponse, err := invoicesController.ListCreditNotes(ctx, nil, &page, &perPage, &lineItems, &discounts, &taxes, &refunds, &applications) + +collectedInput := advancedbilling.ListCreditNotesInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +} + +apiResponse, err := invoicesController.ListCreditNotes(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "credit_notes": [ - { - "uid": "cn_8m9vbd5kkv7kr", - "site_id": 20, - "customer_id": 3, - "subscription_id": 2, - "number": "77", - "sequence_number": 78, - "issue_date": "2018-12-31", - "applied_date": "2018-12-31", - "status": "applied", - "currency": "USD", - "memo": "Refund for overpayment", - "seller": { - "name": "Acme, Inc.", - "address": { - "street": "122 E Houston St", - "line2": "Suite 105", - "city": "San Antonio", - "state": "TX", - "zip": "78205", - "country": "US" - }, - "phone": "555-555-1234 x137" - }, - "customer": { - "chargify_id": 3, - "first_name": "Marty", - "last_name": "McFly", - "organization": "Time Travellers, Inc.", - "email": "timetraveller1985@example.com", - "reference": null - }, - "billing_address": { - "street": "200 Billing Rd.", - "line2": "Suite 100", - "city": "Needham", - "state": "MA", - "zip": "02494", - "country": "US" - }, - "shipping_address": { - "street": "100 Shipping St.", - "line2": "Apt 200", - "city": "Pleasantville", - "state": "NC", - "zip": "12345", - "country": "US" - }, - "subtotal_amount": "208.69341779", - "discount_amount": "20.87125167", - "tax_amount": "12.67783387", - "total_amount": "200.5", - "applied_amount": "200.5", - "remaining_amount": "0.0", - "line_items": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "title": "IP Addresses: 5 to 10 addresses", - "description": "38.2% credit", - "quantity": "0.9855", - "unit_price": "2.0", - "subtotal_amount": "1.971004", - "discount_amount": "0.19862831", - "tax_amount": "0.11963536", - "total_amount": "1.89201105", - "tiered_unit_price": false, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 81, - "price_point_id": 165 - }, - { - "uid": "cnli_8kjttvjcjx8b4", - "title": "Professional Plan", - "description": "38.2% credit", - "quantity": "0.382", - "unit_price": "299.0", - "subtotal_amount": "114.21127834", - "discount_amount": "11.42112783", - "tax_amount": "6.93833516", - "total_amount": "109.72848567", - "tiered_unit_price": false, - "period_range_start": "2018-12-30", - "period_range_end": "2018-12-30", - "product_id": 85, - "product_version": 1, - "component_id": null, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjknzhx7", - "title": "Small Instance (Hourly)", - "description": "38.2% credit", - "quantity": "74.8676", - "unit_price": "0.12244898", - "subtotal_amount": "9.16746047", - "discount_amount": "0.91674605", - "tax_amount": "0.55692322", - "total_amount": "8.80763764", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 78, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjnmh25w", - "title": "Large Instance (Hourly)", - "description": "38.2% credit", - "quantity": "183.3492", - "unit_price": "0.39583333", - "subtotal_amount": "72.57572871", - "discount_amount": "7.25757287", - "tax_amount": "4.40897552", - "total_amount": "69.72713136", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 79, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjqn86kc", - "title": "Email Messages", - "description": "38.2% credit", - "quantity": "10076.9489", - "unit_price": "0.00031045", - "subtotal_amount": "3.12839588", - "discount_amount": "0.31322157", - "tax_amount": "0.19002427", - "total_amount": "3.00519858", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 80, - "price_point_id": null - }, - { - "uid": "cnli_8kjttvjtxxbdd", - "title": "IP Addresses", - "description": "38.2% credit", - "quantity": "3.8198", - "unit_price": "2.0", - "subtotal_amount": "7.63955039", - "discount_amount": "0.76395504", - "tax_amount": "0.46410269", - "total_amount": "7.33969804", - "tiered_unit_price": false, - "period_range_start": "2018-12-30", - "period_range_end": "2018-12-30", - "product_id": 85, - "product_version": 1, - "component_id": 81, - "price_point_id": 165 - } - ], - "discounts": [ - { - "uid": "cndli_8k5jvdzct4h9y", - "title": "Multi-service discount (10%)", - "code": "MULTI3", - "source_type": "Coupon", - "source_id": 40, - "discount_type": "percentage", - "percentage": "10.0", - "eligible_amount": "208.69341779", - "discount_amount": "20.87125167", - "line_item_breakouts": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "eligible_amount": "1.971004", - "discount_amount": "0.19862831" - }, - { - "uid": "cnli_8kjttvjcjx8b4", - "eligible_amount": "114.21127834", - "discount_amount": "11.42112783" - }, - { - "uid": "cnli_8kjttvjknzhx7", - "eligible_amount": "9.16746047", - "discount_amount": "0.91674605" - }, - { - "uid": "cnli_8kjttvjnmh25w", - "eligible_amount": "72.57572871", - "discount_amount": "7.25757287" - }, - { - "uid": "cnli_8kjttvjqn86kc", - "eligible_amount": "3.12839588", - "discount_amount": "0.31322157" - }, - { - "uid": "cnli_8kjttvjtxxbdd", - "eligible_amount": "7.63955039", - "discount_amount": "0.76395504" - } - ] - } - ], - "taxes": [ - { - "uid": "cntli_8k5jvdzct4h9z", - "title": "NC Sales Tax", - "source_type": "Tax", - "source_id": 1, - "percentage": "6.75", - "taxable_amount": "187.82216613", - "tax_amount": "12.67783387", - "line_item_breakouts": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "taxable_amount": "1.77237569", - "tax_amount": "0.11963536" - }, - { - "uid": "cnli_8kjttvjcjx8b4", - "taxable_amount": "102.7901505", - "tax_amount": "6.93833516" - }, - { - "uid": "cnli_8kjttvjknzhx7", - "taxable_amount": "8.25071442", - "tax_amount": "0.55692322" - }, - { - "uid": "cnli_8kjttvjnmh25w", - "taxable_amount": "65.31815584", - "tax_amount": "4.40897552" - }, - { - "uid": "cnli_8kjttvjqn86kc", - "taxable_amount": "2.81517432", - "tax_amount": "0.19002427" - }, - { - "uid": "cnli_8kjttvjtxxbdd", - "taxable_amount": "6.87559535", - "tax_amount": "0.46410269" - } - ] - } - ], - "applications": [ - { - "uid": "cdt_8m9vbdbdwd28n", - "transaction_time": "2018-12-31T21:19:28Z", - "invoice_uid": "inv_8k5jvdzct4hb2", - "memo": "Refund for overpayment", - "applied_amount": "200.5" - } - ], - "refunds": [ - { - "transaction_id": 329, - "payment_id": 39, - "memo": "Refund for overpayment", - "original_amount": "524.9", - "applied_amount": "200.5" - } - ] - } - ] -} -``` - - -# Read Credit Note - -Use this endpoint to retrieve the details for a credit note. - -```go -ReadCreditNote( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "credit_notes": [ + { + "uid": "cn_8m9vbd5kkv7kr", + "site_id": 20, + "customer_id": 3, + "subscription_id": 2, + "number": "77", + "sequence_number": 78, + "issue_date": "2018-12-31", + "applied_date": "2018-12-31", + "status": "applied", + "currency": "USD", + "memo": "Refund for overpayment", + "seller": { + "name": "Acme, Inc.", + "address": { + "street": "122 E Houston St", + "line2": "Suite 105", + "city": "San Antonio", + "state": "TX", + "zip": "78205", + "country": "US" + }, + "phone": "555-555-1234 x137" + }, + "customer": { + "chargify_id": 3, + "first_name": "Marty", + "last_name": "McFly", + "organization": "Time Travellers, Inc.", + "email": "timetraveller1985@example.com", + "reference": null + }, + "billing_address": { + "street": "200 Billing Rd.", + "line2": "Suite 100", + "city": "Needham", + "state": "MA", + "zip": "02494", + "country": "US" + }, + "shipping_address": { + "street": "100 Shipping St.", + "line2": "Apt 200", + "city": "Pleasantville", + "state": "NC", + "zip": "12345", + "country": "US" + }, + "subtotal_amount": "208.69341779", + "discount_amount": "20.87125167", + "tax_amount": "12.67783387", + "total_amount": "200.5", + "applied_amount": "200.5", + "remaining_amount": "0.0", + "line_items": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "title": "IP Addresses: 5 to 10 addresses", + "description": "38.2% credit", + "quantity": "0.9855", + "unit_price": "2.0", + "subtotal_amount": "1.971004", + "discount_amount": "0.19862831", + "tax_amount": "0.11963536", + "total_amount": "1.89201105", + "tiered_unit_price": false, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 81, + "price_point_id": 165 + }, + { + "uid": "cnli_8kjttvjcjx8b4", + "title": "Professional Plan", + "description": "38.2% credit", + "quantity": "0.382", + "unit_price": "299.0", + "subtotal_amount": "114.21127834", + "discount_amount": "11.42112783", + "tax_amount": "6.93833516", + "total_amount": "109.72848567", + "tiered_unit_price": false, + "period_range_start": "2018-12-30", + "period_range_end": "2018-12-30", + "product_id": 85, + "product_version": 1, + "component_id": null, + "price_point_id": null + }, + { + "uid": "cnli_8kjttvjknzhx7", + "title": "Small Instance (Hourly)", + "description": "38.2% credit", + "quantity": "74.8676", + "unit_price": "0.12244898", + "subtotal_amount": "9.16746047", + "discount_amount": "0.91674605", + "tax_amount": "0.55692322", + "total_amount": "8.80763764", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 78, + "price_point_id": null + }, + { + "uid": "cnli_8kjttvjnmh25w", + "title": "Large Instance (Hourly)", + "description": "38.2% credit", + "quantity": "183.3492", + "unit_price": "0.39583333", + "subtotal_amount": "72.57572871", + "discount_amount": "7.25757287", + "tax_amount": "4.40897552", + "total_amount": "69.72713136", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 79, + "price_point_id": null + }, + { + "uid": "cnli_8kjttvjqn86kc", + "title": "Email Messages", + "description": "38.2% credit", + "quantity": "10076.9489", + "unit_price": "0.00031045", + "subtotal_amount": "3.12839588", + "discount_amount": "0.31322157", + "tax_amount": "0.19002427", + "total_amount": "3.00519858", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 80, + "price_point_id": null + }, + { + "uid": "cnli_8kjttvjtxxbdd", + "title": "IP Addresses", + "description": "38.2% credit", + "quantity": "3.8198", + "unit_price": "2.0", + "subtotal_amount": "7.63955039", + "discount_amount": "0.76395504", + "tax_amount": "0.46410269", + "total_amount": "7.33969804", + "tiered_unit_price": false, + "period_range_start": "2018-12-30", + "period_range_end": "2018-12-30", + "product_id": 85, + "product_version": 1, + "component_id": 81, + "price_point_id": 165 + } + ], + "discounts": [ + { + "uid": "cndli_8k5jvdzct4h9y", + "title": "Multi-service discount (10%)", + "code": "MULTI3", + "source_type": "Coupon", + "source_id": 40, + "discount_type": "percentage", + "percentage": "10.0", + "eligible_amount": "208.69341779", + "discount_amount": "20.87125167", + "line_item_breakouts": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "eligible_amount": "1.971004", + "discount_amount": "0.19862831" + }, + { + "uid": "cnli_8kjttvjcjx8b4", + "eligible_amount": "114.21127834", + "discount_amount": "11.42112783" + }, + { + "uid": "cnli_8kjttvjknzhx7", + "eligible_amount": "9.16746047", + "discount_amount": "0.91674605" + }, + { + "uid": "cnli_8kjttvjnmh25w", + "eligible_amount": "72.57572871", + "discount_amount": "7.25757287" + }, + { + "uid": "cnli_8kjttvjqn86kc", + "eligible_amount": "3.12839588", + "discount_amount": "0.31322157" + }, + { + "uid": "cnli_8kjttvjtxxbdd", + "eligible_amount": "7.63955039", + "discount_amount": "0.76395504" + } + ] + } + ], + "taxes": [ + { + "uid": "cntli_8k5jvdzct4h9z", + "title": "NC Sales Tax", + "source_type": "Tax", + "source_id": 1, + "percentage": "6.75", + "taxable_amount": "187.82216613", + "tax_amount": "12.67783387", + "line_item_breakouts": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "taxable_amount": "1.77237569", + "tax_amount": "0.11963536" + }, + { + "uid": "cnli_8kjttvjcjx8b4", + "taxable_amount": "102.7901505", + "tax_amount": "6.93833516" + }, + { + "uid": "cnli_8kjttvjknzhx7", + "taxable_amount": "8.25071442", + "tax_amount": "0.55692322" + }, + { + "uid": "cnli_8kjttvjnmh25w", + "taxable_amount": "65.31815584", + "tax_amount": "4.40897552" + }, + { + "uid": "cnli_8kjttvjqn86kc", + "taxable_amount": "2.81517432", + "tax_amount": "0.19002427" + }, + { + "uid": "cnli_8kjttvjtxxbdd", + "taxable_amount": "6.87559535", + "tax_amount": "0.46410269" + } + ] + } + ], + "applications": [ + { + "uid": "cdt_8m9vbdbdwd28n", + "transaction_time": "2018-12-31T21:19:28Z", + "invoice_uid": "inv_8k5jvdzct4hb2", + "memo": "Refund for overpayment", + "applied_amount": "200.5" + } + ], + "refunds": [ + { + "transaction_id": 329, + "payment_id": 39, + "memo": "Refund for overpayment", + "original_amount": "524.9", + "applied_amount": "200.5" + } + ] + } + ] +} +``` + + +# Read Credit Note + +Use this endpoint to retrieve the details for a credit note. + +```go +ReadCreditNote( + ctx context.Context, uid string) ( models.ApiResponse[models.CreditNote], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier of the credit note | - -## Response Type - -[`models.CreditNote`](../../doc/models/credit-note.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The unique identifier of the credit note | + +## Response Type + +[`models.CreditNote`](../../doc/models/credit-note.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -1619,331 +1625,331 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "uid": "cn_8m9vbd5kkv7kr", - "site_id": 20, - "customer_id": 3, - "subscription_id": 2, - "number": "77", - "sequence_number": 78, - "issue_date": "2018-12-31", - "applied_date": "2018-12-31", - "status": "applied", - "currency": "USD", - "memo": "Refund for overpayment", - "seller": { - "name": "Acme, Inc.", - "address": { - "street": "122 E Houston St", - "line2": "Suite 105", - "city": "San Antonio", - "state": "TX", - "zip": "78205", - "country": "US" - }, - "phone": "555-555-1234 x137" - }, - "customer": { - "chargify_id": 3, - "first_name": "Marty", - "last_name": "McFly", - "organization": "Time Travellers, Inc.", - "email": "timetraveller1985@example.com", - "reference": null - }, - "billing_address": { - "street": "200 Billing Rd.", - "line2": "Suite 100", - "city": "Needham", - "state": "MA", - "zip": "02494", - "country": "US" - }, - "shipping_address": { - "street": "100 Shipping St.", - "line2": "Apt 200", - "city": "Pleasantville", - "state": "NC", - "zip": "12345", - "country": "US" - }, - "subtotal_amount": "208.69341779", - "discount_amount": "20.87125167", - "tax_amount": "12.67783387", - "total_amount": "200.5", - "applied_amount": "200.5", - "remaining_amount": "0.0", - "line_items": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "title": "IP Addresses: 5 to 10 addresses", - "description": "38.2% credit", - "quantity": "0.9855", - "unit_price": "2.0", - "subtotal_amount": "1.971004", - "discount_amount": "0.19862831", - "tax_amount": "0.11963536", - "total_amount": "1.89201105", - "tiered_unit_price": false, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 81, - "price_point_id": 165, - "billing_schedule_item_id": null, - "custom_item": false - }, - { - "uid": "cnli_8kjttvjcjx8b4", - "title": "Professional Plan", - "description": "38.2% credit", - "quantity": "0.382", - "unit_price": "299.0", - "subtotal_amount": "114.21127834", - "discount_amount": "11.42112783", - "tax_amount": "6.93833516", - "total_amount": "109.72848567", - "tiered_unit_price": false, - "period_range_start": "2018-12-30", - "period_range_end": "2018-12-30", - "product_id": 85, - "product_version": 1, - "component_id": null, - "price_point_id": null, - "billing_schedule_item_id": null, - "custom_item": false - }, - { - "uid": "cnli_8kjttvjknzhx7", - "title": "Small Instance (Hourly)", - "description": "38.2% credit", - "quantity": "74.8676", - "unit_price": "0.12244898", - "subtotal_amount": "9.16746047", - "discount_amount": "0.91674605", - "tax_amount": "0.55692322", - "total_amount": "8.80763764", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 78, - "price_point_id": null, - "billing_schedule_item_id": null, - "custom_item": false - }, - { - "uid": "cnli_8kjttvjnmh25w", - "title": "Large Instance (Hourly)", - "description": "38.2% credit", - "quantity": "183.3492", - "unit_price": "0.39583333", - "subtotal_amount": "72.57572871", - "discount_amount": "7.25757287", - "tax_amount": "4.40897552", - "total_amount": "69.72713136", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 79, - "price_point_id": null, - "billing_schedule_item_id": null, - "custom_item": false - }, - { - "uid": "cnli_8kjttvjqn86kc", - "title": "Email Messages", - "description": "38.2% credit", - "quantity": "10076.9489", - "unit_price": "0.00031045", - "subtotal_amount": "3.12839588", - "discount_amount": "0.31322157", - "tax_amount": "0.19002427", - "total_amount": "3.00519858", - "tiered_unit_price": true, - "period_range_start": "2018-11-30", - "period_range_end": "2018-11-30", - "product_id": 85, - "product_version": 1, - "component_id": 80, - "price_point_id": null, - "billing_schedule_item_id": null, - "custom_item": false - }, - { - "uid": "cnli_8kjttvjtxxbdd", - "title": "IP Addresses", - "description": "38.2% credit", - "quantity": "3.8198", - "unit_price": "2.0", - "subtotal_amount": "7.63955039", - "discount_amount": "0.76395504", - "tax_amount": "0.46410269", - "total_amount": "7.33969804", - "tiered_unit_price": false, - "period_range_start": "2018-12-30", - "period_range_end": "2018-12-30", - "product_id": 85, - "product_version": 1, - "component_id": 81, - "price_point_id": 165, - "billing_schedule_item_id": null, - "custom_item": false - } - ], - "discounts": [ - { - "uid": "cndli_8k5jvdzct4h9y", - "title": "Multi-service discount (10%)", - "code": "MULTI3", - "source_type": "Coupon", - "source_id": 40, - "discount_type": "percentage", - "percentage": "10.0", - "eligible_amount": "208.69341779", - "discount_amount": "20.87125167", - "line_item_breakouts": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "eligible_amount": "1.971004", - "discount_amount": "0.19862831" - }, - { - "uid": "cnli_8kjttvjcjx8b4", - "eligible_amount": "114.21127834", - "discount_amount": "11.42112783" - }, - { - "uid": "cnli_8kjttvjknzhx7", - "eligible_amount": "9.16746047", - "discount_amount": "0.91674605" - }, - { - "uid": "cnli_8kjttvjnmh25w", - "eligible_amount": "72.57572871", - "discount_amount": "7.25757287" - }, - { - "uid": "cnli_8kjttvjqn86kc", - "eligible_amount": "3.12839588", - "discount_amount": "0.31322157" - }, - { - "uid": "cnli_8kjttvjtxxbdd", - "eligible_amount": "7.63955039", - "discount_amount": "0.76395504" - } - ] - } - ], - "taxes": [ - { - "uid": "cntli_8k5jvdzct4h9z", - "title": "NC Sales Tax", - "source_type": "Tax", - "source_id": 1, - "percentage": "6.75", - "taxable_amount": "187.82216613", - "tax_amount": "12.67783387", - "line_item_breakouts": [ - { - "uid": "cnli_8k5jvdzct4h9x", - "taxable_amount": "1.77237569", - "tax_amount": "0.11963536" - }, - { - "uid": "cnli_8kjttvjcjx8b4", - "taxable_amount": "102.7901505", - "tax_amount": "6.93833516" - }, - { - "uid": "cnli_8kjttvjknzhx7", - "taxable_amount": "8.25071442", - "tax_amount": "0.55692322" - }, - { - "uid": "cnli_8kjttvjnmh25w", - "taxable_amount": "65.31815584", - "tax_amount": "4.40897552" - }, - { - "uid": "cnli_8kjttvjqn86kc", - "taxable_amount": "2.81517432", - "tax_amount": "0.19002427" - }, - { - "uid": "cnli_8kjttvjtxxbdd", - "taxable_amount": "6.87559535", - "tax_amount": "0.46410269" - } - ] - } - ], - "applications": [ - { - "uid": "cdt_8m9vbdbdwd28n", - "transaction_time": "2018-12-31T21:19:28Z", - "invoice_uid": "inv_8k5jvdzct4hb2", - "memo": "Refund for overpayment", - "applied_amount": "200.5" - } - ], - "refunds": [ - { - "transaction_id": 329, - "payment_id": 39, - "memo": "Refund for overpayment", - "original_amount": "524.9", - "applied_amount": "200.5" - } - ] -} -``` - - -# Record Payment for Subscription - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "uid": "cn_8m9vbd5kkv7kr", + "site_id": 20, + "customer_id": 3, + "subscription_id": 2, + "number": "77", + "sequence_number": 78, + "issue_date": "2018-12-31", + "applied_date": "2018-12-31", + "status": "applied", + "currency": "USD", + "memo": "Refund for overpayment", + "seller": { + "name": "Acme, Inc.", + "address": { + "street": "122 E Houston St", + "line2": "Suite 105", + "city": "San Antonio", + "state": "TX", + "zip": "78205", + "country": "US" + }, + "phone": "555-555-1234 x137" + }, + "customer": { + "chargify_id": 3, + "first_name": "Marty", + "last_name": "McFly", + "organization": "Time Travellers, Inc.", + "email": "timetraveller1985@example.com", + "reference": null + }, + "billing_address": { + "street": "200 Billing Rd.", + "line2": "Suite 100", + "city": "Needham", + "state": "MA", + "zip": "02494", + "country": "US" + }, + "shipping_address": { + "street": "100 Shipping St.", + "line2": "Apt 200", + "city": "Pleasantville", + "state": "NC", + "zip": "12345", + "country": "US" + }, + "subtotal_amount": "208.69341779", + "discount_amount": "20.87125167", + "tax_amount": "12.67783387", + "total_amount": "200.5", + "applied_amount": "200.5", + "remaining_amount": "0.0", + "line_items": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "title": "IP Addresses: 5 to 10 addresses", + "description": "38.2% credit", + "quantity": "0.9855", + "unit_price": "2.0", + "subtotal_amount": "1.971004", + "discount_amount": "0.19862831", + "tax_amount": "0.11963536", + "total_amount": "1.89201105", + "tiered_unit_price": false, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 81, + "price_point_id": 165, + "billing_schedule_item_id": null, + "custom_item": false + }, + { + "uid": "cnli_8kjttvjcjx8b4", + "title": "Professional Plan", + "description": "38.2% credit", + "quantity": "0.382", + "unit_price": "299.0", + "subtotal_amount": "114.21127834", + "discount_amount": "11.42112783", + "tax_amount": "6.93833516", + "total_amount": "109.72848567", + "tiered_unit_price": false, + "period_range_start": "2018-12-30", + "period_range_end": "2018-12-30", + "product_id": 85, + "product_version": 1, + "component_id": null, + "price_point_id": null, + "billing_schedule_item_id": null, + "custom_item": false + }, + { + "uid": "cnli_8kjttvjknzhx7", + "title": "Small Instance (Hourly)", + "description": "38.2% credit", + "quantity": "74.8676", + "unit_price": "0.12244898", + "subtotal_amount": "9.16746047", + "discount_amount": "0.91674605", + "tax_amount": "0.55692322", + "total_amount": "8.80763764", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 78, + "price_point_id": null, + "billing_schedule_item_id": null, + "custom_item": false + }, + { + "uid": "cnli_8kjttvjnmh25w", + "title": "Large Instance (Hourly)", + "description": "38.2% credit", + "quantity": "183.3492", + "unit_price": "0.39583333", + "subtotal_amount": "72.57572871", + "discount_amount": "7.25757287", + "tax_amount": "4.40897552", + "total_amount": "69.72713136", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 79, + "price_point_id": null, + "billing_schedule_item_id": null, + "custom_item": false + }, + { + "uid": "cnli_8kjttvjqn86kc", + "title": "Email Messages", + "description": "38.2% credit", + "quantity": "10076.9489", + "unit_price": "0.00031045", + "subtotal_amount": "3.12839588", + "discount_amount": "0.31322157", + "tax_amount": "0.19002427", + "total_amount": "3.00519858", + "tiered_unit_price": true, + "period_range_start": "2018-11-30", + "period_range_end": "2018-11-30", + "product_id": 85, + "product_version": 1, + "component_id": 80, + "price_point_id": null, + "billing_schedule_item_id": null, + "custom_item": false + }, + { + "uid": "cnli_8kjttvjtxxbdd", + "title": "IP Addresses", + "description": "38.2% credit", + "quantity": "3.8198", + "unit_price": "2.0", + "subtotal_amount": "7.63955039", + "discount_amount": "0.76395504", + "tax_amount": "0.46410269", + "total_amount": "7.33969804", + "tiered_unit_price": false, + "period_range_start": "2018-12-30", + "period_range_end": "2018-12-30", + "product_id": 85, + "product_version": 1, + "component_id": 81, + "price_point_id": 165, + "billing_schedule_item_id": null, + "custom_item": false + } + ], + "discounts": [ + { + "uid": "cndli_8k5jvdzct4h9y", + "title": "Multi-service discount (10%)", + "code": "MULTI3", + "source_type": "Coupon", + "source_id": 40, + "discount_type": "percentage", + "percentage": "10.0", + "eligible_amount": "208.69341779", + "discount_amount": "20.87125167", + "line_item_breakouts": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "eligible_amount": "1.971004", + "discount_amount": "0.19862831" + }, + { + "uid": "cnli_8kjttvjcjx8b4", + "eligible_amount": "114.21127834", + "discount_amount": "11.42112783" + }, + { + "uid": "cnli_8kjttvjknzhx7", + "eligible_amount": "9.16746047", + "discount_amount": "0.91674605" + }, + { + "uid": "cnli_8kjttvjnmh25w", + "eligible_amount": "72.57572871", + "discount_amount": "7.25757287" + }, + { + "uid": "cnli_8kjttvjqn86kc", + "eligible_amount": "3.12839588", + "discount_amount": "0.31322157" + }, + { + "uid": "cnli_8kjttvjtxxbdd", + "eligible_amount": "7.63955039", + "discount_amount": "0.76395504" + } + ] + } + ], + "taxes": [ + { + "uid": "cntli_8k5jvdzct4h9z", + "title": "NC Sales Tax", + "source_type": "Tax", + "source_id": 1, + "percentage": "6.75", + "taxable_amount": "187.82216613", + "tax_amount": "12.67783387", + "line_item_breakouts": [ + { + "uid": "cnli_8k5jvdzct4h9x", + "taxable_amount": "1.77237569", + "tax_amount": "0.11963536" + }, + { + "uid": "cnli_8kjttvjcjx8b4", + "taxable_amount": "102.7901505", + "tax_amount": "6.93833516" + }, + { + "uid": "cnli_8kjttvjknzhx7", + "taxable_amount": "8.25071442", + "tax_amount": "0.55692322" + }, + { + "uid": "cnli_8kjttvjnmh25w", + "taxable_amount": "65.31815584", + "tax_amount": "4.40897552" + }, + { + "uid": "cnli_8kjttvjqn86kc", + "taxable_amount": "2.81517432", + "tax_amount": "0.19002427" + }, + { + "uid": "cnli_8kjttvjtxxbdd", + "taxable_amount": "6.87559535", + "tax_amount": "0.46410269" + } + ] + } + ], + "applications": [ + { + "uid": "cdt_8m9vbdbdwd28n", + "transaction_time": "2018-12-31T21:19:28Z", + "invoice_uid": "inv_8k5jvdzct4hb2", + "memo": "Refund for overpayment", + "applied_amount": "200.5" + } + ], + "refunds": [ + { + "transaction_id": 329, + "payment_id": 39, + "memo": "Refund for overpayment", + "original_amount": "524.9", + "applied_amount": "200.5" + } + ] +} +``` + + +# Record Payment for Subscription + Record an external payment made against a subscription that will pay partially or in full one or more invoices. Payment will be applied starting with the oldest open invoice and then next oldest, and so on until the amount of the payment is fully consumed. Excess payment will result in the creation of a prepayment on the Invoice Account. -Only ungrouped or primary subscriptions may be paid using the "bulk" payment request. - -```go -RecordPaymentForSubscription( - ctx context.Context, - subscriptionId int, +Only ungrouped or primary subscriptions may be paid using the "bulk" payment request. + +```go +RecordPaymentForSubscription( + ctx context.Context, + subscriptionId int, body *models.RecordPaymentRequest) ( models.ApiResponse[models.RecordPaymentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.RecordPaymentRequest`](../../doc/models/record-payment-request.md) | Body, Optional | - | - -## Response Type - -[`models.RecordPaymentResponse`](../../doc/models/record-payment-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.RecordPaymentRequest`](../../doc/models/record-payment-request.md) | Body, Optional | - | + +## Response Type + +[`models.RecordPaymentResponse`](../../doc/models/record-payment-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -1965,40 +1971,40 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "paid_invoices": [ - { - "invoice_id": "inv_bchyhr6z5grby", - "status": "paid", - "due_amount": "0.0", - "paid_amount": "50.0" - }, - { - "invoice_id": "inv_bchyhrgvyb6vm", - "status": "paid", - "due_amount": "0.0", - "paid_amount": "50.0" - } - ], - "prepayment": null -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Reopen Invoice - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "paid_invoices": [ + { + "invoice_id": "inv_bchyhr6z5grby", + "status": "paid", + "due_amount": "0.0", + "paid_amount": "50.0" + }, + { + "invoice_id": "inv_bchyhrgvyb6vm", + "status": "paid", + "due_amount": "0.0", + "paid_amount": "50.0" + } + ], + "prepayment": null +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Reopen Invoice + This endpoint allows you to reopen any invoice with the "canceled" status. Invoices enter "canceled" status if they were open at the time the subscription was canceled (whether through dunning or an intentional cancellation). Invoices with "canceled" status are no longer considered to be due. Once reopened, they are considered due for payment. Payment may then be captured in one of the following ways: @@ -2010,29 +2016,29 @@ A note about reactivations: any canceled invoices from the most recent active pe ### Reopening Consolidated Invoices -When reopening a consolidated invoice, all of its canceled segments will also be reopened. - -```go -ReopenInvoice( - ctx context.Context, +When reopening a consolidated invoice, all of its canceled segments will also be reopened. + +```go +ReopenInvoice( + ctx context.Context, uid string) ( models.ApiResponse[models.Invoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | - -## Response Type - -[`models.Invoice`](../../doc/models/invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | + +## Response Type + +[`models.Invoice`](../../doc/models/invoice.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -2043,44 +2049,44 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Void Invoice - -This endpoint allows you to void any invoice with the "open" or "canceled" status. It will also allow voiding of an invoice with the "pending" status if it is not a consolidated invoice. - -```go -VoidInvoice( - ctx context.Context, - uid string, +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Void Invoice + +This endpoint allows you to void any invoice with the "open" or "canceled" status. It will also allow voiding of an invoice with the "pending" status if it is not a consolidated invoice. + +```go +VoidInvoice( + ctx context.Context, + uid string, body *models.VoidInvoiceRequest) ( models.ApiResponse[models.Invoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | -| `body` | [`*models.VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | - -## Response Type - -[`models.Invoice`](../../doc/models/invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | +| `body` | [`*models.VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | + +## Response Type + +[`models.Invoice`](../../doc/models/invoice.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -2099,336 +2105,340 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Consolidated Invoice Segments - -Invoice segments returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, or `custom_fields`. - -```go -ListConsolidatedInvoiceSegments( - ctx context.Context,input ListConsolidatedInvoiceSegmentsInput) ( +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Consolidated Invoice Segments + +Invoice segments returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, or `custom_fields`. + +```go +ListConsolidatedInvoiceSegments( + ctx context.Context, + input ListConsolidatedInvoiceSegmentsInput) ( models.ApiResponse[models.ConsolidatedInvoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `invoiceUid` | `string` | Template, Required | The unique identifier of the consolidated invoice | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | Sort direction of the returned segments. | - -## Response Type - -[`models.ConsolidatedInvoice`](../../doc/models/consolidated-invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `invoiceUid` | `string` | Template, Required | The unique identifier of the consolidated invoice | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | Sort direction of the returned segments. | + +## Response Type + +[`models.ConsolidatedInvoice`](../../doc/models/consolidated-invoice.md) + +## Example Usage + +```go ctx := context.Background() -invoiceUid := "invoice_uid0" -page := 2 -perPage := 50 -direction := models.Direction("asc") -apiResponse, err := invoicesController.ListConsolidatedInvoiceSegments(ctx, invoiceUid, &page, &perPage, &direction) +collectedInput := advancedbilling.ListConsolidatedInvoiceSegmentsInput{ + InvoiceUid: "invoice_uid0", + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + Direction: models.ToPointer(models.Direction("asc")), +} + +apiResponse, err := invoicesController.ListConsolidatedInvoiceSegments(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "invoices": [ - { - "uid": "inv_8htcd29wcq3q6", - "site_id": 51288, - "customer_id": 20153415, - "subscription_id": 23277588, - "number": "125", - "sequence_number": 125, - "issue_date": "2018-09-20", - "due_date": "2018-09-20", - "paid_date": "2018-09-20", - "status": "paid", - "collection_method": "automatic", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "parent", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": 23277588, - "product_name": "Trial and setup fee", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 20153415, - "first_name": "Meg", - "last_name": "Example", - "organization": "", - "email": "meg@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Boston", - "state": "MA", - "zip": "90210", - "country": "US" - }, - "shipping_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Boston", - "state": "MA", - "zip": "90210", - "country": "US" - }, - "subtotal_amount": "100.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "100.0", - "credit_amount": "0.0", - "paid_amount": "100.0", - "refund_amount": "0.0", - "due_amount": "0.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8htcd29wcq3q6?token=fb6kpjz5rcr2vttyjs4rcv6y" - }, - { - "uid": "inv_8hr3546xp4h8n", - "site_id": 51288, - "customer_id": 21687686, - "subscription_id": 22007644, - "number": "124", - "sequence_number": 124, - "issue_date": "2018-09-18", - "due_date": "2018-09-18", - "paid_date": null, - "status": "open", - "collection_method": "remittance", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "Trial and setup fee", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 21687686, - "first_name": "Charlene", - "last_name": "Tester", - "organization": "", - "email": "food@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": "", - "line2": "", - "city": "", - "state": "", - "zip": "", - "country": "" - }, - "shipping_address": { - "street": "", - "line2": "", - "city": "", - "state": "", - "zip": "", - "country": "" - }, - "subtotal_amount": "100.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "100.0", - "credit_amount": "0.0", - "paid_amount": "0.0", - "refund_amount": "0.0", - "due_amount": "100.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546xp4h8n?token=fb6kpjz5rcr2vttyjs4rcv6y" - }, - { - "uid": "inv_8hr3546wdwxkr", - "site_id": 51288, - "customer_id": 21687670, - "subscription_id": 22007627, - "number": "123", - "sequence_number": 123, - "issue_date": "2018-09-18", - "due_date": "2018-09-18", - "paid_date": "2018-09-18", - "status": "paid", - "collection_method": "automatic", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "Trial End - Free", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 21687670, - "first_name": "Hello", - "last_name": "World", - "organization": "123", - "email": "example@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": "123 Anywhere Street", - "line2": "", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "shipping_address": { - "street": "", - "line2": "", - "city": "Boston", - "state": "AL", - "zip": "02120", - "country": "US" - }, - "subtotal_amount": "0.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "0.0", - "credit_amount": "0.0", - "paid_amount": "0.0", - "refund_amount": "0.0", - "due_amount": "0.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546wdwxkr?token=fb6kpjz5rcr2vttyjs4rcv6y" - }, - { - "uid": "inv_8hjtk8bz56bbp", - "site_id": 51288, - "customer_id": 20137757, - "subscription_id": 20541100, - "number": "122", - "sequence_number": 122, - "issue_date": "2018-09-10", - "due_date": "2018-09-10", - "paid_date": "2018-09-10", - "status": "paid", - "collection_method": "automatic", - "payment_instructions": "Make checks payable to Acme, Inc.", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "$0 Product", - "product_family_name": "Billing Plans", - "seller": { - "name": "General Goods", - "address": { - "street": "123 General Goods Way", - "line2": "Apt. 10", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US" - }, - "phone": "555-555-1212" - }, - "customer": { - "chargify_id": 20137757, - "first_name": "Sasha", - "last_name": "Example", - "organization": "", - "email": "example@example.com" - }, - "memo": "Please pay within 15 days.", - "billing_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Catville", - "state": "MA", - "zip": "90210", - "country": "US" - }, - "shipping_address": { - "street": "123 I Love Cats Way", - "line2": "", - "city": "Catville", - "state": "AL", - "zip": "90210", - "country": "US" - }, - "subtotal_amount": "0.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "0.0", - "credit_amount": "0.0", - "paid_amount": "0.0", - "refund_amount": "0.0", - "due_amount": "0.0", - "public_url": "https://www.chargifypay.com/invoice/inv_8jzrw74xq8kxr?token=fb6kpjz5rcr2vttyjs4rcv6y" - } - ] -} -``` - - -# Create Invoice - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "invoices": [ + { + "uid": "inv_8htcd29wcq3q6", + "site_id": 51288, + "customer_id": 20153415, + "subscription_id": 23277588, + "number": "125", + "sequence_number": 125, + "issue_date": "2018-09-20", + "due_date": "2018-09-20", + "paid_date": "2018-09-20", + "status": "paid", + "collection_method": "automatic", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "parent", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": 23277588, + "product_name": "Trial and setup fee", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 20153415, + "first_name": "Meg", + "last_name": "Example", + "organization": "", + "email": "meg@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Boston", + "state": "MA", + "zip": "90210", + "country": "US" + }, + "shipping_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Boston", + "state": "MA", + "zip": "90210", + "country": "US" + }, + "subtotal_amount": "100.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "100.0", + "credit_amount": "0.0", + "paid_amount": "100.0", + "refund_amount": "0.0", + "due_amount": "0.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8htcd29wcq3q6?token=fb6kpjz5rcr2vttyjs4rcv6y" + }, + { + "uid": "inv_8hr3546xp4h8n", + "site_id": 51288, + "customer_id": 21687686, + "subscription_id": 22007644, + "number": "124", + "sequence_number": 124, + "issue_date": "2018-09-18", + "due_date": "2018-09-18", + "paid_date": null, + "status": "open", + "collection_method": "remittance", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "Trial and setup fee", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 21687686, + "first_name": "Charlene", + "last_name": "Tester", + "organization": "", + "email": "food@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": "", + "line2": "", + "city": "", + "state": "", + "zip": "", + "country": "" + }, + "shipping_address": { + "street": "", + "line2": "", + "city": "", + "state": "", + "zip": "", + "country": "" + }, + "subtotal_amount": "100.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "100.0", + "credit_amount": "0.0", + "paid_amount": "0.0", + "refund_amount": "0.0", + "due_amount": "100.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546xp4h8n?token=fb6kpjz5rcr2vttyjs4rcv6y" + }, + { + "uid": "inv_8hr3546wdwxkr", + "site_id": 51288, + "customer_id": 21687670, + "subscription_id": 22007627, + "number": "123", + "sequence_number": 123, + "issue_date": "2018-09-18", + "due_date": "2018-09-18", + "paid_date": "2018-09-18", + "status": "paid", + "collection_method": "automatic", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "Trial End - Free", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 21687670, + "first_name": "Hello", + "last_name": "World", + "organization": "123", + "email": "example@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": "123 Anywhere Street", + "line2": "", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "shipping_address": { + "street": "", + "line2": "", + "city": "Boston", + "state": "AL", + "zip": "02120", + "country": "US" + }, + "subtotal_amount": "0.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "0.0", + "credit_amount": "0.0", + "paid_amount": "0.0", + "refund_amount": "0.0", + "due_amount": "0.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8hr3546wdwxkr?token=fb6kpjz5rcr2vttyjs4rcv6y" + }, + { + "uid": "inv_8hjtk8bz56bbp", + "site_id": 51288, + "customer_id": 20137757, + "subscription_id": 20541100, + "number": "122", + "sequence_number": 122, + "issue_date": "2018-09-10", + "due_date": "2018-09-10", + "paid_date": "2018-09-10", + "status": "paid", + "collection_method": "automatic", + "payment_instructions": "Make checks payable to Acme, Inc.", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "$0 Product", + "product_family_name": "Billing Plans", + "seller": { + "name": "General Goods", + "address": { + "street": "123 General Goods Way", + "line2": "Apt. 10", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US" + }, + "phone": "555-555-1212" + }, + "customer": { + "chargify_id": 20137757, + "first_name": "Sasha", + "last_name": "Example", + "organization": "", + "email": "example@example.com" + }, + "memo": "Please pay within 15 days.", + "billing_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Catville", + "state": "MA", + "zip": "90210", + "country": "US" + }, + "shipping_address": { + "street": "123 I Love Cats Way", + "line2": "", + "city": "Catville", + "state": "AL", + "zip": "90210", + "country": "US" + }, + "subtotal_amount": "0.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "0.0", + "credit_amount": "0.0", + "paid_amount": "0.0", + "refund_amount": "0.0", + "due_amount": "0.0", + "public_url": "https://www.chargifypay.com/invoice/inv_8jzrw74xq8kxr?token=fb6kpjz5rcr2vttyjs4rcv6y" + } + ] +} +``` + + +# Create Invoice + This endpoint will allow you to create an ad hoc invoice. ### Basic Behavior @@ -2595,38 +2605,42 @@ A custom memo can be sent with the `memo` parameter to override the site's defau #### Status -By default, invoices will be created with open status. Possible alternative is `draft`. - -```go -CreateInvoice( - ctx context.Context, - subscriptionId int, +By default, invoices will be created with open status. Possible alternative is `draft`. + +```go +CreateInvoice( + ctx context.Context, + subscriptionId int, body *models.CreateInvoiceRequest) ( models.ApiResponse[models.InvoiceResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.CreateInvoiceRequest`](../../doc/models/create-invoice-request.md) | Body, Optional | - | - -## Response Type - -[`models.InvoiceResponse`](../../doc/models/invoice-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.CreateInvoiceRequest`](../../doc/models/create-invoice-request.md) | Body, Optional | - | + +## Response Type + +[`models.InvoiceResponse`](../../doc/models/invoice-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 +bodyInvoiceLineItems0Quantity := models.CreateInvoiceItemQuantityContainer.FromPrecision(float64(12)) + +bodyInvoiceLineItems0UnitPrice := models.CreateInvoiceItemUnitPriceContainer.FromString("150.00") + bodyInvoiceLineItems0 := models.CreateInvoiceItem{ Title: models.ToPointer("A Product"), - Quantity: models.ToPointer(interface{}("[key1, val1][key2, val2]")), - UnitPrice: models.ToPointer(interface{}("[key1, val1][key2, val2]")), + Quantity: models.ToPointer(bodyInvoiceLineItems0Quantity), + UnitPrice: models.ToPointer(bodyInvoiceLineItems0UnitPrice), } bodyInvoiceLineItems := []models.CreateInvoiceItem{bodyInvoiceLineItems0} @@ -2645,150 +2659,150 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "invoice": { - "uid": "inv_98nbmb93gxjz8", - "site_id": 5, - "customer_id": 13, - "subscription_id": 17, - "number": "1", - "sequence_number": 1, - "issue_date": "2020-12-02", - "due_date": "2020-12-02", - "paid_date": null, - "status": "open", - "collection_method": "remittance", - "payment_instructions": "", - "currency": "USD", - "consolidation_level": "none", - "parent_invoice_uid": null, - "parent_invoice_number": null, - "group_primary_subscription_id": null, - "product_name": "Digitized discrete initiative", - "product_family_name": "Networked bottom-line orchestration", - "role": "adhoc", - "seller": { - "name": "Steuber, West and Hegmann 1", - "address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null - }, - "phone": "(766) 316-0492" - }, - "customer": { - "chargify_id": 13, - "first_name": "Dean", - "last_name": "Adams", - "organization": null, - "email": "brandi1@example.com", - "vat_number": null, - "reference": null - }, - "memo": "", - "billing_address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null - }, - "shipping_address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null - }, - "subtotal_amount": "1800.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "1800.0", - "credit_amount": "0.0", - "paid_amount": "0.0", - "refund_amount": "0.0", - "due_amount": "1800.0", - "line_items": [ - { - "uid": "li_98nbmb9jgz84c", - "title": "Some product", - "description": "12/02/2020 - 12/02/2020", - "quantity": "12.0", - "unit_price": "150.0", - "subtotal_amount": "1800.0", - "discount_amount": "0.0", - "tax_amount": "0.0", - "total_amount": "1800.0", - "tiered_unit_price": false, - "period_range_start": "2020-12-02", - "period_range_end": "2020-12-02", - "product_id": null, - "product_version": null, - "product_price_point_id": null, - "component_id": null, - "price_point_id": null - } - ], - "discounts": [], - "taxes": [], - "credits": [], - "payments": [], - "refunds": [], - "custom_fields": [], - "public_url": "https://www.test-chargifypay.com/invoice/inv_98nbmb93gxjz8?token=rmfmwvbdy4xmyw5f29j5gc6x" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | - - -# Send Invoice - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "invoice": { + "uid": "inv_98nbmb93gxjz8", + "site_id": 5, + "customer_id": 13, + "subscription_id": 17, + "number": "1", + "sequence_number": 1, + "issue_date": "2020-12-02", + "due_date": "2020-12-02", + "paid_date": null, + "status": "open", + "collection_method": "remittance", + "payment_instructions": "", + "currency": "USD", + "consolidation_level": "none", + "parent_invoice_uid": null, + "parent_invoice_number": null, + "group_primary_subscription_id": null, + "product_name": "Digitized discrete initiative", + "product_family_name": "Networked bottom-line orchestration", + "role": "adhoc", + "seller": { + "name": "Steuber, West and Hegmann 1", + "address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "phone": "(766) 316-0492" + }, + "customer": { + "chargify_id": 13, + "first_name": "Dean", + "last_name": "Adams", + "organization": null, + "email": "brandi1@example.com", + "vat_number": null, + "reference": null + }, + "memo": "", + "billing_address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "shipping_address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null + }, + "subtotal_amount": "1800.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "1800.0", + "credit_amount": "0.0", + "paid_amount": "0.0", + "refund_amount": "0.0", + "due_amount": "1800.0", + "line_items": [ + { + "uid": "li_98nbmb9jgz84c", + "title": "Some product", + "description": "12/02/2020 - 12/02/2020", + "quantity": "12.0", + "unit_price": "150.0", + "subtotal_amount": "1800.0", + "discount_amount": "0.0", + "tax_amount": "0.0", + "total_amount": "1800.0", + "tiered_unit_price": false, + "period_range_start": "2020-12-02", + "period_range_end": "2020-12-02", + "product_id": null, + "product_version": null, + "product_price_point_id": null, + "component_id": null, + "price_point_id": null + } + ], + "discounts": [], + "taxes": [], + "credits": [], + "payments": [], + "refunds": [], + "custom_fields": [], + "public_url": "https://www.test-chargifypay.com/invoice/inv_98nbmb93gxjz8?token=rmfmwvbdy4xmyw5f29j5gc6x" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + + +# Send Invoice + This endpoint allows for invoices to be programmatically delivered via email. This endpoint supports the delivery of both ad-hoc and automatically generated invoices. Additionally, this endpoint supports email delivery to direct recipients, carbon-copy (cc) recipients, and blind carbon-copy (bcc) recipients. Please note that if no recipient email addresses are specified in the request, then the subscription's default email configuration will be used. For example, if `recipient_emails` is left blank, then the invoice will be delivered to the subscription's customer email address. -On success, a 204 no-content response will be returned. Please note that this does not indicate that email(s) have been delivered, but instead indicates that emails have been successfully queued for delivery. If _any_ invalid or malformed email address is found in the request body, the entire request will be rejected and a 422 response will be returned. - -```go -SendInvoice( - ctx context.Context, - uid string, +On success, a 204 no-content response will be returned. Please note that this does not indicate that email(s) have been delivered, but instead indicates that emails have been successfully queued for delivery. If _any_ invalid or malformed email address is found in the request body, the entire request will be rejected and a 422 response will be returned. + +```go +SendInvoice( + ctx context.Context, + uid string, body *models.SendInvoiceRequest) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | -| `body` | [`*models.SendInvoiceRequest`](../../doc/models/send-invoice-request.md) | Body, Optional | - | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | +| `body` | [`*models.SendInvoiceRequest`](../../doc/models/send-invoice-request.md) | Body, Optional | - | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -2803,43 +2817,43 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Preview Customer Information Changes - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Preview Customer Information Changes + Customer information may change after an invoice is issued which may lead to a mismatch between customer information that are present on an open invoice and actual customer information. This endpoint allows to preview these differences, if any. -The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. - -```go -PreviewCustomerInformationChanges( - ctx context.Context, +The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. + +```go +PreviewCustomerInformationChanges( + ctx context.Context, uid string) ( models.ApiResponse[models.CustomerChangesPreviewResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | - -## Response Type - -[`models.CustomerChangesPreviewResponse`](../../doc/models/customer-changes-preview-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | + +## Response Type + +[`models.CustomerChangesPreviewResponse`](../../doc/models/customer-changes-preview-response.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -2850,97 +2864,97 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "changes": { - "payer": { - "before": { - "last_name": "Beatty" - }, - "after": { - "last_name": "Doe" - } - }, - "shipping_address": { - "before": { - "line2": "Suite 703" - }, - "after": { - "line2": "Suite 702" - } - }, - "billing_address": { - "before": { - "line2": "Suite 703" - }, - "after": { - "line2": "Suite 702" - } - }, - "custom_fields": { - "before": [ - { - "owner_id": 1002, - "owner_type": "Customer", - "name": "Color", - "value": "blue", - "metadatum_id": 20 - } - ], - "after": [ - { - "owner_id": 1002, - "owner_type": "Customer", - "name": "Color", - "value": "green", - "metadatum_id": 20 - } - ] - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Update Customer Information - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "changes": { + "payer": { + "before": { + "last_name": "Beatty" + }, + "after": { + "last_name": "Doe" + } + }, + "shipping_address": { + "before": { + "line2": "Suite 703" + }, + "after": { + "line2": "Suite 702" + } + }, + "billing_address": { + "before": { + "line2": "Suite 703" + }, + "after": { + "line2": "Suite 702" + } + }, + "custom_fields": { + "before": [ + { + "owner_id": 1002, + "owner_type": "Customer", + "name": "Color", + "value": "blue", + "metadatum_id": 20 + } + ], + "after": [ + { + "owner_id": 1002, + "owner_type": "Customer", + "name": "Color", + "value": "green", + "metadatum_id": 20 + } + ] + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Update Customer Information + This endpoint updates customer information on an open invoice and returns the updated invoice. If you would like to preview changes that will be applied, use the `/invoices/{uid}/customer_information/preview.json` endpoint before. -The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. - -```go -UpdateCustomerInformation( - ctx context.Context, +The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. + +```go +UpdateCustomerInformation( + ctx context.Context, uid string) ( models.ApiResponse[models.Invoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | - -## Response Type - -[`models.Invoice`](../../doc/models/invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | + +## Response Type + +[`models.Invoice`](../../doc/models/invoice.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -2951,206 +2965,206 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "uid": "elit Ut", - "site_id": 46283786, - "customer_id": -62349460, - "subscription_id": 12801726, - "number": "dolore et ut", - "sequence_number": -84210096, - "issue_date": "2017-01-01", - "due_date": "2017-01-30", - "paid_date": "2017-01-28", - "status": "open", - "collection_method": "automatic", - "payment_instructions": "enim officia", - "currency": "dolore", - "consolidation_level": "none", - "product_name": "occaecat veniam culpa", - "product_family_name": "qui commodo ea dolore cillum", - "seller": { - "name": "co", - "phone": "ullamco in officia" - }, - "customer": { - "chargify_id": -55826334, - "first_name": "deserunt", - "last_name": "velit dolore", - "email": "aliquip sed velit Lorem" - }, - "memo": "ea cupidatat deserunt", - "billing_address": { - "street": "qui commodo cupidatat sunt", - "line2": "ut officia enim", - "city": "velit minim dolore sint nulla", - "state": "velit", - "zip": "ullamco", - "country": "irure est laborum deserun" - }, - "shipping_address": { - "street": "do fugiat dolore deserunt officia", - "line2": "ipsum cillum", - "city": "aliqua laboris incididunt ut", - "state": "et fugiat sit", - "zip": "dolore do", - "country": "Excepteur consequat cillum" - }, - "subtotal_amount": "dolore mollit", - "discount_amount": "aute", - "tax_amount": "eu aliqua est velit ea", - "total_amount": "ut non", - "credit_amount": "sit", - "refund_amount": "et eiusmod qui sed", - "paid_amount": "amet nulla s", - "due_amount": "non esse ullamco", - "line_items": [ - { - "description": "qui", - "price_point_id": 123, - "tax_amount": "occaecat deserunt veniam", - "subtotal_amount": "commodo consequat tempor et Duis" - }, - { - "uid": "", - "subtotal_amount": "ven" - }, - { - "price_point_id": 94750853, - "product_id": 79058036, - "tax_amount": "1.0", - "subtotal_amount": "128.5" - }, - { - "unit_price": "eiusmod consequat ut nostrud", - "tax_amount": "quis nulla proident" - }, - { - "period_range_end": "2022-02-02", - "product_id": 57352537, - "description": "minim in dolore Ut Excepteur", - "uid": "sit qui in ullamco anim" - } - ], - "discounts": [ - { - "title": "nostrud" - } - ], - "taxes": [ - { - "source_type": "Tax", - "line_item_breakouts": [ - { - "uid": "in ipsum", - "tax_amount": "velit", - "taxable_amount": "quis sint" - }, - { - "uid": "co" - } - ] - }, - { - "uid": "enim irure in", - "title": "incididunt est mollit irure" - } - ], - "credits": [ - { - "uid": "exercitation eiusmod", - "transaction_time": "2024-01-23T13:51:27Z", - "credit_note_number": "qui fugiat labore laborum", - "credit_note_uid": "ipsum sunt" - }, - { - "memo": "dolor" - } - ], - "refunds": [ - { - "memo": "deserunt elit" - }, - { - "original_amount": "Duis nulla" - } - ], - "payments": [ - { - "prepayment": false, - "memo": "enim Excepteur Lorem magna sit" - }, - { - "transaction_time": "2024-01-23T13:51:27Z", - "prepayment": false, - "payment_method": { - "details": "labore ut et", - "kind": "dolor qui", - "memo": "ea commodo", - "type": "fugiat veniam", - "card_brand": "consequat", - "card_expiration": "aliqua a", - "last_four": "ut in consectetur sed", - "masked_card_number": "minim ea ullamco nostrud tempor" - } - }, - { - "prepayment": true, - "transaction_id": 67527234 - }, - { - "original_amount": "c", - "memo": "dolore fugiat labore" - } - ], - "custom_fields": [ - { - "name": "CustomerStatus", - "value": "Gold", - "owner_type": "Customer", - "owner_id": 18482224, - "metadatum_id": 13924 - }, - { - "name": "SubscriptionTag", - "value": "Special Subscriber", - "owner_type": "Subscription", - "owner_id": 21344, - "metadatum_id": 139245 - } - ], - "public_url": "dolo", - "previous_balance_data": { - "captured_at": "2024-01-09T11:22:23-05:00", - "invoices": [ - { - "number": "veniam dolore labore ipsum cupidatat", - "uid": "tempor", - "outstanding_amount": "Excepteur nostrud irur" - }, - { - "outstanding_amount": "id" - } - ] - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Issue Invoice - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "uid": "elit Ut", + "site_id": 46283786, + "customer_id": -62349460, + "subscription_id": 12801726, + "number": "dolore et ut", + "sequence_number": -84210096, + "issue_date": "2017-01-01", + "due_date": "2017-01-30", + "paid_date": "2017-01-28", + "status": "open", + "collection_method": "automatic", + "payment_instructions": "enim officia", + "currency": "dolore", + "consolidation_level": "none", + "product_name": "occaecat veniam culpa", + "product_family_name": "qui commodo ea dolore cillum", + "seller": { + "name": "co", + "phone": "ullamco in officia" + }, + "customer": { + "chargify_id": -55826334, + "first_name": "deserunt", + "last_name": "velit dolore", + "email": "aliquip sed velit Lorem" + }, + "memo": "ea cupidatat deserunt", + "billing_address": { + "street": "qui commodo cupidatat sunt", + "line2": "ut officia enim", + "city": "velit minim dolore sint nulla", + "state": "velit", + "zip": "ullamco", + "country": "irure est laborum deserun" + }, + "shipping_address": { + "street": "do fugiat dolore deserunt officia", + "line2": "ipsum cillum", + "city": "aliqua laboris incididunt ut", + "state": "et fugiat sit", + "zip": "dolore do", + "country": "Excepteur consequat cillum" + }, + "subtotal_amount": "dolore mollit", + "discount_amount": "aute", + "tax_amount": "eu aliqua est velit ea", + "total_amount": "ut non", + "credit_amount": "sit", + "refund_amount": "et eiusmod qui sed", + "paid_amount": "amet nulla s", + "due_amount": "non esse ullamco", + "line_items": [ + { + "description": "qui", + "price_point_id": 123, + "tax_amount": "occaecat deserunt veniam", + "subtotal_amount": "commodo consequat tempor et Duis" + }, + { + "uid": "", + "subtotal_amount": "ven" + }, + { + "price_point_id": 94750853, + "product_id": 79058036, + "tax_amount": "1.0", + "subtotal_amount": "128.5" + }, + { + "unit_price": "eiusmod consequat ut nostrud", + "tax_amount": "quis nulla proident" + }, + { + "period_range_end": "2022-02-02", + "product_id": 57352537, + "description": "minim in dolore Ut Excepteur", + "uid": "sit qui in ullamco anim" + } + ], + "discounts": [ + { + "title": "nostrud" + } + ], + "taxes": [ + { + "source_type": "Tax", + "line_item_breakouts": [ + { + "uid": "in ipsum", + "tax_amount": "velit", + "taxable_amount": "quis sint" + }, + { + "uid": "co" + } + ] + }, + { + "uid": "enim irure in", + "title": "incididunt est mollit irure" + } + ], + "credits": [ + { + "uid": "exercitation eiusmod", + "transaction_time": "2024-01-23T13:51:27Z", + "credit_note_number": "qui fugiat labore laborum", + "credit_note_uid": "ipsum sunt" + }, + { + "memo": "dolor" + } + ], + "refunds": [ + { + "memo": "deserunt elit" + }, + { + "original_amount": "Duis nulla" + } + ], + "payments": [ + { + "prepayment": false, + "memo": "enim Excepteur Lorem magna sit" + }, + { + "transaction_time": "2024-01-23T13:51:27Z", + "prepayment": false, + "payment_method": { + "details": "labore ut et", + "kind": "dolor qui", + "memo": "ea commodo", + "type": "fugiat veniam", + "card_brand": "consequat", + "card_expiration": "aliqua a", + "last_four": "ut in consectetur sed", + "masked_card_number": "minim ea ullamco nostrud tempor" + } + }, + { + "prepayment": true, + "transaction_id": 67527234 + }, + { + "original_amount": "c", + "memo": "dolore fugiat labore" + } + ], + "custom_fields": [ + { + "name": "CustomerStatus", + "value": "Gold", + "owner_type": "Customer", + "owner_id": 18482224, + "metadatum_id": 13924 + }, + { + "name": "SubscriptionTag", + "value": "Special Subscriber", + "owner_type": "Subscription", + "owner_id": 21344, + "metadatum_id": 139245 + } + ], + "public_url": "dolo", + "previous_balance_data": { + "captured_at": "2024-01-09T11:22:23-05:00", + "invoices": [ + { + "number": "veniam dolore labore ipsum cupidatat", + "uid": "tempor", + "outstanding_amount": "Excepteur nostrud irur" + }, + { + "outstanding_amount": "id" + } + ] + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Issue Invoice + This endpoint allows you to issue an invoice that is in "pending" status. For example, you can issue an invoice that was created when allocating new quantity on a component and using "accrue charges" option. You cannot issue a pending child invoice that was created for a member subscription in a group. @@ -3161,31 +3175,31 @@ For Automatic subscriptions, prepayments and service credits will apply to the i - `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. - `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. -- `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). - -```go -IssueInvoice( - ctx context.Context, - uid string, +- `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). + +```go +IssueInvoice( + ctx context.Context, + uid string, body *models.IssueInvoiceRequest) ( models.ApiResponse[models.Invoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | -| `body` | [`*models.IssueInvoiceRequest`](../../doc/models/issue-invoice-request.md) | Body, Optional | - | - -## Response Type - -[`models.Invoice`](../../doc/models/invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The unique identifier for the invoice, this does not refer to the public facing invoice number. | +| `body` | [`*models.IssueInvoiceRequest`](../../doc/models/issue-invoice-request.md) | Body, Optional | - | + +## Response Type + +[`models.Invoice`](../../doc/models/invoice.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -3200,13 +3214,13 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/controllers/offers.md b/doc/controllers/offers.md index 695b335f..70bce1e1 100644 --- a/doc/controllers/offers.md +++ b/doc/controllers/offers.md @@ -1,24 +1,24 @@ -# Offers - -```go -offersController := client.OffersController() -``` - -## Class Name - -`OffersController` - -## Methods - +# Offers + +```go +offersController := client.OffersController() +``` + +## Class Name + +`OffersController` + +## Methods + * [Create Offer](../../doc/controllers/offers.md#create-offer) * [List Offers](../../doc/controllers/offers.md#list-offers) * [Read Offer](../../doc/controllers/offers.md#read-offer) * [Archive Offer](../../doc/controllers/offers.md#archive-offer) -* [Unarchive Offer](../../doc/controllers/offers.md#unarchive-offer) - - -# Create Offer - +* [Unarchive Offer](../../doc/controllers/offers.md#unarchive-offer) + + +# Create Offer + Create an offer within your Chargify site by sending a POST request. ## Documentation @@ -31,29 +31,29 @@ Full documentation on how to use offers in the Chargify UI can be located [here] ## Using a Product Price Point -You can optionally pass in a `product_price_point_id` that corresponds with the `product_id` and the offer will use that price point. If a `product_price_point_id` is not passed in, the product's default price point will be used. - -```go -CreateOffer( - ctx context.Context, +You can optionally pass in a `product_price_point_id` that corresponds with the `product_id` and the offer will use that price point. If a `product_price_point_id` is not passed in, the product's default price point will be used. + +```go +CreateOffer( + ctx context.Context, body *models.CreateOfferRequest) ( models.ApiResponse[models.OfferResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.CreateOfferRequest`](../../doc/models/create-offer-request.md) | Body, Optional | - | - -## Response Type - -[`models.OfferResponse`](../../doc/models/offer-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.CreateOfferRequest`](../../doc/models/create-offer-request.md) | Body, Optional | - | + +## Response Type + +[`models.OfferResponse`](../../doc/models/offer-response.md) + +## Example Usage + +```go ctx := context.Background() bodyOfferComponents0 := models.CreateOfferComponent{ @@ -83,181 +83,185 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "offer": { - "id": 3, - "site_id": 2, - "product_family_id": 4, - "product_family_name": "Chargify", - "product_id": 31, - "product_name": "30-Day Square Trial", - "product_price_in_cents": 2000, - "product_revisable_number": 0, - "name": "Solo", - "handle": "han_shot_first", - "description": "A Star Wars Story", - "created_at": "2018-06-08T14:51:52-04:00", - "updated_at": "2018-06-08T14:51:52-04:00", - "archived_at": null, - "product_price_point_name": "Default", - "offer_items": [ - { - "component_id": 24, - "component_name": "Invoices", - "component_unit_price": "3.0", - "price_point_id": 104, - "price_point_name": "Original", - "starting_quantity": "1.0", - "editable": false - } - ], - "offer_discounts": [ - { - "coupon_id": 3, - "coupon_code": "DEF456", - "coupon_name": "IB Loyalty" - } - ] - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | - - -# List Offers - -This endpoint will list offers for a site. - -```go -ListOffers( - ctx context.Context,input ListOffersInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "offer": { + "id": 3, + "site_id": 2, + "product_family_id": 4, + "product_family_name": "Chargify", + "product_id": 31, + "product_name": "30-Day Square Trial", + "product_price_in_cents": 2000, + "product_revisable_number": 0, + "name": "Solo", + "handle": "han_shot_first", + "description": "A Star Wars Story", + "created_at": "2018-06-08T14:51:52-04:00", + "updated_at": "2018-06-08T14:51:52-04:00", + "archived_at": null, + "product_price_point_name": "Default", + "offer_items": [ + { + "component_id": 24, + "component_name": "Invoices", + "component_unit_price": "3.0", + "price_point_id": 104, + "price_point_name": "Original", + "starting_quantity": "1.0", + "editable": false + } + ], + "offer_discounts": [ + { + "coupon_id": 3, + "coupon_code": "DEF456", + "coupon_name": "IB Loyalty" + } + ] + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + + +# List Offers + +This endpoint will list offers for a site. + +```go +ListOffers( + ctx context.Context, + input ListOffersInput) ( models.ApiResponse[models.ListOffersResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `includeArchived` | `*bool` | Query, Optional | Include archived products. Use in query: `include_archived=true`. | - -## Response Type - -[`models.ListOffersResponse`](../../doc/models/list-offers-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `includeArchived` | `*bool` | Query, Optional | Include archived products. Use in query: `include_archived=true`. | + +## Response Type + +[`models.ListOffersResponse`](../../doc/models/list-offers-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -includeArchived := true -apiResponse, err := offersController.ListOffers(ctx, &page, &perPage, &includeArchived) +collectedInput := advancedbilling.ListOffersInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + IncludeArchived: models.ToPointer(true), +} + +apiResponse, err := offersController.ListOffers(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "offers": [ - { - "id": 239, - "site_id": 48110, - "product_family_id": 1025627, - "product_family_name": "Gold", - "product_id": 110, - "product_name": "Pro", - "product_price_in_cents": 1000, - "product_revisable_number": 0, - "product_price_point_id": 138, - "product_price_point_name": "Default", - "name": "Third Offer", - "handle": "third", - "description": "", - "created_at": "2018-08-03T09:56:11-05:00", - "updated_at": "2018-08-03T09:56:11-05:00", - "archived_at": null, - "offer_items": [ - { - "component_id": 426665, - "component_name": "Database Size (GB)", - "component_unit_price": "1.0", - "price_point_id": 149438, - "price_point_name": "Auto-created", - "starting_quantity": "0.0", - "editable": false, - "currency_prices": [] - } - ], - "offer_discounts": [ - { - "coupon_id": 234, - "coupon_code": "GR8_CUSTOMER", - "coupon_name": "Multi-service Discount" - } - ], - "offer_signup_pages": [ - { - "id": 356482, - "nickname": "ggoods", - "enabled": true, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargifypay.com/subscribe/hjpvhnw63tzy" - } - ] - } - ] -} -``` - - -# Read Offer - -This method allows you to list a specific offer's attributes. This is different than list all offers for a site, as it requires an `offer_id`. - -```go -ReadOffer( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "offers": [ + { + "id": 239, + "site_id": 48110, + "product_family_id": 1025627, + "product_family_name": "Gold", + "product_id": 110, + "product_name": "Pro", + "product_price_in_cents": 1000, + "product_revisable_number": 0, + "product_price_point_id": 138, + "product_price_point_name": "Default", + "name": "Third Offer", + "handle": "third", + "description": "", + "created_at": "2018-08-03T09:56:11-05:00", + "updated_at": "2018-08-03T09:56:11-05:00", + "archived_at": null, + "offer_items": [ + { + "component_id": 426665, + "component_name": "Database Size (GB)", + "component_unit_price": "1.0", + "price_point_id": 149438, + "price_point_name": "Auto-created", + "starting_quantity": "0.0", + "editable": false, + "currency_prices": [] + } + ], + "offer_discounts": [ + { + "coupon_id": 234, + "coupon_code": "GR8_CUSTOMER", + "coupon_name": "Multi-service Discount" + } + ], + "offer_signup_pages": [ + { + "id": 356482, + "nickname": "ggoods", + "enabled": true, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargifypay.com/subscribe/hjpvhnw63tzy" + } + ] + } + ] +} +``` + + +# Read Offer + +This method allows you to list a specific offer's attributes. This is different than list all offers for a site, as it requires an `offer_id`. + +```go +ReadOffer( + ctx context.Context, offerId int) ( models.ApiResponse[models.OfferResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `offerId` | `int` | Template, Required | The Chargify id of the offer | - -## Response Type - -[`models.OfferResponse`](../../doc/models/offer-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `offerId` | `int` | Template, Required | The Chargify id of the offer | + +## Response Type + +[`models.OfferResponse`](../../doc/models/offer-response.md) + +## Example Usage + +```go ctx := context.Background() offerId := 130 @@ -268,35 +272,35 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Archive Offer - -Archive an existing offer. Please provide an `offer_id` in order to archive the correct item. - -```go -ArchiveOffer( - ctx context.Context, +} +``` + + +# Archive Offer + +Archive an existing offer. Please provide an `offer_id` in order to archive the correct item. + +```go +ArchiveOffer( + ctx context.Context, offerId int) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `offerId` | `int` | Template, Required | The Chargify id of the offer | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `offerId` | `int` | Template, Required | The Chargify id of the offer | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() offerId := 130 @@ -305,35 +309,35 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - - -# Unarchive Offer - -Unarchive a previously archived offer. Please provide an `offer_id` in order to un-archive the correct item. - -```go -UnarchiveOffer( - ctx context.Context, +} +``` + + +# Unarchive Offer + +Unarchive a previously archived offer. Please provide an `offer_id` in order to un-archive the correct item. + +```go +UnarchiveOffer( + ctx context.Context, offerId int) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `offerId` | `int` | Template, Required | The Chargify id of the offer | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `offerId` | `int` | Template, Required | The Chargify id of the offer | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() offerId := 130 @@ -342,6 +346,6 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - +} +``` + diff --git a/doc/controllers/payment-profiles.md b/doc/controllers/payment-profiles.md index f35abb48..fdde577b 100644 --- a/doc/controllers/payment-profiles.md +++ b/doc/controllers/payment-profiles.md @@ -1,15 +1,15 @@ -# Payment Profiles - -```go -paymentProfilesController := client.PaymentProfilesController() -``` - -## Class Name - -`PaymentProfilesController` - -## Methods - +# Payment Profiles + +```go +paymentProfilesController := client.PaymentProfilesController() +``` + +## Class Name + +`PaymentProfilesController` + +## Methods + * [Create Payment Profile](../../doc/controllers/payment-profiles.md#create-payment-profile) * [List Payment Profiles](../../doc/controllers/payment-profiles.md#list-payment-profiles) * [Read Payment Profile](../../doc/controllers/payment-profiles.md#read-payment-profile) @@ -21,11 +21,11 @@ paymentProfilesController := client.PaymentProfilesController() * [Change Subscription Default Payment Profile](../../doc/controllers/payment-profiles.md#change-subscription-default-payment-profile) * [Change Subscription Group Default Payment Profile](../../doc/controllers/payment-profiles.md#change-subscription-group-default-payment-profile) * [Read One Time Token](../../doc/controllers/payment-profiles.md#read-one-time-token) -* [Send Request Update Payment Email](../../doc/controllers/payment-profiles.md#send-request-update-payment-email) - - -# Create Payment Profile - +* [Send Request Update Payment Email](../../doc/controllers/payment-profiles.md#send-request-update-payment-email) + + +# Create Payment Profile + Use this endpoint to create a payment profile for a customer. Payment Profiles house the credit card, ACH (Authorize.Net or Stripe only,) or PayPal (Braintree only,) data for a customer. The payment information is attached to the customer within Chargify, as opposed to the Subscription itself. @@ -269,29 +269,29 @@ You may wish to redirect customers to different pages depending on whether their 5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied 6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. 7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known -8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not - -```go -CreatePaymentProfile( - ctx context.Context, +8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not + +```go +CreatePaymentProfile( + ctx context.Context, body *models.CreatePaymentProfileRequest) ( models.ApiResponse[models.PaymentProfileResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.CreatePaymentProfileRequest`](../../doc/models/create-payment-profile-request.md) | Body, Optional | When following the IBAN or the Local Bank details examples, a customer, bank account and mandate will be created in your current vault. If the customer, bank account, and mandate already exist in your vault, follow the Import example to link the payment profile into Chargify. | - -## Response Type - -[`models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.CreatePaymentProfileRequest`](../../doc/models/create-payment-profile-request.md) | Body, Optional | When following the IBAN or the Local Bank details examples, a customer, bank account and mandate will be created in your current vault. If the customer, bank account, and mandate already exist in your vault, follow the Import example to link the payment profile into Chargify. | + +## Response Type + +[`models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) + +## Example Usage + +```go ctx := context.Background() bodyPaymentProfile := models.CreatePaymentProfile{ @@ -315,148 +315,152 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "payment_profile": { - "first_name": "Jessica", - "last_name": "Test", - "card_type": "visa", - "masked_card_number": "XXXX-XXXX-XXXX-1111", - "expiration_month": 10, - "expiration_year": 2018, - "customer_id": 19195410, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "123 Main St.", - "billing_city": "Boston", - "billing_state": "MA", - "billing_zip": "02120", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": null, - "payment_type": "credit_card", - "site_gateway_setting_id": 1, - "gateway_handle": "handle", - "disabled": false - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Payment Profiles - -This method will return all of the active `payment_profiles` for a Site, or for one Customer within a site. If no payment profiles are found, this endpoint will return an empty array, not a 404. - -```go -ListPaymentProfiles( - ctx context.Context,input ListPaymentProfilesInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "payment_profile": { + "first_name": "Jessica", + "last_name": "Test", + "card_type": "visa", + "masked_card_number": "XXXX-XXXX-XXXX-1111", + "expiration_month": 10, + "expiration_year": 2018, + "customer_id": 19195410, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": "123 Main St.", + "billing_city": "Boston", + "billing_state": "MA", + "billing_zip": "02120", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": null, + "payment_type": "credit_card", + "site_gateway_setting_id": 1, + "gateway_handle": "handle", + "disabled": false + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Payment Profiles + +This method will return all of the active `payment_profiles` for a Site, or for one Customer within a site. If no payment profiles are found, this endpoint will return an empty array, not a 404. + +```go +ListPaymentProfiles( + ctx context.Context, + input ListPaymentProfilesInput) ( models.ApiResponse[[]models.PaymentProfileResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `customerId` | `*int` | Query, Optional | The ID of the customer for which you wish to list payment profiles | - -## Response Type - -[`[]models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `customerId` | `*int` | Query, Optional | The ID of the customer for which you wish to list payment profiles | + +## Response Type + +[`[]models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -apiResponse, err := paymentProfilesController.ListPaymentProfiles(ctx, &page, &perPage, nil) +collectedInput := advancedbilling.ListPaymentProfilesInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +} + +apiResponse, err := paymentProfilesController.ListPaymentProfiles(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "payment_profile": { - "id": 10089892, - "first_name": "Chester", - "last_name": "Tester", - "customer_id": 14543792, - "current_vault": "bogus", - "vault_token": "0011223344", - "billing_address": "456 Juniper Court", - "billing_city": "Boulder", - "billing_state": "CO", - "billing_zip": "80302", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": "", - "bank_name": "Bank of Kansas City", - "masked_bank_routing_number": "XXXX6789", - "masked_bank_account_number": "XXXX3344", - "bank_account_type": "checking", - "bank_account_holder_type": "personal", - "payment_type": "bank_account", - "verified": true, - "site_gateway_setting_id": 1, - "gateway_handle": "handle" - } - }, - { - "payment_profile": { - "id": 10188522, - "first_name": "Frankie", - "last_name": "Tester", - "customer_id": 14543712, - "current_vault": "bogus", - "vault_token": "123456789", - "billing_address": "123 Montana Way", - "billing_city": "Los Angeles", - "billing_state": "CA", - "billing_zip": "90210", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": "", - "bank_name": "Bank of Kansas City", - "masked_bank_routing_number": "XXXX6789", - "masked_bank_account_number": "XXXX6789", - "bank_account_type": "checking", - "bank_account_holder_type": "personal", - "payment_type": "bank_account", - "verified": true, - "site_gateway_setting_id": 1, - "gateway_handle": "handle" - } - } -] -``` - - -# Read Payment Profile - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "payment_profile": { + "id": 10089892, + "first_name": "Chester", + "last_name": "Tester", + "customer_id": 14543792, + "current_vault": "bogus", + "vault_token": "0011223344", + "billing_address": "456 Juniper Court", + "billing_city": "Boulder", + "billing_state": "CO", + "billing_zip": "80302", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": "", + "bank_name": "Bank of Kansas City", + "masked_bank_routing_number": "XXXX6789", + "masked_bank_account_number": "XXXX3344", + "bank_account_type": "checking", + "bank_account_holder_type": "personal", + "payment_type": "bank_account", + "verified": true, + "site_gateway_setting_id": 1, + "gateway_handle": "handle" + } + }, + { + "payment_profile": { + "id": 10188522, + "first_name": "Frankie", + "last_name": "Tester", + "customer_id": 14543712, + "current_vault": "bogus", + "vault_token": "123456789", + "billing_address": "123 Montana Way", + "billing_city": "Los Angeles", + "billing_state": "CA", + "billing_zip": "90210", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": "", + "bank_name": "Bank of Kansas City", + "masked_bank_routing_number": "XXXX6789", + "masked_bank_account_number": "XXXX6789", + "bank_account_type": "checking", + "bank_account_holder_type": "personal", + "payment_type": "bank_account", + "verified": true, + "site_gateway_setting_id": 1, + "gateway_handle": "handle" + } + } +] +``` + + +# Read Payment Profile + Using the GET method you can retrieve a Payment Profile identified by its unique ID. Please note that a different JSON object will be returned if the card method on file is a bank account. @@ -491,29 +495,29 @@ Example response for Bank Account: "gateway_handle": null } } -``` - -```go -ReadPaymentProfile( - ctx context.Context, +``` + +```go +ReadPaymentProfile( + ctx context.Context, paymentProfileId int) ( models.ApiResponse[models.PaymentProfileResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | - -## Response Type - -[`models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | + +## Response Type + +[`models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) + +## Example Usage + +```go ctx := context.Background() paymentProfileId := 198 @@ -524,47 +528,47 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "payment_profile": { - "id": 10088716, - "first_name": "Test", - "last_name": "Subscription", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2022, - "customer_id": 14543792, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "123 Montana Way", - "billing_city": "Billings", - "billing_state": "MT", - "billing_zip": "59101", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": "", - "payment_type": "credit_card", - "site_gateway_setting_id": 1, - "gateway_handle": null - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Update Payment Profile - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "payment_profile": { + "id": 10088716, + "first_name": "Test", + "last_name": "Subscription", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2022, + "customer_id": 14543792, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": "123 Montana Way", + "billing_city": "Billings", + "billing_state": "MT", + "billing_zip": "59101", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": "", + "payment_type": "credit_card", + "site_gateway_setting_id": 1, + "gateway_handle": null + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Update Payment Profile + ## Partial Card Updates In the event that you are using the Authorize.net, Stripe, Cybersource, Forte or Braintree Blue payment gateways, you can update just the billing and contact information for a payment method. Note the lack of credit-card related data contained in the JSON payload. @@ -598,31 +602,31 @@ The result will be that you have updated the billing information for the card, y - Updating a payment profile directly will not trigger an attempt to capture a past-due balance. If this is the intent, update the card details via the Subscription instead. -- If you are using Authorize.net or Stripe, you may elect to manually trigger a retry for a past due subscription after a partial update. - -```go -UpdatePaymentProfile( - ctx context.Context, - paymentProfileId int, +- If you are using Authorize.net or Stripe, you may elect to manually trigger a retry for a past due subscription after a partial update. + +```go +UpdatePaymentProfile( + ctx context.Context, + paymentProfileId int, body *models.UpdatePaymentProfileRequest) ( models.ApiResponse[models.PaymentProfileResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | -| `body` | [`*models.UpdatePaymentProfileRequest`](../../doc/models/update-payment-profile-request.md) | Body, Optional | - | - -## Response Type - -[`models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | +| `body` | [`*models.UpdatePaymentProfileRequest`](../../doc/models/update-payment-profile-request.md) | Body, Optional | - | + +## Response Type + +[`models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) + +## Example Usage + +```go ctx := context.Background() paymentProfileId := 198 @@ -653,73 +657,73 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "payment_profile": { - "id": 10088716, - "first_name": "Test", - "last_name": "Subscription", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2022, - "customer_id": 14543792, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "123 Montana Way", - "billing_city": "Billings", - "billing_state": "MT", - "billing_zip": "59101", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": "", - "payment_type": "credit_card", - "site_gateway_setting_id": 1, - "gateway_handle": null - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorStringMapResponseException`](../../doc/models/error-string-map-response-exception.md) | - - -# Delete Unused Payment Profile - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "payment_profile": { + "id": 10088716, + "first_name": "Test", + "last_name": "Subscription", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2022, + "customer_id": 14543792, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": "123 Montana Way", + "billing_city": "Billings", + "billing_state": "MT", + "billing_zip": "59101", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": "", + "payment_type": "credit_card", + "site_gateway_setting_id": 1, + "gateway_handle": null + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorStringMapResponseException`](../../doc/models/error-string-map-response-exception.md) | + + +# Delete Unused Payment Profile + Deletes an unused payment profile. -If the payment profile is in use by one or more subscriptions or groups, a 422 and error message will be returned. - -```go -DeleteUnusedPaymentProfile( - ctx context.Context, +If the payment profile is in use by one or more subscriptions or groups, a 422 and error message will be returned. + +```go +DeleteUnusedPaymentProfile( + ctx context.Context, paymentProfileId int) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() paymentProfileId := 198 @@ -728,48 +732,48 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Delete Subscriptions Payment Profile - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Delete Subscriptions Payment Profile + This will delete a payment profile belonging to the customer on the subscription. + If the customer has multiple subscriptions, the payment profile will be removed from all of them. -+ If you delete the default payment profile for a subscription, you will need to specify another payment profile to be the default through the api, or either prompt the user to enter a card in the billing portal or on the self-service page, or visit the Payment Details tab on the subscription in the Admin UI and use the “Add New Credit Card” or “Make Active Payment Method” link, (depending on whether there are other cards present). - -```go -DeleteSubscriptionsPaymentProfile( - ctx context.Context, - subscriptionId int, ++ If you delete the default payment profile for a subscription, you will need to specify another payment profile to be the default through the api, or either prompt the user to enter a card in the billing portal or on the self-service page, or visit the Payment Details tab on the subscription in the Admin UI and use the “Add New Credit Card” or “Make Active Payment Method” link, (depending on whether there are other cards present). + +```go +DeleteSubscriptionsPaymentProfile( + ctx context.Context, + subscriptionId int, paymentProfileId int) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 paymentProfileId := 198 @@ -779,37 +783,37 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - - -# Verify Bank Account - -Submit the two small deposit amounts the customer received in their bank account in order to verify the bank account. (Stripe only) - -```go -VerifyBankAccount( - ctx context.Context, - bankAccountId int, +} +``` + + +# Verify Bank Account + +Submit the two small deposit amounts the customer received in their bank account in order to verify the bank account. (Stripe only) + +```go +VerifyBankAccount( + ctx context.Context, + bankAccountId int, body *models.BankAccountVerificationRequest) ( models.ApiResponse[models.BankAccountResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `bankAccountId` | `int` | Template, Required | Identifier of the bank account in the system. | -| `body` | [`*models.BankAccountVerificationRequest`](../../doc/models/bank-account-verification-request.md) | Body, Optional | - | - -## Response Type - -[`models.BankAccountResponse`](../../doc/models/bank-account-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `bankAccountId` | `int` | Template, Required | Identifier of the bank account in the system. | +| `body` | [`*models.BankAccountVerificationRequest`](../../doc/models/bank-account-verification-request.md) | Body, Optional | - | + +## Response Type + +[`models.BankAccountResponse`](../../doc/models/bank-account-response.md) + +## Example Usage + +```go ctx := context.Background() bankAccountId := 252 @@ -829,74 +833,74 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "payment_profile": { - "id": 10089892, - "first_name": "Chester", - "last_name": "Tester", - "customer_id": 14543792, - "current_vault": "stripe_connect", - "vault_token": "cus_0123abc456def", - "billing_address": "456 Juniper Court", - "billing_city": "Boulder", - "billing_state": "CO", - "billing_zip": "80302", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": "", - "bank_name": "Bank of Kansas City", - "masked_bank_routing_number": "XXXX6789", - "masked_bank_account_number": "XXXX3344", - "bank_account_type": "checking", - "bank_account_holder_type": "personal", - "payment_type": "bank_account" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Delete Subscription Group Payment Profile - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "payment_profile": { + "id": 10089892, + "first_name": "Chester", + "last_name": "Tester", + "customer_id": 14543792, + "current_vault": "stripe_connect", + "vault_token": "cus_0123abc456def", + "billing_address": "456 Juniper Court", + "billing_city": "Boulder", + "billing_state": "CO", + "billing_zip": "80302", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": "", + "bank_name": "Bank of Kansas City", + "masked_bank_routing_number": "XXXX6789", + "masked_bank_account_number": "XXXX3344", + "bank_account_type": "checking", + "bank_account_holder_type": "personal", + "payment_type": "bank_account" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Delete Subscription Group Payment Profile + This will delete a Payment Profile belonging to a Subscription Group. -**Note**: If the Payment Profile belongs to multiple Subscription Groups and/or Subscriptions, it will be removed from all of them. - -```go -DeleteSubscriptionGroupPaymentProfile( - ctx context.Context, - uid string, +**Note**: If the Payment Profile belongs to multiple Subscription Groups and/or Subscriptions, it will be removed from all of them. + +```go +DeleteSubscriptionGroupPaymentProfile( + ctx context.Context, + uid string, paymentProfileId int) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() uid := "uid0" paymentProfileId := 198 @@ -906,39 +910,39 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - - -# Change Subscription Default Payment Profile - +} +``` + + +# Change Subscription Default Payment Profile + This will change the default payment profile on the subscription to the existing payment profile with the id specified. -You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. - -```go -ChangeSubscriptionDefaultPaymentProfile( - ctx context.Context, - subscriptionId int, +You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. + +```go +ChangeSubscriptionDefaultPaymentProfile( + ctx context.Context, + subscriptionId int, paymentProfileId int) ( models.ApiResponse[models.PaymentProfileResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | - -## Response Type - -[`models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | + +## Response Type + +[`models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 paymentProfileId := 198 @@ -950,77 +954,77 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "payment_profile": { - "id": 10211899, - "first_name": "Amelia", - "last_name": "Example", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 2, - "expiration_year": 2018, - "customer_id": 14399371, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "", - "billing_city": "", - "billing_state": "", - "billing_zip": "", - "billing_country": "", - "customer_vault_token": null, - "billing_address_2": "", - "payment_type": "credit_card", - "site_gateway_setting_id": 1, - "gateway_handle": null - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Change Subscription Group Default Payment Profile - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "payment_profile": { + "id": 10211899, + "first_name": "Amelia", + "last_name": "Example", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 2, + "expiration_year": 2018, + "customer_id": 14399371, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": "", + "billing_city": "", + "billing_state": "", + "billing_zip": "", + "billing_country": "", + "customer_vault_token": null, + "billing_address_2": "", + "payment_type": "credit_card", + "site_gateway_setting_id": 1, + "gateway_handle": null + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Change Subscription Group Default Payment Profile + This will change the default payment profile on the subscription group to the existing payment profile with the id specified. You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. -The new payment profile must belong to the subscription group's customer, otherwise you will receive an error. - -```go -ChangeSubscriptionGroupDefaultPaymentProfile( - ctx context.Context, - uid string, +The new payment profile must belong to the subscription group's customer, otherwise you will receive an error. + +```go +ChangeSubscriptionGroupDefaultPaymentProfile( + ctx context.Context, + uid string, paymentProfileId int) ( models.ApiResponse[models.PaymentProfileResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | - -## Response Type - -[`models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `paymentProfileId` | `int` | Template, Required | The Chargify id of the payment profile | + +## Response Type + +[`models.PaymentProfileResponse`](../../doc/models/payment-profile-response.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" paymentProfileId := 198 @@ -1032,74 +1036,74 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "payment_profile": { - "id": 10211899, - "first_name": "Amelia", - "last_name": "Example", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 2, - "expiration_year": 2018, - "customer_id": 14399371, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "", - "billing_city": "", - "billing_state": "", - "billing_zip": "", - "billing_country": "", - "customer_vault_token": null, - "billing_address_2": "", - "payment_type": "credit_card", - "site_gateway_setting_id": 1, - "gateway_handle": null - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Read One Time Token - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "payment_profile": { + "id": 10211899, + "first_name": "Amelia", + "last_name": "Example", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 2, + "expiration_year": 2018, + "customer_id": 14399371, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": "", + "billing_city": "", + "billing_state": "", + "billing_zip": "", + "billing_country": "", + "customer_vault_token": null, + "billing_address_2": "", + "payment_type": "credit_card", + "site_gateway_setting_id": 1, + "gateway_handle": null + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Read One Time Token + One Time Tokens aka Chargify Tokens house the credit card or ACH (Authorize.Net or Stripe only) data for a customer. You can use One Time Tokens while creating a subscription or payment profile instead of passing all bank account or credit card data directly to a given API endpoint. -To obtain a One Time Token you have to use [chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview). - -```go -ReadOneTimeToken( - ctx context.Context, +To obtain a One Time Token you have to use [chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview). + +```go +ReadOneTimeToken( + ctx context.Context, chargifyToken string) ( models.ApiResponse[models.GetOneTimeTokenRequest], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `chargifyToken` | `string` | Template, Required | Chargify Token | - -## Response Type - -[`models.GetOneTimeTokenRequest`](../../doc/models/get-one-time-token-request.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `chargifyToken` | `string` | Template, Required | Chargify Token | + +## Response Type + +[`models.GetOneTimeTokenRequest`](../../doc/models/get-one-time-token-request.md) + +## Example Usage + +```go ctx := context.Background() chargifyToken := "chargify_token8" @@ -1110,47 +1114,47 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Send Request Update Payment Email - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Send Request Update Payment Email + You can send a "request payment update" email to the customer associated with the subscription. If you attempt to send a "request payment update" email more than five times within a 30-minute period, you will receive a `422` response with an error message in the body. This error message will indicate that the request has been rejected due to excessive attempts, and will provide instructions on how to resubmit the request. Additionally, if you attempt to send a "request payment update" email for a subscription that does not exist, you will receive a `404` error response. This error message will indicate that the subscription could not be found, and will provide instructions on how to correct the error and resubmit the request. -These error responses are designed to prevent excessive or invalid requests, and to provide clear and helpful information to users who encounter errors during the request process. - -```go -SendRequestUpdatePaymentEmail( - ctx context.Context, +These error responses are designed to prevent excessive or invalid requests, and to provide clear and helpful information to users who encounter errors during the request process. + +```go +SendRequestUpdatePaymentEmail( + ctx context.Context, subscriptionId int) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -1159,13 +1163,13 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/controllers/product-families.md b/doc/controllers/product-families.md index 2cd2b412..be732027 100644 --- a/doc/controllers/product-families.md +++ b/doc/controllers/product-families.md @@ -1,206 +1,210 @@ -# Product Families - -```go -productFamiliesController := client.ProductFamiliesController() -``` - -## Class Name - -`ProductFamiliesController` - -## Methods - +# Product Families + +```go +productFamiliesController := client.ProductFamiliesController() +``` + +## Class Name + +`ProductFamiliesController` + +## Methods + * [List Products for Product Family](../../doc/controllers/product-families.md#list-products-for-product-family) * [Create Product Family](../../doc/controllers/product-families.md#create-product-family) * [List Product Families](../../doc/controllers/product-families.md#list-product-families) -* [Read Product Family](../../doc/controllers/product-families.md#read-product-family) - - -# List Products for Product Family - -This method allows to retrieve a list of Products belonging to a Product Family. - -```go -ListProductsForProductFamily( - ctx context.Context,input ListProductsForProductFamilyInput) ( +* [Read Product Family](../../doc/controllers/product-families.md#read-product-family) + + +# List Products for Product Family + +This method allows to retrieve a list of Products belonging to a Product Family. + +```go +ListProductsForProductFamily( + ctx context.Context, + input ListProductsForProductFamilyInput) ( models.ApiResponse[[]models.ProductResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the product belongs | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | -| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | -| `includeArchived` | `*bool` | Query, Optional | Include archived products | -| `include` | [`*models.ListProductsInclude`](../../doc/models/list-products-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=prepaid_product_price_point`. | -| `filterPrepaidProductPricePointProductPricePointId` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching products only if a prepaid product price point is present or not. To use this filter you also have to include the following param in the request `include=prepaid_product_price_point`. Use in query `filter[prepaid_product_price_point][product_price_point_id]=not_null`. | -| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching products with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | - -## Response Type - -[`[]models.ProductResponse`](../../doc/models/product-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the product belongs | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | +| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | +| `includeArchived` | `*bool` | Query, Optional | Include archived products | +| `include` | [`*models.ListProductsInclude`](../../doc/models/list-products-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=prepaid_product_price_point`. | +| `filterPrepaidProductPricePointProductPricePointId` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching products only if a prepaid product price point is present or not. To use this filter you also have to include the following param in the request `include=prepaid_product_price_point`. Use in query `filter[prepaid_product_price_point][product_price_point_id]=not_null`. | +| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching products with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | + +## Response Type + +[`[]models.ProductResponse`](../../doc/models/product-response.md) + +## Example Usage + +```go ctx := context.Background() -productFamilyId := 140 -page := 2 -perPage := 50 -dateField := models.BasicDateField("updated_at") -include := models.ListProductsInclude("prepaid_product_price_point")Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') -apiResponse, err := productFamiliesController.ListProductsForProductFamily(ctx, productFamilyId, &page, &perPage, &dateField, nil, nil, nil, nil, nil, &include, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key')) +collectedInput := advancedbilling.ListProductsForProductFamilyInput{ + ProductFamilyId: 140, + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + DateField: models.ToPointer(models.BasicDateField("updated_at")), + Include: models.ToPointer(models.ListProductsInclude("prepaid_product_price_point")), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := productFamiliesController.ListProductsForProductFamily(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "product": { - "id": 3801242, - "name": "Free product", - "handle": "zero-dollar-product", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2016-04-21T16:08:39-04:00", - "updated_at": "2016-08-03T11:27:53-04:00", - "price_in_cents": 10000, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": 0, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": false, - "return_params": "", - "taxable": false, - "update_return_url": "", - "initial_charge_after_trial": false, - "version_number": 4, - "update_return_params": "", - "product_family": { - "id": 527890, - "name": "Acme Projects", - "description": "", - "handle": "billing-plans", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 283460, - "return_url": null, - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/smcc4j3d2w6h/zero-dollar-product" - } - ], - "product_price_point_name": "Default", - "use_site_exchange_rate": true - } - }, - { - "product": { - "id": 3858146, - "name": "Calendar Billing Product", - "handle": "calendar-billing-product", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2016-07-05T13:07:38-04:00", - "updated_at": "2016-07-05T13:07:38-04:00", - "price_in_cents": 10000, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": true, - "return_params": "", - "taxable": false, - "update_return_url": "", - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": "", - "product_family": { - "id": 527890, - "name": "Acme Projects", - "description": "", - "handle": "billing-plans", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 289193, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/gxdbfxzxhcjq/calendar-billing-product" - } - ], - "product_price_point_name": "Default", - "use_site_exchange_rate": true - } - } -] -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Create Product Family - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "product": { + "id": 3801242, + "name": "Free product", + "handle": "zero-dollar-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2016-04-21T16:08:39-04:00", + "updated_at": "2016-08-03T11:27:53-04:00", + "price_in_cents": 10000, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": 0, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": false, + "return_params": "", + "taxable": false, + "update_return_url": "", + "initial_charge_after_trial": false, + "version_number": 4, + "update_return_params": "", + "product_family": { + "id": 527890, + "name": "Acme Projects", + "description": "", + "handle": "billing-plans", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 283460, + "return_url": null, + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/smcc4j3d2w6h/zero-dollar-product" + } + ], + "product_price_point_name": "Default", + "use_site_exchange_rate": true + } + }, + { + "product": { + "id": 3858146, + "name": "Calendar Billing Product", + "handle": "calendar-billing-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2016-07-05T13:07:38-04:00", + "updated_at": "2016-07-05T13:07:38-04:00", + "price_in_cents": 10000, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": true, + "return_params": "", + "taxable": false, + "update_return_url": "", + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": "", + "product_family": { + "id": 527890, + "name": "Acme Projects", + "description": "", + "handle": "billing-plans", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 289193, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/gxdbfxzxhcjq/calendar-billing-product" + } + ], + "product_price_point_name": "Default", + "use_site_exchange_rate": true + } + } +] +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Create Product Family + This method will create a Product Family within your Chargify site. Create a Product Family to act as a container for your products, components and coupons. -Full documentation on how Product Families operate within the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405369633421). - -```go -CreateProductFamily( - ctx context.Context, +Full documentation on how Product Families operate within the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405369633421). + +```go +CreateProductFamily( + ctx context.Context, body *models.CreateProductFamilyRequest) ( models.ApiResponse[models.ProductFamilyResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.CreateProductFamilyRequest`](../../doc/models/create-product-family-request.md) | Body, Optional | - | - -## Response Type - -[`models.ProductFamilyResponse`](../../doc/models/product-family-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.CreateProductFamilyRequest`](../../doc/models/create-product-family-request.md) | Body, Optional | - | + +## Response Type + +[`models.ProductFamilyResponse`](../../doc/models/product-family-response.md) + +## Example Usage + +```go ctx := context.Background() bodyProductFamily := models.CreateProductFamily{ @@ -219,128 +223,132 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "product_family": { - "id": 933860, - "name": "Acme Projects", - "description": "Amazing project management tool", - "handle": "acme-projects", - "accounting_code": null - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Product Families - -This method allows to retrieve a list of Product Families for a site. - -```go -ListProductFamilies( - ctx context.Context,input ListProductFamiliesInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "product_family": { + "id": 933860, + "name": "Acme Projects", + "description": "Amazing project management tool", + "handle": "acme-projects", + "accounting_code": null + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Product Families + +This method allows to retrieve a list of Product Families for a site. + +```go +ListProductFamilies( + ctx context.Context, + input ListProductFamiliesInput) ( models.ApiResponse[[]models.ProductFamilyResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | -| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | - -## Response Type - -[`[]models.ProductFamilyResponse`](../../doc/models/product-family-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | +| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | + +## Response Type + +[`[]models.ProductFamilyResponse`](../../doc/models/product-family-response.md) + +## Example Usage + +```go ctx := context.Background() -dateField := models.BasicDateField("updated_at") -apiResponse, err := productFamiliesController.ListProductFamilies(ctx, &dateField, nil, nil, nil, nil) +collectedInput := advancedbilling.ListProductFamiliesInput{ + DateField: models.ToPointer(models.BasicDateField("updated_at")), +} + +apiResponse, err := productFamiliesController.ListProductFamilies(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "product_family": { - "id": 37, - "name": "Acme Projects", - "description": null, - "handle": "acme-projects", - "accounting_code": null, - "created_at": "2013-02-20T15:05:51-07:00", - "updated_at": "2013-02-20T15:05:51-07:00" - } - }, - { - "product_family": { - "id": 155, - "name": "Bat Family", - "description": "Another family.", - "handle": "bat-family", - "accounting_code": null, - "created_at": "2014-04-16T12:41:13-06:00", - "updated_at": "2014-04-16T12:41:13-06:00" - } - } -] -``` - - -# Read Product Family - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "product_family": { + "id": 37, + "name": "Acme Projects", + "description": null, + "handle": "acme-projects", + "accounting_code": null, + "created_at": "2013-02-20T15:05:51-07:00", + "updated_at": "2013-02-20T15:05:51-07:00" + } + }, + { + "product_family": { + "id": 155, + "name": "Bat Family", + "description": "Another family.", + "handle": "bat-family", + "accounting_code": null, + "created_at": "2014-04-16T12:41:13-06:00", + "updated_at": "2014-04-16T12:41:13-06:00" + } + } +] +``` + + +# Read Product Family + This method allows to retrieve a Product Family via the `product_family_id`. The response will contain a Product Family object. -The product family can be specified either with the id number, or with the `handle:my-family` format. - -```go -ReadProductFamily( - ctx context.Context, +The product family can be specified either with the id number, or with the `handle:my-family` format. + +```go +ReadProductFamily( + ctx context.Context, id int) ( models.ApiResponse[models.ProductFamilyResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `id` | `int` | Template, Required | The Chargify id of the product family | - -## Response Type - -[`models.ProductFamilyResponse`](../../doc/models/product-family-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `id` | `int` | Template, Required | The Chargify id of the product family | + +## Response Type + +[`models.ProductFamilyResponse`](../../doc/models/product-family-response.md) + +## Example Usage + +```go ctx := context.Background() id := 112 @@ -351,20 +359,20 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "product_family": { - "id": 527890, - "name": "Acme Projects", - "description": "", - "handle": "billing-plans", - "accounting_code": null - } -} -``` - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "product_family": { + "id": 527890, + "name": "Acme Projects", + "description": "", + "handle": "billing-plans", + "accounting_code": null + } +} +``` + diff --git a/doc/controllers/product-price-points.md b/doc/controllers/product-price-points.md index b5f171a5..8e69d746 100644 --- a/doc/controllers/product-price-points.md +++ b/doc/controllers/product-price-points.md @@ -1,15 +1,15 @@ -# Product Price Points - -```go -productPricePointsController := client.ProductPricePointsController() -``` - -## Class Name - -`ProductPricePointsController` - -## Methods - +# Product Price Points + +```go +productPricePointsController := client.ProductPricePointsController() +``` + +## Class Name + +`ProductPricePointsController` + +## Methods + * [Create Product Price Point](../../doc/controllers/product-price-points.md#create-product-price-point) * [List Product Price Points](../../doc/controllers/product-price-points.md#list-product-price-points) * [Update Product Price Point](../../doc/controllers/product-price-points.md#update-product-price-point) @@ -20,38 +20,39 @@ productPricePointsController := client.ProductPricePointsController() * [Bulk Create Product Price Points](../../doc/controllers/product-price-points.md#bulk-create-product-price-points) * [Create Product Currency Prices](../../doc/controllers/product-price-points.md#create-product-currency-prices) * [Update Product Currency Prices](../../doc/controllers/product-price-points.md#update-product-currency-prices) -* [List All Product Price Points](../../doc/controllers/product-price-points.md#list-all-product-price-points) - - -# Create Product Price Point - -[Product Price Point Documentation](https://chargify.zendesk.com/hc/en-us/articles/4407755824155) - -```go -CreateProductPricePoint( - ctx context.Context, - productId interface{}, +* [List All Product Price Points](../../doc/controllers/product-price-points.md#list-all-product-price-points) + + +# Create Product Price Point + +[Product Price Point Documentation](https://chargify.zendesk.com/hc/en-us/articles/4407755824155) + +```go +CreateProductPricePoint( + ctx context.Context, + productId models.CreateProductPricePointProductId, body *models.CreateProductPricePointRequest) ( models.ApiResponse[models.ProductPricePointResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | `interface{}` | Template, Required | The id or handle of the product. When using the handle, it must be prefixed with `handle:` | -| `body` | [`*models.CreateProductPricePointRequest`](../../doc/models/create-product-price-point-request.md) | Body, Optional | - | - -## Response Type - -[`models.ProductPricePointResponse`](../../doc/models/product-price-point-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | [`models.CreateProductPricePointProductId`](../../doc/models/containers/create-product-price-point-product-id.md) | Template, Required | This is a container for one-of cases. | +| `body` | [`*models.CreateProductPricePointRequest`](../../doc/models/create-product-price-point-request.md) | Body, Optional | - | + +## Response Type + +[`models.ProductPricePointResponse`](../../doc/models/product-price-point-response.md) + +## Example Usage + +```go ctx := context.Background() -productId := interface{}("[key1, val1][key2, val2]") + +productId := models.CreateProductPricePointProductIdContainer.FromNumber(124) bodyPricePoint := models.CreateProductPricePoint{ Name: "Educational", @@ -79,150 +80,158 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_point": { - "id": 283, - "name": "Educational", - "handle": "educational", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "trial_price_in_cents": 4900, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "initial_charge_in_cents": 120000, - "initial_charge_after_trial": false, - "expiration_interval": 12, - "expiration_interval_unit": "month", - "product_id": 901, - "archived_at": "2023-11-30T06:37:20-05:00", - "created_at": "2023-11-27T06:37:20-05:00", - "updated_at": "2023-11-27T06:37:20-05:00" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ProductPricePointErrorResponseException`](../../doc/models/product-price-point-error-response-exception.md) | - - -# List Product Price Points - -Use this endpoint to retrieve a list of product price points. - -```go -ListProductPricePoints( - ctx context.Context,input ListProductPricePointsInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_point": { + "id": 283, + "name": "Educational", + "handle": "educational", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "trial_price_in_cents": 4900, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "initial_charge_in_cents": 120000, + "initial_charge_after_trial": false, + "expiration_interval": 12, + "expiration_interval_unit": "month", + "product_id": 901, + "archived_at": "2023-11-30T06:37:20-05:00", + "created_at": "2023-11-27T06:37:20-05:00", + "updated_at": "2023-11-27T06:37:20-05:00" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ProductPricePointErrorResponseException`](../../doc/models/product-price-point-error-response-exception.md) | + + +# List Product Price Points + +Use this endpoint to retrieve a list of product price points. + +```go +ListProductPricePoints( + ctx context.Context, + input ListProductPricePointsInput) ( models.ApiResponse[models.ListProductPricePointsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | `interface{}` | Template, Required | The id or handle of the product. When using the handle, it must be prefixed with `handle:` | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 10. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. | -| `currencyPrices` | `*bool` | Query, Optional | When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. | -| `filterType` | [`[]models.PricePointType`](../../doc/models/price-point-type.md) | Query, Optional | Use in query: `filter[type]=catalog,default`. | - -## Response Type - -[`models.ListProductPricePointsResponse`](../../doc/models/list-product-price-points-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | [`models.ListProductPricePointsInputProductId`](../../doc/models/containers/list-product-price-points-input-product-id.md) | Template, Required | This is a container for one-of cases. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 10. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. | +| `currencyPrices` | `*bool` | Query, Optional | When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. | +| `filterType` | [`[]models.PricePointType`](../../doc/models/price-point-type.md) | Query, Optional | Use in query: `filter[type]=catalog,default`. | + +## Response Type + +[`models.ListProductPricePointsResponse`](../../doc/models/list-product-price-points-response.md) + +## Example Usage + +```go ctx := context.Background() -productId := interface{}("[key1, val1][key2, val2]") -page := 2 -perPage := 10Liquid error: Value cannot be null. (Parameter 'key') -apiResponse, err := productPricePointsController.ListProductPricePoints(ctx, productId, &page, &perPage, nil, Liquid error: Value cannot be null. (Parameter 'key')) +collectedInputProductId := models.ListProductPricePointsInputProductIdContainer.FromNumber(124) + +collectedInput := advancedbilling.ListProductPricePointsInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(10), +Liquid error: Value cannot be null. (Parameter 'key') ProductId: collectedInputProductId, +} + +apiResponse, err := productPricePointsController.ListProductPricePoints(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_points": [ - { - "id": 283, - "name": "Educational", - "handle": "educational", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "trial_price_in_cents": 4900, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "initial_charge_in_cents": 120000, - "initial_charge_after_trial": false, - "expiration_interval": 12, - "expiration_interval_unit": "month", - "product_id": 901, - "archived_at": "2023-11-30T06:37:20-05:00", - "created_at": "2023-11-27T06:37:20-05:00", - "updated_at": "2023-11-27T06:37:20-05:00" - } - ] -} -``` - - -# Update Product Price Point - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_points": [ + { + "id": 283, + "name": "Educational", + "handle": "educational", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "trial_price_in_cents": 4900, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "initial_charge_in_cents": 120000, + "initial_charge_after_trial": false, + "expiration_interval": 12, + "expiration_interval_unit": "month", + "product_id": 901, + "archived_at": "2023-11-30T06:37:20-05:00", + "created_at": "2023-11-27T06:37:20-05:00", + "updated_at": "2023-11-27T06:37:20-05:00" + } + ] +} +``` + + +# Update Product Price Point + Use this endpoint to update a product price point. -Note: Custom product price points are not able to be updated. - -```go -UpdateProductPricePoint( - ctx context.Context, - productId interface{}, - pricePointId interface{}, +Note: Custom product price points are not able to be updated. + +```go +UpdateProductPricePoint( + ctx context.Context, + productId models.UpdateProductPricePointProductId, + pricePointId models.UpdateProductPricePointPricePointId, body *models.UpdateProductPricePointRequest) ( models.ApiResponse[models.ProductPricePointResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | `interface{}` | Template, Required | The id or handle of the product. When using the handle, it must be prefixed with `handle:` | -| `pricePointId` | `interface{}` | Template, Required | The id or handle of the price point. When using the handle, it must be prefixed with `handle:` | -| `body` | [`*models.UpdateProductPricePointRequest`](../../doc/models/update-product-price-point-request.md) | Body, Optional | - | - -## Response Type - -[`models.ProductPricePointResponse`](../../doc/models/product-price-point-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | [`models.UpdateProductPricePointProductId`](../../doc/models/containers/update-product-price-point-product-id.md) | Template, Required | This is a container for one-of cases. | +| `pricePointId` | [`models.UpdateProductPricePointPricePointId`](../../doc/models/containers/update-product-price-point-price-point-id.md) | Template, Required | This is a container for one-of cases. | +| `body` | [`*models.UpdateProductPricePointRequest`](../../doc/models/update-product-price-point-request.md) | Body, Optional | - | + +## Response Type + +[`models.ProductPricePointResponse`](../../doc/models/product-price-point-response.md) + +## Example Usage + +```go ctx := context.Background() -productId := interface{}("[key1, val1][key2, val2]") -pricePointId := interface{}("[key1, val1][key2, val2]") + +productId := models.UpdateProductPricePointProductIdContainer.FromNumber(124) + +pricePointId := models.UpdateProductPricePointPricePointIdContainer.FromNumber(188) bodyPricePoint := models.UpdateProductPricePoint{ Handle: models.ToPointer("educational"), @@ -240,69 +249,71 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_point": { - "id": 283, - "name": "Educational", - "handle": "educational", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "trial_price_in_cents": 4900, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "initial_charge_in_cents": 120000, - "initial_charge_after_trial": false, - "expiration_interval": 12, - "expiration_interval_unit": "month", - "product_id": 901, - "archived_at": "2023-11-30T06:37:20-05:00", - "created_at": "2023-11-27T06:37:20-05:00", - "updated_at": "2023-11-27T06:37:20-05:00" - } -} -``` - - -# Read Product Price Point - -Use this endpoint to retrieve details for a specific product price point. - -```go -ReadProductPricePoint( - ctx context.Context, - productId interface{}, - pricePointId interface{}, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_point": { + "id": 283, + "name": "Educational", + "handle": "educational", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "trial_price_in_cents": 4900, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "initial_charge_in_cents": 120000, + "initial_charge_after_trial": false, + "expiration_interval": 12, + "expiration_interval_unit": "month", + "product_id": 901, + "archived_at": "2023-11-30T06:37:20-05:00", + "created_at": "2023-11-27T06:37:20-05:00", + "updated_at": "2023-11-27T06:37:20-05:00" + } +} +``` + + +# Read Product Price Point + +Use this endpoint to retrieve details for a specific product price point. + +```go +ReadProductPricePoint( + ctx context.Context, + productId models.ReadProductPricePointProductId, + pricePointId models.ReadProductPricePointPricePointId, currencyPrices *bool) ( models.ApiResponse[models.ProductPricePointResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | `interface{}` | Template, Required | The id or handle of the product. When using the handle, it must be prefixed with `handle:` | -| `pricePointId` | `interface{}` | Template, Required | The id or handle of the price point. When using the handle, it must be prefixed with `handle:` | -| `currencyPrices` | `*bool` | Query, Optional | When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. | - -## Response Type - -[`models.ProductPricePointResponse`](../../doc/models/product-price-point-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | [`models.ReadProductPricePointProductId`](../../doc/models/containers/read-product-price-point-product-id.md) | Template, Required | This is a container for one-of cases. | +| `pricePointId` | [`models.ReadProductPricePointPricePointId`](../../doc/models/containers/read-product-price-point-price-point-id.md) | Template, Required | This is a container for one-of cases. | +| `currencyPrices` | `*bool` | Query, Optional | When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. | + +## Response Type + +[`models.ProductPricePointResponse`](../../doc/models/product-price-point-response.md) + +## Example Usage + +```go ctx := context.Background() -productId := interface{}("[key1, val1][key2, val2]") -pricePointId := interface{}("[key1, val1][key2, val2]") + +productId := models.ReadProductPricePointProductIdContainer.FromNumber(124) + +pricePointId := models.ReadProductPricePointPricePointIdContainer.FromNumber(188) apiResponse, err := productPricePointsController.ReadProductPricePoint(ctx, productId, pricePointId, nil) if err != nil { @@ -311,67 +322,69 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_point": { - "id": 283, - "name": "Educational", - "handle": "educational", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "trial_price_in_cents": 4900, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "initial_charge_in_cents": 120000, - "initial_charge_after_trial": false, - "expiration_interval": 12, - "expiration_interval_unit": "month", - "product_id": 901, - "archived_at": "2023-11-30T06:37:20-05:00", - "created_at": "2023-11-27T06:37:20-05:00", - "updated_at": "2023-11-27T06:37:20-05:00" - } -} -``` - - -# Archive Product Price Point - -Use this endpoint to archive a product price point. - -```go -ArchiveProductPricePoint( - ctx context.Context, - productId interface{}, - pricePointId interface{}) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_point": { + "id": 283, + "name": "Educational", + "handle": "educational", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "trial_price_in_cents": 4900, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "initial_charge_in_cents": 120000, + "initial_charge_after_trial": false, + "expiration_interval": 12, + "expiration_interval_unit": "month", + "product_id": 901, + "archived_at": "2023-11-30T06:37:20-05:00", + "created_at": "2023-11-27T06:37:20-05:00", + "updated_at": "2023-11-27T06:37:20-05:00" + } +} +``` + + +# Archive Product Price Point + +Use this endpoint to archive a product price point. + +```go +ArchiveProductPricePoint( + ctx context.Context, + productId models.ArchiveProductPricePointProductId, + pricePointId models.ArchiveProductPricePointPricePointId) ( models.ApiResponse[models.ProductPricePointResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | `interface{}` | Template, Required | The id or handle of the product. When using the handle, it must be prefixed with `handle:` | -| `pricePointId` | `interface{}` | Template, Required | The id or handle of the price point. When using the handle, it must be prefixed with `handle:` | - -## Response Type - -[`models.ProductPricePointResponse`](../../doc/models/product-price-point-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | [`models.ArchiveProductPricePointProductId`](../../doc/models/containers/archive-product-price-point-product-id.md) | Template, Required | This is a container for one-of cases. | +| `pricePointId` | [`models.ArchiveProductPricePointPricePointId`](../../doc/models/containers/archive-product-price-point-price-point-id.md) | Template, Required | This is a container for one-of cases. | + +## Response Type + +[`models.ProductPricePointResponse`](../../doc/models/product-price-point-response.md) + +## Example Usage + +```go ctx := context.Background() -productId := interface{}("[key1, val1][key2, val2]") -pricePointId := interface{}("[key1, val1][key2, val2]") + +productId := models.ArchiveProductPricePointProductIdContainer.FromNumber(124) + +pricePointId := models.ArchiveProductPricePointPricePointIdContainer.FromNumber(188) apiResponse, err := productPricePointsController.ArchiveProductPricePoint(ctx, productId, pricePointId) if err != nil { @@ -380,70 +393,70 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_point": { - "id": 283, - "name": "Educational", - "handle": "educational", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "trial_price_in_cents": 4900, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "initial_charge_in_cents": 120000, - "initial_charge_after_trial": false, - "expiration_interval": 12, - "expiration_interval_unit": "month", - "product_id": 901, - "archived_at": "2023-11-30T06:37:20-05:00", - "created_at": "2023-11-27T06:37:20-05:00", - "updated_at": "2023-11-27T06:37:20-05:00" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Unarchive Product Price Point - -Use this endpoint to unarchive an archived product price point. - -```go -UnarchiveProductPricePoint( - ctx context.Context, - productId int, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_point": { + "id": 283, + "name": "Educational", + "handle": "educational", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "trial_price_in_cents": 4900, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "initial_charge_in_cents": 120000, + "initial_charge_after_trial": false, + "expiration_interval": 12, + "expiration_interval_unit": "month", + "product_id": 901, + "archived_at": "2023-11-30T06:37:20-05:00", + "created_at": "2023-11-27T06:37:20-05:00", + "updated_at": "2023-11-27T06:37:20-05:00" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Unarchive Product Price Point + +Use this endpoint to unarchive an archived product price point. + +```go +UnarchiveProductPricePoint( + ctx context.Context, + productId int, pricePointId int) ( models.ApiResponse[models.ProductPricePointResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | `int` | Template, Required | The Chargify id of the product to which the price point belongs | -| `pricePointId` | `int` | Template, Required | The Chargify id of the product price point | - -## Response Type - -[`models.ProductPricePointResponse`](../../doc/models/product-price-point-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | `int` | Template, Required | The Chargify id of the product to which the price point belongs | +| `pricePointId` | `int` | Template, Required | The Chargify id of the product price point | + +## Response Type + +[`models.ProductPricePointResponse`](../../doc/models/product-price-point-response.md) + +## Example Usage + +```go ctx := context.Background() productId := 202 pricePointId := 10 @@ -455,66 +468,66 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_point": { - "id": 283, - "name": "Educational", - "handle": "educational", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "trial_price_in_cents": 4900, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "initial_charge_in_cents": 120000, - "initial_charge_after_trial": false, - "expiration_interval": 12, - "expiration_interval_unit": "month", - "product_id": 901, - "archived_at": "2023-11-30T06:37:20-05:00", - "created_at": "2023-11-27T06:37:20-05:00", - "updated_at": "2023-11-27T06:37:20-05:00" - } -} -``` - - -# Promote Product Price Point to Default - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_point": { + "id": 283, + "name": "Educational", + "handle": "educational", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "trial_price_in_cents": 4900, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "initial_charge_in_cents": 120000, + "initial_charge_after_trial": false, + "expiration_interval": 12, + "expiration_interval_unit": "month", + "product_id": 901, + "archived_at": "2023-11-30T06:37:20-05:00", + "created_at": "2023-11-27T06:37:20-05:00", + "updated_at": "2023-11-27T06:37:20-05:00" + } +} +``` + + +# Promote Product Price Point to Default + Use this endpoint to make a product price point the default for the product. -Note: Custom product price points are not able to be set as the default for a product. - -```go -PromoteProductPricePointToDefault( - ctx context.Context, - productId int, +Note: Custom product price points are not able to be set as the default for a product. + +```go +PromoteProductPricePointToDefault( + ctx context.Context, + productId int, pricePointId int) ( models.ApiResponse[models.ProductResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | `int` | Template, Required | The Chargify id of the product to which the price point belongs | -| `pricePointId` | `int` | Template, Required | The Chargify id of the product price point | - -## Response Type - -[`models.ProductResponse`](../../doc/models/product-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | `int` | Template, Required | The Chargify id of the product to which the price point belongs | +| `pricePointId` | `int` | Template, Required | The Chargify id of the product price point | + +## Response Type + +[`models.ProductResponse`](../../doc/models/product-response.md) + +## Example Usage + +```go ctx := context.Background() productId := 202 pricePointId := 10 @@ -526,91 +539,91 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "product": { - "id": 29778, - "name": "Educational", - "handle": "educational", - "description": null, - "accounting_code": null, - "request_credit_card": true, - "expiration_interval": 12, - "expiration_interval_unit": "month", - "created_at": "2023-12-01T06:56:12-05:00", - "updated_at": "2023-12-01T06:56:26-05:00", - "price_in_cents": 100, - "interval": 2, - "interval_unit": "month", - "initial_charge_in_cents": 120000, - "trial_price_in_cents": 4900, - "trial_interval": 1, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": true, - "return_params": null, - "taxable": false, - "update_return_url": null, - "tax_code": null, - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": null, - "default_product_price_point_id": 32395, - "request_billing_address": false, - "require_billing_address": false, - "require_shipping_address": false, - "use_site_exchange_rate": true, - "item_category": null, - "product_price_point_id": 32395, - "product_price_point_name": "Default", - "product_price_point_handle": "uuid:8c878f50-726e-013c-c71b-0286551bb34f", - "product_family": { - "id": 933860, - "name": "Acme Projects", - "description": "Amazing project management tool", - "handle": "acme-projects", - "accounting_code": null, - "created_at": "2023-12-01T06:56:12-05:00", - "updated_at": "2023-12-01T06:56:12-05:00" - }, - "public_signup_pages": [] - } -} -``` - - -# Bulk Create Product Price Points - -Use this endpoint to create multiple product price points in one request. - -```go -BulkCreateProductPricePoints( - ctx context.Context, - productId int, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "product": { + "id": 29778, + "name": "Educational", + "handle": "educational", + "description": null, + "accounting_code": null, + "request_credit_card": true, + "expiration_interval": 12, + "expiration_interval_unit": "month", + "created_at": "2023-12-01T06:56:12-05:00", + "updated_at": "2023-12-01T06:56:26-05:00", + "price_in_cents": 100, + "interval": 2, + "interval_unit": "month", + "initial_charge_in_cents": 120000, + "trial_price_in_cents": 4900, + "trial_interval": 1, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": true, + "return_params": null, + "taxable": false, + "update_return_url": null, + "tax_code": null, + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": null, + "default_product_price_point_id": 32395, + "request_billing_address": false, + "require_billing_address": false, + "require_shipping_address": false, + "use_site_exchange_rate": true, + "item_category": null, + "product_price_point_id": 32395, + "product_price_point_name": "Default", + "product_price_point_handle": "uuid:8c878f50-726e-013c-c71b-0286551bb34f", + "product_family": { + "id": 933860, + "name": "Acme Projects", + "description": "Amazing project management tool", + "handle": "acme-projects", + "accounting_code": null, + "created_at": "2023-12-01T06:56:12-05:00", + "updated_at": "2023-12-01T06:56:12-05:00" + }, + "public_signup_pages": [] + } +} +``` + + +# Bulk Create Product Price Points + +Use this endpoint to create multiple product price points in one request. + +```go +BulkCreateProductPricePoints( + ctx context.Context, + productId int, body *models.BulkCreateProductPricePointsRequest) ( models.ApiResponse[models.BulkCreateProductPricePointsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | `int` | Template, Required | The Chargify id of the product to which the price points belong | -| `body` | [`*models.BulkCreateProductPricePointsRequest`](../../doc/models/bulk-create-product-price-points-request.md) | Body, Optional | - | - -## Response Type - -[`models.BulkCreateProductPricePointsResponse`](../../doc/models/bulk-create-product-price-points-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | `int` | Template, Required | The Chargify id of the product to which the price points belong | +| `body` | [`*models.BulkCreateProductPricePointsRequest`](../../doc/models/bulk-create-product-price-points-request.md) | Body, Optional | - | + +## Response Type + +[`models.BulkCreateProductPricePointsResponse`](../../doc/models/bulk-create-product-price-points-response.md) + +## Example Usage + +```go ctx := context.Background() productId := 202 @@ -656,76 +669,76 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_points": [ - { - "id": 283, - "name": "Educational", - "handle": "educational", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "trial_price_in_cents": 4900, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "initial_charge_in_cents": 120000, - "initial_charge_after_trial": false, - "expiration_interval": 12, - "expiration_interval_unit": "month", - "product_id": 901, - "archived_at": "2023-11-30T06:37:20-05:00", - "created_at": "2023-11-27T06:37:20-05:00", - "updated_at": "2023-11-27T06:37:20-05:00" - } - ] -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | `ApiError` | - - -# Create Product Currency Prices - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_points": [ + { + "id": 283, + "name": "Educational", + "handle": "educational", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "trial_price_in_cents": 4900, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "initial_charge_in_cents": 120000, + "initial_charge_after_trial": false, + "expiration_interval": 12, + "expiration_interval_unit": "month", + "product_id": 901, + "archived_at": "2023-11-30T06:37:20-05:00", + "created_at": "2023-11-27T06:37:20-05:00", + "updated_at": "2023-11-27T06:37:20-05:00" + } + ] +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | `ApiError` | + + +# Create Product Currency Prices + This endpoint allows you to create currency prices for a given currency that has been defined on the site level in your settings. When creating currency prices, they need to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. -Note: Currency Prices are not able to be created for custom product price points. - -```go -CreateProductCurrencyPrices( - ctx context.Context, - productPricePointId int, +Note: Currency Prices are not able to be created for custom product price points. + +```go +CreateProductCurrencyPrices( + ctx context.Context, + productPricePointId int, body *models.CreateProductCurrencyPricesRequest) ( models.ApiResponse[models.CurrencyPricesResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productPricePointId` | `int` | Template, Required | The Chargify id of the product price point | -| `body` | [`*models.CreateProductCurrencyPricesRequest`](../../doc/models/create-product-currency-prices-request.md) | Body, Optional | - | - -## Response Type - -[`models.CurrencyPricesResponse`](../../doc/models/currency-prices-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productPricePointId` | `int` | Template, Required | The Chargify id of the product price point | +| `body` | [`*models.CreateProductCurrencyPricesRequest`](../../doc/models/create-product-currency-prices-request.md) | Body, Optional | - | + +## Response Type + +[`models.CurrencyPricesResponse`](../../doc/models/currency-prices-response.md) + +## Example Usage + +```go ctx := context.Background() productPricePointId := 234 @@ -759,64 +772,64 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "currency_prices": [ - { - "id": 100, - "currency": "EUR", - "price": 123, - "formatted_price": "€123,00", - "product_price_point_id": 32669, - "role": "baseline" - } - ] -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | - - -# Update Product Currency Prices - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "currency_prices": [ + { + "id": 100, + "currency": "EUR", + "price": 123, + "formatted_price": "€123,00", + "product_price_point_id": 32669, + "role": "baseline" + } + ] +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + + +# Update Product Currency Prices + This endpoint allows you to update the `price`s of currency prices for a given currency that exists on the product price point. When updating the pricing, it needs to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. -Note: Currency Prices are not able to be updated for custom product price points. - -```go -UpdateProductCurrencyPrices( - ctx context.Context, - productPricePointId int, +Note: Currency Prices are not able to be updated for custom product price points. + +```go +UpdateProductCurrencyPrices( + ctx context.Context, + productPricePointId int, body *models.UpdateCurrencyPricesRequest) ( models.ApiResponse[models.CurrencyPricesResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productPricePointId` | `int` | Template, Required | The Chargify id of the product price point | -| `body` | [`*models.UpdateCurrencyPricesRequest`](../../doc/models/update-currency-prices-request.md) | Body, Optional | - | - -## Response Type - -[`models.CurrencyPricesResponse`](../../doc/models/currency-prices-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productPricePointId` | `int` | Template, Required | The Chargify id of the product price point | +| `body` | [`*models.UpdateCurrencyPricesRequest`](../../doc/models/update-currency-prices-request.md) | Body, Optional | - | + +## Response Type + +[`models.CurrencyPricesResponse`](../../doc/models/currency-prices-response.md) + +## Example Usage + +```go ctx := context.Background() productPricePointId := 234 @@ -842,116 +855,120 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "currency_prices": [ - { - "id": 123, - "currency": "EUR", - "price": 100, - "formatted_price": "€123,00", - "product_price_point_id": 32669, - "role": "baseline" - } - ] -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | - - -# List All Product Price Points - -This method allows retrieval of a list of Products Price Points belonging to a Site. - -```go -ListAllProductPricePoints( - ctx context.Context,input ListAllProductPricePointsInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "currency_prices": [ + { + "id": 123, + "currency": "EUR", + "price": 100, + "formatted_price": "€123,00", + "product_price_point_id": 32669, + "role": "baseline" + } + ] +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + + +# List All Product Price Points + +This method allows retrieval of a list of Products Price Points belonging to a Site. + +```go +ListAllProductPricePoints( + ctx context.Context, + input ListAllProductPricePointsInput) ( models.ApiResponse[models.ListProductPricePointsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | -| `filterArchivedAt` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching price points only if archived_at is present or not. Use in query: `filter[archived_at]=not_null`. | -| `filterDateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query: `filter[date_field]=created_at`. | -| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `filterEndDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | -| `filterIds` | `[]int` | Query, Optional | Allows fetching price points with matching id based on provided values. Use in query: `filter[ids]=1,2,3`. | -| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `filterStartDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | -| `filterType` | [`[]models.PricePointType`](../../doc/models/price-point-type.md) | Query, Optional | Allows fetching price points with matching type. Use in query: `filter[type]=catalog,custom`. | -| `include` | [`*models.ListProductsPricePointsInclude`](../../doc/models/list-products-price-points-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include=currency_prices`. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | - -## Response Type - -[`models.ListProductPricePointsResponse`](../../doc/models/list-product-price-points-response.md) - -## Example Usage - -```go -ctx := context.Background()Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') -include := models.ListProductsPricePointsInclude("currency_prices") -page := 2 -perPage := 50 - -apiResponse, err := productPricePointsController.ListAllProductPricePoints(ctx, nil, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), &include, &page, &perPage) + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | +| `filterArchivedAt` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching price points only if archived_at is present or not. Use in query: `filter[archived_at]=not_null`. | +| `filterDateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. Use in query: `filter[date_field]=created_at`. | +| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `filterEndDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. | +| `filterIds` | `[]int` | Query, Optional | Allows fetching price points with matching id based on provided values. Use in query: `filter[ids]=1,2,3`. | +| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `filterStartDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. | +| `filterType` | [`[]models.PricePointType`](../../doc/models/price-point-type.md) | Query, Optional | Allows fetching price points with matching type. Use in query: `filter[type]=catalog,custom`. | +| `include` | [`*models.ListProductsPricePointsInclude`](../../doc/models/list-products-price-points-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include=currency_prices`. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | + +## Response Type + +[`models.ListProductPricePointsResponse`](../../doc/models/list-product-price-points-response.md) + +## Example Usage + +```go +ctx := context.Background() +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') +collectedInput := advancedbilling.ListAllProductPricePointsInput{ +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') Include: models.ToPointer(models.ListProductsPricePointsInclude("currency_prices")), + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := productPricePointsController.ListAllProductPricePoints(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "price_points": [ - { - "id": 0, - "name": "My pricepoint", - "handle": "handle", - "price_in_cents": 10, - "interval": 5, - "interval_unit": "month", - "trial_price_in_cents": 10, - "trial_interval": 1, - "trial_interval_unit": "month", - "trial_type": "payment_expected", - "introductory_offer": true, - "initial_charge_in_cents": 0, - "initial_charge_after_trial": true, - "expiration_interval": 0, - "expiration_interval_unit": "month", - "product_id": 1230, - "created_at": "2021-04-02T17:52:09-04:00", - "updated_at": "2021-04-02T17:52:09-04:00", - "use_site_exchange_rate": true - } - ] -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "price_points": [ + { + "id": 0, + "name": "My pricepoint", + "handle": "handle", + "price_in_cents": 10, + "interval": 5, + "interval_unit": "month", + "trial_price_in_cents": 10, + "trial_interval": 1, + "trial_interval_unit": "month", + "trial_type": "payment_expected", + "introductory_offer": true, + "initial_charge_in_cents": 0, + "initial_charge_after_trial": true, + "expiration_interval": 0, + "expiration_interval_unit": "month", + "product_id": 1230, + "created_at": "2021-04-02T17:52:09-04:00", + "updated_at": "2021-04-02T17:52:09-04:00", + "use_site_exchange_rate": true + } + ] +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/controllers/products.md b/doc/controllers/products.md index 0d3637db..2b51687a 100644 --- a/doc/controllers/products.md +++ b/doc/controllers/products.md @@ -1,53 +1,53 @@ -# Products - -```go -productsController := client.ProductsController() -``` - -## Class Name - -`ProductsController` - -## Methods - +# Products + +```go +productsController := client.ProductsController() +``` + +## Class Name + +`ProductsController` + +## Methods + * [Create Product](../../doc/controllers/products.md#create-product) * [Read Product](../../doc/controllers/products.md#read-product) * [Update Product](../../doc/controllers/products.md#update-product) * [Archive Product](../../doc/controllers/products.md#archive-product) * [Read Product by Handle](../../doc/controllers/products.md#read-product-by-handle) -* [List Products](../../doc/controllers/products.md#list-products) - - -# Create Product - +* [List Products](../../doc/controllers/products.md#list-products) + + +# Create Product + Use this method to create a product within your Chargify site. + [Products Documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405561405709) -+ [Changing a Subscription's Product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404225334669-Product-Changes-Migrations) - -```go -CreateProduct( - ctx context.Context, - productFamilyId int, ++ [Changing a Subscription's Product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404225334669-Product-Changes-Migrations) + +```go +CreateProduct( + ctx context.Context, + productFamilyId int, body *models.CreateOrUpdateProductRequest) ( models.ApiResponse[models.ProductResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the product belongs | -| `body` | [`*models.CreateOrUpdateProductRequest`](../../doc/models/create-or-update-product-request.md) | Body, Optional | - | - -## Response Type - -[`models.ProductResponse`](../../doc/models/product-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productFamilyId` | `int` | Template, Required | The Chargify id of the product family to which the product belongs | +| `body` | [`*models.CreateOrUpdateProductRequest`](../../doc/models/create-or-update-product-request.md) | Body, Optional | - | + +## Response Type + +[`models.ProductResponse`](../../doc/models/product-response.md) + +## Example Usage + +```go ctx := context.Background() productFamilyId := 140 @@ -75,90 +75,90 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "product": { - "id": 4364984, - "name": "Gold Plan", - "handle": "gold", - "description": "This is our gold plan.", - "accounting_code": "123", - "request_credit_card": true, - "created_at": "2016-11-04T16:31:15-04:00", - "updated_at": "2016-11-04T16:31:15-04:00", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "expiration_interval_unit": null, - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": null, - "archived_at": null, - "require_credit_card": true, - "return_params": null, - "taxable": false, - "update_return_url": null, - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": null, - "product_family": { - "id": 527890, - "name": "Acme Projects", - "description": "", - "handle": "billing-plans", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 301078, - "return_url": null, - "return_params": null, - "url": "https://general-goods.chargify.com/subscribe/ftgbpq7f5qpr/gold" - } - ], - "product_price_point_name": "Default" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Read Product - -This endpoint allows you to read the current details of a product that you've created in Chargify. - -```go -ReadProduct( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "product": { + "id": 4364984, + "name": "Gold Plan", + "handle": "gold", + "description": "This is our gold plan.", + "accounting_code": "123", + "request_credit_card": true, + "created_at": "2016-11-04T16:31:15-04:00", + "updated_at": "2016-11-04T16:31:15-04:00", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "expiration_interval_unit": null, + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": null, + "archived_at": null, + "require_credit_card": true, + "return_params": null, + "taxable": false, + "update_return_url": null, + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": null, + "product_family": { + "id": 527890, + "name": "Acme Projects", + "description": "", + "handle": "billing-plans", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 301078, + "return_url": null, + "return_params": null, + "url": "https://general-goods.chargify.com/subscribe/ftgbpq7f5qpr/gold" + } + ], + "product_price_point_name": "Default" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Read Product + +This endpoint allows you to read the current details of a product that you've created in Chargify. + +```go +ReadProduct( + ctx context.Context, productId int) ( models.ApiResponse[models.ProductResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | `int` | Template, Required | The Chargify id of the product | - -## Response Type - -[`models.ProductResponse`](../../doc/models/product-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | `int` | Template, Required | The Chargify id of the product | + +## Response Type + +[`models.ProductResponse`](../../doc/models/product-response.md) + +## Example Usage + +```go ctx := context.Background() productId := 202 @@ -169,56 +169,56 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "product": { - "id": 4535635, - "name": "Paid Annual Seats", - "handle": "paid-annual-seats", - "description": "Paid annual seats for our commercial enterprise product", - "accounting_code": "paid-annual-seats", - "request_credit_card": true, - "expiration_interval": 1, - "expiration_interval_unit": "day", - "created_at": "2017-08-25T10:25:31-05:00", - "updated_at": "2018-01-16T12:58:04-06:00", - "price_in_cents": 10000, - "interval": 12, - "interval_unit": "month", - "initial_charge_in_cents": 4900, - "trial_price_in_cents": 1000, - "trial_interval": 14, - "trial_interval_unit": "day", - "archived_at": null, - "require_credit_card": true, - "return_params": "id={subscription_id}&ref={customer_reference}", - "taxable": true, - "update_return_url": "http://www.example.com", - "tax_code": "D0000000", - "initial_charge_after_trial": false, - "version_number": 4, - "update_return_params": "id={subscription_id}&ref={customer_reference}", - "product_family": { - "id": 1025627, - "name": "Acme Products", - "description": "", - "handle": "acme-products", - "accounting_code": null - }, - "public_signup_pages": [], - "product_price_point_name": "Default" - } -} -``` - - -# Update Product - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "product": { + "id": 4535635, + "name": "Paid Annual Seats", + "handle": "paid-annual-seats", + "description": "Paid annual seats for our commercial enterprise product", + "accounting_code": "paid-annual-seats", + "request_credit_card": true, + "expiration_interval": 1, + "expiration_interval_unit": "day", + "created_at": "2017-08-25T10:25:31-05:00", + "updated_at": "2018-01-16T12:58:04-06:00", + "price_in_cents": 10000, + "interval": 12, + "interval_unit": "month", + "initial_charge_in_cents": 4900, + "trial_price_in_cents": 1000, + "trial_interval": 14, + "trial_interval_unit": "day", + "archived_at": null, + "require_credit_card": true, + "return_params": "id={subscription_id}&ref={customer_reference}", + "taxable": true, + "update_return_url": "http://www.example.com", + "tax_code": "D0000000", + "initial_charge_after_trial": false, + "version_number": 4, + "update_return_params": "id={subscription_id}&ref={customer_reference}", + "product_family": { + "id": 1025627, + "name": "Acme Products", + "description": "", + "handle": "acme-products", + "accounting_code": null + }, + "public_signup_pages": [], + "product_price_point_name": "Default" + } +} +``` + + +# Update Product + Use this method to change aspects of an existing product. ### Input Attributes Update Notes @@ -227,31 +227,31 @@ Use this method to change aspects of an existing product. ### Product Price Point -Updating a product using this endpoint will create a new price point and set it as the default price point for this product. If you should like to update an existing product price point, that must be done separately. - -```go -UpdateProduct( - ctx context.Context, - productId int, +Updating a product using this endpoint will create a new price point and set it as the default price point for this product. If you should like to update an existing product price point, that must be done separately. + +```go +UpdateProduct( + ctx context.Context, + productId int, body *models.CreateOrUpdateProductRequest) ( models.ApiResponse[models.ProductResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | `int` | Template, Required | The Chargify id of the product | -| `body` | [`*models.CreateOrUpdateProductRequest`](../../doc/models/create-or-update-product-request.md) | Body, Optional | - | - -## Response Type - -[`models.ProductResponse`](../../doc/models/product-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | `int` | Template, Required | The Chargify id of the product | +| `body` | [`*models.CreateOrUpdateProductRequest`](../../doc/models/create-or-update-product-request.md) | Body, Optional | - | + +## Response Type + +[`models.ProductResponse`](../../doc/models/product-response.md) + +## Example Usage + +```go ctx := context.Background() productId := 202 @@ -262,91 +262,91 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "product": { - "id": 4365034, - "name": "Platinum Plan", - "handle": "platinum", - "description": "This is our platinum plan.", - "accounting_code": "123", - "request_credit_card": true, - "created_at": "2016-11-04T16:34:29-04:00", - "updated_at": "2016-11-04T16:37:11-04:00", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": null, - "archived_at": null, - "require_credit_card": true, - "return_params": null, - "taxable": false, - "update_return_url": null, - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": null, - "product_family": { - "id": 527890, - "name": "Acme Projects", - "description": "", - "handle": "billing-plans", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 301079, - "return_url": null, - "return_params": null, - "url": "https://general-goods.chargify.com/subscribe/wgyd96tb5pj9/platinum" - } - ], - "product_price_point_name": "Original" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Archive Product - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "product": { + "id": 4365034, + "name": "Platinum Plan", + "handle": "platinum", + "description": "This is our platinum plan.", + "accounting_code": "123", + "request_credit_card": true, + "created_at": "2016-11-04T16:34:29-04:00", + "updated_at": "2016-11-04T16:37:11-04:00", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": null, + "archived_at": null, + "require_credit_card": true, + "return_params": null, + "taxable": false, + "update_return_url": null, + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": null, + "product_family": { + "id": 527890, + "name": "Acme Projects", + "description": "", + "handle": "billing-plans", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 301079, + "return_url": null, + "return_params": null, + "url": "https://general-goods.chargify.com/subscribe/wgyd96tb5pj9/platinum" + } + ], + "product_price_point_name": "Original" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Archive Product + Sending a DELETE request to this endpoint will archive the product. All current subscribers will be unffected; their subscription/purchase will continue to be charged monthly. -This will restrict the option to chose the product for purchase via the Billing Portal, as well as disable Public Signup Pages for the product. - -```go -ArchiveProduct( - ctx context.Context, +This will restrict the option to chose the product for purchase via the Billing Portal, as well as disable Public Signup Pages for the product. + +```go +ArchiveProduct( + ctx context.Context, productId int) ( models.ApiResponse[models.ProductResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `productId` | `int` | Template, Required | The Chargify id of the product | - -## Response Type - -[`models.ProductResponse`](../../doc/models/product-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `productId` | `int` | Template, Required | The Chargify id of the product | + +## Response Type + +[`models.ProductResponse`](../../doc/models/product-response.md) + +## Example Usage + +```go ctx := context.Background() productId := 202 @@ -357,85 +357,85 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "product": { - "id": 4535638, - "name": "Business Monthly", - "handle": null, - "description": "Business Monthly", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2017-08-25T10:25:31-05:00", - "updated_at": "2018-01-16T13:02:44-06:00", - "price_in_cents": 4900, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": 0, - "trial_interval": 1, - "trial_interval_unit": "day", - "archived_at": "2018-01-16T13:02:44-06:00", - "require_credit_card": false, - "return_params": "", - "taxable": false, - "update_return_url": "", - "tax_code": "", - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": "", - "product_family": { - "id": 1025627, - "name": "Acme Products", - "description": "", - "handle": "acme-products", - "accounting_code": null - }, - "public_signup_pages": [], - "product_price_point_name": "Default" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Read Product by Handle - -This method allows to retrieve a Product object by its `api_handle`. - -```go -ReadProductByHandle( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "product": { + "id": 4535638, + "name": "Business Monthly", + "handle": null, + "description": "Business Monthly", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2017-08-25T10:25:31-05:00", + "updated_at": "2018-01-16T13:02:44-06:00", + "price_in_cents": 4900, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": 0, + "trial_interval": 1, + "trial_interval_unit": "day", + "archived_at": "2018-01-16T13:02:44-06:00", + "require_credit_card": false, + "return_params": "", + "taxable": false, + "update_return_url": "", + "tax_code": "", + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": "", + "product_family": { + "id": 1025627, + "name": "Acme Products", + "description": "", + "handle": "acme-products", + "accounting_code": null + }, + "public_signup_pages": [], + "product_price_point_name": "Default" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Read Product by Handle + +This method allows to retrieve a Product object by its `api_handle`. + +```go +ReadProductByHandle( + ctx context.Context, apiHandle string) ( models.ApiResponse[models.ProductResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `apiHandle` | `string` | Template, Required | The handle of the product | - -## Response Type - -[`models.ProductResponse`](../../doc/models/product-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `apiHandle` | `string` | Template, Required | The handle of the product | + +## Response Type + +[`models.ProductResponse`](../../doc/models/product-response.md) + +## Example Usage + +```go ctx := context.Background() apiHandle := "api_handle6" @@ -446,186 +446,190 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "product": { - "id": 3903594, - "name": "No cost product", - "handle": "no-cost-product", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2016-09-02T17:11:29-04:00", - "updated_at": "2016-11-30T11:46:13-05:00", - "price_in_cents": 0, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": 5, - "trial_interval": 1, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": false, - "return_params": "reference=5678", - "taxable": false, - "update_return_url": "", - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": "reference=5678", - "product_family": { - "id": 527890, - "name": "Acme Projects", - "description": "", - "handle": "billing-plans", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 281174, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/xgdxtk4vhtbz/no-cost-product" - }, - { - "id": 282270, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/xxqmrgtsbd9k/no-cost-product" - }, - { - "id": 291587, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/pvhwss7zjjnh/no-cost-product" - }, - { - "id": 294832, - "return_url": "http://www.example.com/", - "return_params": "engine=md7a", - "url": "https://general-goods.chargify.com/subscribe/m6tbcq4mcgpw/no-cost-product" - } - ], - "product_price_point_name": "Default" - } -} -``` - - -# List Products - -This method allows to retrieve a list of Products belonging to a Site. - -```go -ListProducts( - ctx context.Context,input ListProductsInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "product": { + "id": 3903594, + "name": "No cost product", + "handle": "no-cost-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2016-09-02T17:11:29-04:00", + "updated_at": "2016-11-30T11:46:13-05:00", + "price_in_cents": 0, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": 5, + "trial_interval": 1, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": false, + "return_params": "reference=5678", + "taxable": false, + "update_return_url": "", + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": "reference=5678", + "product_family": { + "id": 527890, + "name": "Acme Projects", + "description": "", + "handle": "billing-plans", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 281174, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/xgdxtk4vhtbz/no-cost-product" + }, + { + "id": 282270, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/xxqmrgtsbd9k/no-cost-product" + }, + { + "id": 291587, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/pvhwss7zjjnh/no-cost-product" + }, + { + "id": 294832, + "return_url": "http://www.example.com/", + "return_params": "engine=md7a", + "url": "https://general-goods.chargify.com/subscribe/m6tbcq4mcgpw/no-cost-product" + } + ], + "product_price_point_name": "Default" + } +} +``` + + +# List Products + +This method allows to retrieve a list of Products belonging to a Site. + +```go +ListProducts( + ctx context.Context, + input ListProductsInput) ( models.ApiResponse[[]models.ProductResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | -| `endDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `endDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. | -| `startDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `startDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `includeArchived` | `*bool` | Query, Optional | Include archived products. Use in query: `include_archived=true`. | -| `include` | [`*models.ListProductsInclude`](../../doc/models/list-products-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=prepaid_product_price_point`. | -| `filterPrepaidProductPricePointProductPricePointId` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching products only if a prepaid product price point is present or not. To use this filter you also have to include the following param in the request `include=prepaid_product_price_point`. Use in query `filter[prepaid_product_price_point][product_price_point_id]=not_null`. | -| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching products with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | - -## Response Type - -[`[]models.ProductResponse`](../../doc/models/product-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `dateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `date_field=created_at`. | +| `endDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `endDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. | +| `startDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `startDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `includeArchived` | `*bool` | Query, Optional | Include archived products. Use in query: `include_archived=true`. | +| `include` | [`*models.ListProductsInclude`](../../doc/models/list-products-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=prepaid_product_price_point`. | +| `filterPrepaidProductPricePointProductPricePointId` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching products only if a prepaid product price point is present or not. To use this filter you also have to include the following param in the request `include=prepaid_product_price_point`. Use in query `filter[prepaid_product_price_point][product_price_point_id]=not_null`. | +| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching products with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. | + +## Response Type + +[`[]models.ProductResponse`](../../doc/models/product-response.md) + +## Example Usage + +```go ctx := context.Background() -dateField := models.BasicDateField("updated_at") -page := 2 -perPage := 50 -includeArchived := true -include := models.ListProductsInclude("prepaid_product_price_point")Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') -apiResponse, err := productsController.ListProducts(ctx, &dateField, nil, nil, nil, nil, &page, &perPage, &includeArchived, &include, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key')) +collectedInput := advancedbilling.ListProductsInput{ + DateField: models.ToPointer(models.BasicDateField("updated_at")), + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + IncludeArchived: models.ToPointer(true), + Include: models.ToPointer(models.ListProductsInclude("prepaid_product_price_point")), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := productsController.ListProducts(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "product": { - "id": 0, - "name": "string", - "handle": "string", - "description": "string", - "accounting_code": "string", - "request_credit_card": true, - "expiration_interval": 0, - "expiration_interval_unit": "month", - "created_at": "2023-11-23T10:28:34-05:00", - "updated_at": "2023-11-23T10:28:34-05:00", - "price_in_cents": 0, - "interval": 0, - "interval_unit": "month", - "initial_charge_in_cents": 0, - "trial_price_in_cents": 0, - "trial_interval": 0, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": true, - "return_params": "string", - "taxable": true, - "update_return_url": "string", - "initial_charge_after_trial": true, - "version_number": 0, - "update_return_params": "string", - "product_family": { - "id": 0, - "name": "string", - "handle": "string", - "accounting_code": null, - "description": "string", - "created_at": "2021-05-05T16:00:21-04:00", - "updated_at": "2021-05-05T16:00:21-04:00" - }, - "public_signup_pages": [ - { - "id": 0, - "return_url": "string", - "return_params": "string", - "url": "string" - } - ], - "product_price_point_name": "string", - "request_billing_address": true, - "require_billing_address": true, - "require_shipping_address": true, - "use_site_exchange_rate": true, - "tax_code": "string", - "default_product_price_point_id": 0 - } - } -] -``` - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "product": { + "id": 0, + "name": "string", + "handle": "string", + "description": "string", + "accounting_code": "string", + "request_credit_card": true, + "expiration_interval": 0, + "expiration_interval_unit": "month", + "created_at": "2023-11-23T10:28:34-05:00", + "updated_at": "2023-11-23T10:28:34-05:00", + "price_in_cents": 0, + "interval": 0, + "interval_unit": "month", + "initial_charge_in_cents": 0, + "trial_price_in_cents": 0, + "trial_interval": 0, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": true, + "return_params": "string", + "taxable": true, + "update_return_url": "string", + "initial_charge_after_trial": true, + "version_number": 0, + "update_return_params": "string", + "product_family": { + "id": 0, + "name": "string", + "handle": "string", + "accounting_code": null, + "description": "string", + "created_at": "2021-05-05T16:00:21-04:00", + "updated_at": "2021-05-05T16:00:21-04:00" + }, + "public_signup_pages": [ + { + "id": 0, + "return_url": "string", + "return_params": "string", + "url": "string" + } + ], + "product_price_point_name": "string", + "request_billing_address": true, + "require_billing_address": true, + "require_shipping_address": true, + "use_site_exchange_rate": true, + "tax_code": "string", + "default_product_price_point_id": 0 + } + } +] +``` + diff --git a/doc/controllers/proforma-invoices.md b/doc/controllers/proforma-invoices.md index df9bcdb3..fda31d9f 100644 --- a/doc/controllers/proforma-invoices.md +++ b/doc/controllers/proforma-invoices.md @@ -1,15 +1,15 @@ -# Proforma Invoices - -```go -proformaInvoicesController := client.ProformaInvoicesController() -``` - -## Class Name - -`ProformaInvoicesController` - -## Methods - +# Proforma Invoices + +```go +proformaInvoicesController := client.ProformaInvoicesController() +``` + +## Class Name + +`ProformaInvoicesController` + +## Methods + * [Create Consolidated Proforma Invoice](../../doc/controllers/proforma-invoices.md#create-consolidated-proforma-invoice) * [List Subscription Group Proforma Invoices](../../doc/controllers/proforma-invoices.md#list-subscription-group-proforma-invoices) * [Read Proforma Invoice](../../doc/controllers/proforma-invoices.md#read-proforma-invoice) @@ -18,40 +18,40 @@ proformaInvoicesController := client.ProformaInvoicesController() * [Void Proforma Invoice](../../doc/controllers/proforma-invoices.md#void-proforma-invoice) * [Preview Proforma Invoice](../../doc/controllers/proforma-invoices.md#preview-proforma-invoice) * [Create Signup Proforma Invoice](../../doc/controllers/proforma-invoices.md#create-signup-proforma-invoice) -* [Preview Signup Proforma Invoice](../../doc/controllers/proforma-invoices.md#preview-signup-proforma-invoice) - - -# Create Consolidated Proforma Invoice - +* [Preview Signup Proforma Invoice](../../doc/controllers/proforma-invoices.md#preview-signup-proforma-invoice) + + +# Create Consolidated Proforma Invoice + This endpoint will trigger the creation of a consolidated proforma invoice asynchronously. It will return a 201 with no message, or a 422 with any errors. To find and view the new consolidated proforma invoice, you may poll the subscription group listing for proforma invoices; only one consolidated proforma invoice may be created per group at a time. If the information becomes outdated, simply void the old consolidated proforma invoice and generate a new one. ## Restrictions -Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be prepaid, and must be in a live state. - -```go -CreateConsolidatedProformaInvoice( - ctx context.Context, +Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be prepaid, and must be in a live state. + +```go +CreateConsolidatedProformaInvoice( + ctx context.Context, uid string) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -60,103 +60,101 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Subscription Group Proforma Invoices - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Subscription Group Proforma Invoices + Only proforma invoices with a `consolidation_level` of parent are returned. -By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to true. - -```go -ListSubscriptionGroupProformaInvoices( - ctx context.Context,input ListSubscriptionGroupProformaInvoicesInput) ( +By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to true. + +```go +ListSubscriptionGroupProformaInvoices( + ctx context.Context, + input ListSubscriptionGroupProformaInvoicesInput) ( models.ApiResponse[models.ListProformaInvoicesResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `lineItems` | `*bool` | Query, Optional | Include line items data | -| `discounts` | `*bool` | Query, Optional | Include discounts data | -| `taxes` | `*bool` | Query, Optional | Include taxes data | -| `credits` | `*bool` | Query, Optional | Include credits data | -| `payments` | `*bool` | Query, Optional | Include payments data | -| `customFields` | `*bool` | Query, Optional | Include custom fields data | - -## Response Type - -[`models.ListProformaInvoicesResponse`](../../doc/models/list-proforma-invoices-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `lineItems` | `*bool` | Query, Optional | Include line items data | +| `discounts` | `*bool` | Query, Optional | Include discounts data | +| `taxes` | `*bool` | Query, Optional | Include taxes data | +| `credits` | `*bool` | Query, Optional | Include credits data | +| `payments` | `*bool` | Query, Optional | Include payments data | +| `customFields` | `*bool` | Query, Optional | Include custom fields data | + +## Response Type + +[`models.ListProformaInvoicesResponse`](../../doc/models/list-proforma-invoices-response.md) + +## Example Usage + +```go ctx := context.Background() -uid := "uid0" -lineItems := false -discounts := false -taxes := false -credits := false -payments := false -customFields := false - -apiResponse, err := proformaInvoicesController.ListSubscriptionGroupProformaInvoices(ctx, uid, &lineItems, &discounts, &taxes, &credits, &payments, &customFields) + +collectedInput := advancedbilling.ListSubscriptionGroupProformaInvoicesInput{ + Uid: "uid0", +} + +apiResponse, err := proformaInvoicesController.ListSubscriptionGroupProformaInvoices(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Read Proforma Invoice - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Read Proforma Invoice + Use this endpoint to read the details of an existing proforma invoice. ## Restrictions -Proforma invoices are only available on Relationship Invoicing sites. - -```go -ReadProformaInvoice( - ctx context.Context, +Proforma invoices are only available on Relationship Invoicing sites. + +```go +ReadProformaInvoice( + ctx context.Context, proformaInvoiceUid string) ( models.ApiResponse[models.ProformaInvoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `proformaInvoiceUid` | `string` | Template, Required | The uid of the proforma invoice | - -## Response Type - -[`models.ProformaInvoice`](../../doc/models/proforma-invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `proformaInvoiceUid` | `string` | Template, Required | The uid of the proforma invoice | + +## Response Type + +[`models.ProformaInvoice`](../../doc/models/proforma-invoice.md) + +## Example Usage + +```go ctx := context.Background() proformaInvoiceUid := "proforma_invoice_uid4" @@ -167,47 +165,47 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Create Proforma Invoice - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Create Proforma Invoice + This endpoint will create a proforma invoice and return it as a response. If the information becomes outdated, simply void the old proforma invoice and generate a new one. If you would like to preview the next billing amounts without generating a full proforma invoice, please use the renewal preview endpoint. ## Restrictions -Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be in a group, must not be prepaid, and must be in a live state. - -```go -CreateProformaInvoice( - ctx context.Context, +Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be in a group, must not be prepaid, and must be in a live state. + +```go +CreateProformaInvoice( + ctx context.Context, subscriptionId int) ( models.ApiResponse[models.ProformaInvoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -[`models.ProformaInvoice`](../../doc/models/proforma-invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +[`models.ProformaInvoice`](../../doc/models/proforma-invoice.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -218,77 +216,75 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Proforma Invoices - -By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, or `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. - -```go -ListProformaInvoices( - ctx context.Context,input ListProformaInvoicesInput) ( +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Proforma Invoices + +By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, or `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. + +```go +ListProformaInvoices( + ctx context.Context, + input ListProformaInvoicesInput) ( models.ApiResponse[models.ListProformaInvoicesResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `startDate` | `*string` | Query, Optional | The beginning date range for the invoice's Due Date, in the YYYY-MM-DD format. | -| `endDate` | `*string` | Query, Optional | The ending date range for the invoice's Due Date, in the YYYY-MM-DD format. | -| `status` | [`*models.ProformaInvoiceStatus`](../../doc/models/proforma-invoice-status.md) | Query, Optional | The current status of the invoice. Allowed Values: draft, open, paid, pending, voided | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned invoices. | -| `lineItems` | `*bool` | Query, Optional | Include line items data | -| `discounts` | `*bool` | Query, Optional | Include discounts data | -| `taxes` | `*bool` | Query, Optional | Include taxes data | -| `credits` | `*bool` | Query, Optional | Include credits data | -| `payments` | `*bool` | Query, Optional | Include payments data | -| `customFields` | `*bool` | Query, Optional | Include custom fields data | - -## Response Type - -[`models.ListProformaInvoicesResponse`](../../doc/models/list-proforma-invoices-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `startDate` | `*string` | Query, Optional | The beginning date range for the invoice's Due Date, in the YYYY-MM-DD format. | +| `endDate` | `*string` | Query, Optional | The ending date range for the invoice's Due Date, in the YYYY-MM-DD format. | +| `status` | [`*models.ProformaInvoiceStatus`](../../doc/models/proforma-invoice-status.md) | Query, Optional | The current status of the invoice. Allowed Values: draft, open, paid, pending, voided | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `direction` | [`*models.Direction`](../../doc/models/direction.md) | Query, Optional | The sort direction of the returned invoices. | +| `lineItems` | `*bool` | Query, Optional | Include line items data | +| `discounts` | `*bool` | Query, Optional | Include discounts data | +| `taxes` | `*bool` | Query, Optional | Include taxes data | +| `credits` | `*bool` | Query, Optional | Include credits data | +| `payments` | `*bool` | Query, Optional | Include payments data | +| `customFields` | `*bool` | Query, Optional | Include custom fields data | + +## Response Type + +[`models.ListProformaInvoicesResponse`](../../doc/models/list-proforma-invoices-response.md) + +## Example Usage + +```go ctx := context.Background() -subscriptionId := 222 -page := 2 -perPage := 50 -direction := models.Direction("desc") -lineItems := false -discounts := false -taxes := false -credits := false -payments := false -customFields := false - -apiResponse, err := proformaInvoicesController.ListProformaInvoices(ctx, subscriptionId, nil, nil, nil, &page, &perPage, &direction, &lineItems, &discounts, &taxes, &credits, &payments, &customFields) + +collectedInput := advancedbilling.ListProformaInvoicesInput{ + SubscriptionId: 222, + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + Direction: models.ToPointer(models.Direction("desc")), +} + +apiResponse, err := proformaInvoicesController.ListProformaInvoices(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Void Proforma Invoice - +} +``` + + +# Void Proforma Invoice + This endpoint will void a proforma invoice that has the status "draft". ## Restrictions @@ -297,31 +293,31 @@ Proforma invoices are only available on Relationship Invoicing sites. Only proforma invoices that have the appropriate status may be reopened. If the invoice identified by {uid} does not have the appropriate status, the response will have HTTP status code 422 and an error message. -A reason for the void operation is required to be included in the request body. If one is not provided, the response will have HTTP status code 422 and an error message. - -```go -VoidProformaInvoice( - ctx context.Context, - proformaInvoiceUid string, +A reason for the void operation is required to be included in the request body. If one is not provided, the response will have HTTP status code 422 and an error message. + +```go +VoidProformaInvoice( + ctx context.Context, + proformaInvoiceUid string, body *models.VoidInvoiceRequest) ( models.ApiResponse[models.ProformaInvoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `proformaInvoiceUid` | `string` | Template, Required | The uid of the proforma invoice | -| `body` | [`*models.VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | - -## Response Type - -[`models.ProformaInvoice`](../../doc/models/proforma-invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `proformaInvoiceUid` | `string` | Template, Required | The uid of the proforma invoice | +| `body` | [`*models.VoidInvoiceRequest`](../../doc/models/void-invoice-request.md) | Body, Optional | - | + +## Response Type + +[`models.ProformaInvoice`](../../doc/models/proforma-invoice.md) + +## Example Usage + +```go ctx := context.Background() proformaInvoiceUid := "proforma_invoice_uid4" @@ -332,48 +328,48 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Preview Proforma Invoice - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Preview Proforma Invoice + Return a preview of the data that will be included on a given subscription's proforma invoice if one were to be generated. It will have similar line items and totals as a renewal preview, but the response will be presented in the format of a proforma invoice. Consequently it will include additional information such as the name and addresses that will appear on the proforma invoice. The preview endpoint is subject to all the same conditions as the proforma invoice endpoint. For example, previews are only available on the Relationship Invoicing architecture, and previews cannot be made for end-of-life subscriptions. If all the data returned in the preview is as expected, you may then create a static proforma invoice and send it to your customer. The data within a preview will not be saved and will not be accessible after the call is made. -Alternatively, if you have some proforma invoices already, you may make a preview call to determine whether any billing information for the subscription's upcoming renewal has changed. - -```go -PreviewProformaInvoice( - ctx context.Context, +Alternatively, if you have some proforma invoices already, you may make a preview call to determine whether any billing information for the subscription's upcoming renewal has changed. + +```go +PreviewProformaInvoice( + ctx context.Context, subscriptionId int) ( models.ApiResponse[models.ProformaInvoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -[`models.ProformaInvoice`](../../doc/models/proforma-invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +[`models.ProformaInvoice`](../../doc/models/proforma-invoice.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -384,48 +380,48 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Create Signup Proforma Invoice - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Create Signup Proforma Invoice + This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoices or preview prepaid subscriptions. Create a proforma invoice to preview costs before a subscription's signup. Like other proforma invoices, it can be emailed to the customer, voided, and publicly viewed on the chargifypay domain. Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. -A product and customer first name, last name, and email are the minimum requirements. We recommend associating the proforma invoice with a customer_id to easily find their proforma invoices, since the subscription_id will always be blank. - -```go -CreateSignupProformaInvoice( - ctx context.Context, +A product and customer first name, last name, and email are the minimum requirements. We recommend associating the proforma invoice with a customer_id to easily find their proforma invoices, since the subscription_id will always be blank. + +```go +CreateSignupProformaInvoice( + ctx context.Context, body *models.CreateSubscriptionRequest) ( models.ApiResponse[models.ProformaInvoice], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | - -## Response Type - -[`models.ProformaInvoice`](../../doc/models/proforma-invoice.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | + +## Response Type + +[`models.ProformaInvoice`](../../doc/models/proforma-invoice.md) + +## Example Usage + +```go ctx := context.Background() bodySubscriptionCustomerAttributes := models.CustomerAttributes{ @@ -450,50 +446,50 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 400 | Bad Request | [`ProformaBadRequestErrorResponseException`](../../doc/models/proforma-bad-request-error-response-exception.md) | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | - - -# Preview Signup Proforma Invoice - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 400 | Bad Request | [`ProformaBadRequestErrorResponseException`](../../doc/models/proforma-bad-request-error-response-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + + +# Preview Signup Proforma Invoice + This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoice previews or preview prepaid subscriptions. Create a signup preview in the format of a proforma invoice to preview costs before a subscription's signup. You have the option of optionally previewing the first renewal's costs as well. The proforma invoice preview will not be persisted. Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. -A product and customer first name, last name, and email are the minimum requirements. - -```go -PreviewSignupProformaInvoice( - ctx context.Context, - include *models.CreateSignupProformaPreviewInclude, +A product and customer first name, last name, and email are the minimum requirements. + +```go +PreviewSignupProformaInvoice( + ctx context.Context, + include *models.CreateSignupProformaPreviewInclude, body *models.CreateSubscriptionRequest) ( models.ApiResponse[models.SignupProformaPreviewResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `include` | [`*models.CreateSignupProformaPreviewInclude`](../../doc/models/create-signup-proforma-preview-include.md) | Query, Optional | Choose to include a proforma invoice preview for the first renewal. Use in query `include=next_proforma_invoice`. | -| `body` | [`*models.CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | - -## Response Type - -[`models.SignupProformaPreviewResponse`](../../doc/models/signup-proforma-preview-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `include` | [`*models.CreateSignupProformaPreviewInclude`](../../doc/models/create-signup-proforma-preview-include.md) | Query, Optional | Choose to include a proforma invoice preview for the first renewal. Use in query `include=next_proforma_invoice`. | +| `body` | [`*models.CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | + +## Response Type + +[`models.SignupProformaPreviewResponse`](../../doc/models/signup-proforma-preview-response.md) + +## Example Usage + +```go ctx := context.Background() bodySubscriptionCustomerAttributes := models.CustomerAttributes{ @@ -518,13 +514,13 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 400 | Bad Request | [`ProformaBadRequestErrorResponseException`](../../doc/models/proforma-bad-request-error-response-exception.md) | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 400 | Bad Request | [`ProformaBadRequestErrorResponseException`](../../doc/models/proforma-bad-request-error-response-exception.md) | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + diff --git a/doc/controllers/reason-codes.md b/doc/controllers/reason-codes.md index 167ebce0..6fd1222a 100644 --- a/doc/controllers/reason-codes.md +++ b/doc/controllers/reason-codes.md @@ -1,24 +1,24 @@ -# Reason Codes - -```go -reasonCodesController := client.ReasonCodesController() -``` - -## Class Name - -`ReasonCodesController` - -## Methods - +# Reason Codes + +```go +reasonCodesController := client.ReasonCodesController() +``` + +## Class Name + +`ReasonCodesController` + +## Methods + * [Create Reason Code](../../doc/controllers/reason-codes.md#create-reason-code) * [List Reason Codes](../../doc/controllers/reason-codes.md#list-reason-codes) * [Read Reason Code](../../doc/controllers/reason-codes.md#read-reason-code) * [Update Reason Code](../../doc/controllers/reason-codes.md#update-reason-code) -* [Delete Reason Code](../../doc/controllers/reason-codes.md#delete-reason-code) - - -# Create Reason Code - +* [Delete Reason Code](../../doc/controllers/reason-codes.md#delete-reason-code) + + +# Create Reason Code + # Reason Codes Intro ReasonCodes are a way to gain a high level view of why your customers are cancelling the subcription to your product or service. @@ -33,29 +33,29 @@ Full documentation on how Reason Codes operate within Chargify can be located un ## Create Reason Code -This method gives a merchant the option to create a reason codes for a given Site. - -```go -CreateReasonCode( - ctx context.Context, +This method gives a merchant the option to create a reason codes for a given Site. + +```go +CreateReasonCode( + ctx context.Context, body *models.CreateReasonCodeRequest) ( models.ApiResponse[models.ReasonCodeResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.CreateReasonCodeRequest`](../../doc/models/create-reason-code-request.md) | Body, Optional | - | - -## Response Type - -[`models.ReasonCodeResponse`](../../doc/models/reason-code-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.CreateReasonCodeRequest`](../../doc/models/create-reason-code-request.md) | Body, Optional | - | + +## Response Type + +[`models.ReasonCodeResponse`](../../doc/models/reason-code-response.md) + +## Example Usage + +```go ctx := context.Background() bodyReasonCode := models.CreateReasonCode{ @@ -75,121 +75,125 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Reason Codes - -This method gives a merchant the option to retrieve a list of all of the current churn codes for a given site. - -```go -ListReasonCodes( - ctx context.Context,input ListReasonCodesInput) ( +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Reason Codes + +This method gives a merchant the option to retrieve a list of all of the current churn codes for a given site. + +```go +ListReasonCodes( + ctx context.Context, + input ListReasonCodesInput) ( models.ApiResponse[[]models.ReasonCodeResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | - -## Response Type - -[`[]models.ReasonCodeResponse`](../../doc/models/reason-code-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | + +## Response Type + +[`[]models.ReasonCodeResponse`](../../doc/models/reason-code-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -apiResponse, err := reasonCodesController.ListReasonCodes(ctx, &page, &perPage) +collectedInput := advancedbilling.ListReasonCodesInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +} + +apiResponse, err := reasonCodesController.ListReasonCodes(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "reason_code": { - "id": 2, - "site_id": 2, - "code": "LARGE", - "description": "This is too complicated", - "position": 1, - "created_at": "2017-02-16T16:49:07-05:00", - "updated_at": "2017-02-17T16:29:51-05:00" - } - }, - { - "reason_code": { - "id": 1, - "site_id": 2, - "code": "CH1", - "description": "This doesnt meet my needs", - "position": 2, - "created_at": "2017-02-16T16:48:45-05:00", - "updated_at": "2017-02-17T16:29:59-05:00" - } - }, - { - "reason_code": { - "id": 5, - "site_id": 2, - "code": "HAN99", - "description": "Hard to setup", - "position": 3, - "created_at": "2017-02-17T16:29:42-05:00", - "updated_at": "2017-02-17T16:29:59-05:00" - } - } -] -``` - - -# Read Reason Code - -This method gives a merchant the option to retrieve a list of a particular code for a given Site by providing the unique numerical ID of the code. - -```go -ReadReasonCode( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "reason_code": { + "id": 2, + "site_id": 2, + "code": "LARGE", + "description": "This is too complicated", + "position": 1, + "created_at": "2017-02-16T16:49:07-05:00", + "updated_at": "2017-02-17T16:29:51-05:00" + } + }, + { + "reason_code": { + "id": 1, + "site_id": 2, + "code": "CH1", + "description": "This doesnt meet my needs", + "position": 2, + "created_at": "2017-02-16T16:48:45-05:00", + "updated_at": "2017-02-17T16:29:59-05:00" + } + }, + { + "reason_code": { + "id": 5, + "site_id": 2, + "code": "HAN99", + "description": "Hard to setup", + "position": 3, + "created_at": "2017-02-17T16:29:42-05:00", + "updated_at": "2017-02-17T16:29:59-05:00" + } + } +] +``` + + +# Read Reason Code + +This method gives a merchant the option to retrieve a list of a particular code for a given Site by providing the unique numerical ID of the code. + +```go +ReadReasonCode( + ctx context.Context, reasonCodeId int) ( models.ApiResponse[models.ReasonCodeResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `reasonCodeId` | `int` | Template, Required | The Chargify id of the reason code | - -## Response Type - -[`models.ReasonCodeResponse`](../../doc/models/reason-code-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `reasonCodeId` | `int` | Template, Required | The Chargify id of the reason code | + +## Response Type + +[`models.ReasonCodeResponse`](../../doc/models/reason-code-response.md) + +## Example Usage + +```go ctx := context.Background() reasonCodeId := 32 @@ -200,43 +204,43 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Update Reason Code - -This method gives a merchant the option to update an existing reason code for a given site. - -```go -UpdateReasonCode( - ctx context.Context, - reasonCodeId int, +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Update Reason Code + +This method gives a merchant the option to update an existing reason code for a given site. + +```go +UpdateReasonCode( + ctx context.Context, + reasonCodeId int, body *models.UpdateReasonCodeRequest) ( models.ApiResponse[models.ReasonCodeResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `reasonCodeId` | `int` | Template, Required | The Chargify id of the reason code | -| `body` | [`*models.UpdateReasonCodeRequest`](../../doc/models/update-reason-code-request.md) | Body, Optional | - | - -## Response Type - -[`models.ReasonCodeResponse`](../../doc/models/reason-code-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `reasonCodeId` | `int` | Template, Required | The Chargify id of the reason code | +| `body` | [`*models.UpdateReasonCodeRequest`](../../doc/models/update-reason-code-request.md) | Body, Optional | - | + +## Response Type + +[`models.ReasonCodeResponse`](../../doc/models/reason-code-response.md) + +## Example Usage + +```go ctx := context.Background() reasonCodeId := 32 @@ -247,41 +251,41 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Delete Reason Code - -This method gives a merchant the option to delete one reason code from the Churn Reason Codes. This code will be immediately removed. This action is not reversable. - -```go -DeleteReasonCode( - ctx context.Context, +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Delete Reason Code + +This method gives a merchant the option to delete one reason code from the Churn Reason Codes. This code will be immediately removed. This action is not reversable. + +```go +DeleteReasonCode( + ctx context.Context, reasonCodeId int) ( models.ApiResponse[models.ReasonCodesJsonResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `reasonCodeId` | `int` | Template, Required | The Chargify id of the reason code | - -## Response Type - -[`models.ReasonCodesJsonResponse`](../../doc/models/reason-codes-json-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `reasonCodeId` | `int` | Template, Required | The Chargify id of the reason code | + +## Response Type + +[`models.ReasonCodesJsonResponse`](../../doc/models/reason-codes-json-response.md) + +## Example Usage + +```go ctx := context.Background() reasonCodeId := 32 @@ -292,20 +296,20 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "ok": "ok" -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "ok": "ok" +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + diff --git a/doc/controllers/referral-codes.md b/doc/controllers/referral-codes.md index 7d6ca51b..8e13ced3 100644 --- a/doc/controllers/referral-codes.md +++ b/doc/controllers/referral-codes.md @@ -1,16 +1,16 @@ -# Referral Codes - -```go -referralCodesController := client.ReferralCodesController() -``` - -## Class Name - -`ReferralCodesController` - - -# Validate Referral Code - +# Referral Codes + +```go +referralCodesController := client.ReferralCodesController() +``` + +## Class Name + +`ReferralCodesController` + + +# Validate Referral Code + Use this method to determine if the referral code is valid and applicable within your Site. This method is useful for validating referral codes that are entered by a customer. ## Referrals Documentation @@ -19,29 +19,29 @@ Full documentation on how to use the referrals feature in the Chargify UI can be ## Server Response -If the referral code is valid the status code will be `200` and the referral code will be returned. If the referral code is invalid, a `404` response will be returned. - -```go -ValidateReferralCode( - ctx context.Context, +If the referral code is valid the status code will be `200` and the referral code will be returned. If the referral code is invalid, a `404` response will be returned. + +```go +ValidateReferralCode( + ctx context.Context, code string) ( models.ApiResponse[models.ReferralValidationResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `code` | `string` | Query, Required | The referral code you are trying to validate | - -## Response Type - -[`models.ReferralValidationResponse`](../../doc/models/referral-validation-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `code` | `string` | Query, Required | The referral code you are trying to validate | + +## Response Type + +[`models.ReferralValidationResponse`](../../doc/models/referral-validation-response.md) + +## Example Usage + +```go ctx := context.Background() code := "code8" @@ -52,25 +52,25 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "referral_code": { - "id": 1032514, - "site_id": 31615, - "subscription_id": 16254270, - "code": "9b6cdw" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | [`SingleStringErrorResponseException`](../../doc/models/single-string-error-response-exception.md) | - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "referral_code": { + "id": 1032514, + "site_id": 31615, + "subscription_id": 16254270, + "code": "9b6cdw" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | [`SingleStringErrorResponseException`](../../doc/models/single-string-error-response-exception.md) | + diff --git a/doc/controllers/sales-commissions.md b/doc/controllers/sales-commissions.md index 213c2767..794d74f3 100644 --- a/doc/controllers/sales-commissions.md +++ b/doc/controllers/sales-commissions.md @@ -1,22 +1,22 @@ -# Sales Commissions - -```go -salesCommissionsController := client.SalesCommissionsController() -``` - -## Class Name - -`SalesCommissionsController` - -## Methods - +# Sales Commissions + +```go +salesCommissionsController := client.SalesCommissionsController() +``` + +## Class Name + +`SalesCommissionsController` + +## Methods + * [List Sales Commission Settings](../../doc/controllers/sales-commissions.md#list-sales-commission-settings) * [List Sales Reps](../../doc/controllers/sales-commissions.md#list-sales-reps) -* [Read Sales Rep](../../doc/controllers/sales-commissions.md#read-sales-rep) - - -# List Sales Commission Settings - +* [Read Sales Rep](../../doc/controllers/sales-commissions.md#read-sales-rep) + + +# List Sales Commission Settings + Endpoint returns subscriptions with associated sales reps ## Modified Authentication Process @@ -25,85 +25,89 @@ The Sales Commission API differs from other Chargify API endpoints. This resourc Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. -> Note: The request is at seller level, it means `<>` variable will be replaced by `app` - -```go -ListSalesCommissionSettings( - ctx context.Context,input ListSalesCommissionSettingsInput) ( +> Note: The request is at seller level, it means `<>` variable will be replaced by `app` + +```go +ListSalesCommissionSettings( + ctx context.Context, + input ListSalesCommissionSettingsInput) ( models.ApiResponse[[]models.SaleRepSettings], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `sellerId` | `string` | Template, Required | The Chargify id of your seller account | -| `authorization` | `*string` | Header, Optional | For authorization use user API key. See details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). | -| `liveMode` | `*bool` | Query, Optional | This parameter indicates if records should be fetched from live mode sites. Default value is true. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. | - -## Response Type - -[`[]models.SaleRepSettings`](../../doc/models/sale-rep-settings.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `sellerId` | `string` | Template, Required | The Chargify id of your seller account | +| `authorization` | `*string` | Header, Optional | For authorization use user API key. See details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). | +| `liveMode` | `*bool` | Query, Optional | This parameter indicates if records should be fetched from live mode sites. Default value is true. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. | + +## Response Type + +[`[]models.SaleRepSettings`](../../doc/models/sale-rep-settings.md) + +## Example Usage + +```go ctx := context.Background() -sellerId := "seller_id8" -authorization := "Bearer <>" -page := 2 -perPage := 100 -apiResponse, err := salesCommissionsController.ListSalesCommissionSettings(ctx, sellerId, &authorization, nil, &page, &perPage) +collectedInput := advancedbilling.ListSalesCommissionSettingsInput{ + SellerId: "seller_id8", + Authorization: models.ToPointer("Bearer <>"), + Page: models.ToPointer(2), + PerPage: models.ToPointer(100), +} + +apiResponse, err := salesCommissionsController.ListSalesCommissionSettings(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "customer_name": "Ziomek Ziomeczek", - "subscription_id": 81746, - "site_link": "https://chargify9.staging-chargify.com/dashboard", - "site_name": "Chargify", - "subscription_mrr": "$200.00", - "sales_rep_id": 48, - "sales_rep_name": "John Candy" - }, - { - "customer_name": "Ziom Kom", - "subscription_id": 83758, - "site_link": "https://chargify9.staging-chargify.com/dashboard", - "site_name": "Chargify", - "subscription_mrr": "$200.00", - "sales_rep_id": 49, - "sales_rep_name": "Josh Acme" - }, - { - "customer_name": "George Bush", - "subscription_id": 83790, - "site_link": "https://chargify9.staging-chargify.com/dashboard", - "site_name": "Chargify", - "subscription_mrr": "$200.00", - "sales_rep_id": 48, - "sales_rep_name": "John Candy" - } -] -``` - - -# List Sales Reps - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "customer_name": "Ziomek Ziomeczek", + "subscription_id": 81746, + "site_link": "https://chargify9.staging-chargify.com/dashboard", + "site_name": "Chargify", + "subscription_mrr": "$200.00", + "sales_rep_id": 48, + "sales_rep_name": "John Candy" + }, + { + "customer_name": "Ziom Kom", + "subscription_id": 83758, + "site_link": "https://chargify9.staging-chargify.com/dashboard", + "site_name": "Chargify", + "subscription_mrr": "$200.00", + "sales_rep_id": 49, + "sales_rep_name": "Josh Acme" + }, + { + "customer_name": "George Bush", + "subscription_id": 83790, + "site_link": "https://chargify9.staging-chargify.com/dashboard", + "site_name": "Chargify", + "subscription_mrr": "$200.00", + "sales_rep_id": 48, + "sales_rep_name": "John Candy" + } +] +``` + + +# List Sales Reps + Endpoint returns sales rep list with details ## Modified Authentication Process @@ -112,134 +116,138 @@ The Sales Commission API differs from other Chargify API endpoints. This resourc Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. -> Note: The request is at seller level, it means `<>` variable will be replaced by `app` - -```go -ListSalesReps( - ctx context.Context,input ListSalesRepsInput) ( +> Note: The request is at seller level, it means `<>` variable will be replaced by `app` + +```go +ListSalesReps( + ctx context.Context, + input ListSalesRepsInput) ( models.ApiResponse[[]models.ListSaleRepItem], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `sellerId` | `string` | Template, Required | The Chargify id of your seller account | -| `authorization` | `*string` | Header, Optional | For authorization use user API key. See details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). | -| `liveMode` | `*bool` | Query, Optional | This parameter indicates if records should be fetched from live mode sites. Default value is true. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. | - -## Response Type - -[`[]models.ListSaleRepItem`](../../doc/models/list-sale-rep-item.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `sellerId` | `string` | Template, Required | The Chargify id of your seller account | +| `authorization` | `*string` | Header, Optional | For authorization use user API key. See details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). | +| `liveMode` | `*bool` | Query, Optional | This parameter indicates if records should be fetched from live mode sites. Default value is true. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. | + +## Response Type + +[`[]models.ListSaleRepItem`](../../doc/models/list-sale-rep-item.md) + +## Example Usage + +```go ctx := context.Background() -sellerId := "seller_id8" -authorization := "Bearer <>" -page := 2 -perPage := 100 -apiResponse, err := salesCommissionsController.ListSalesReps(ctx, sellerId, &authorization, nil, &page, &perPage) +collectedInput := advancedbilling.ListSalesRepsInput{ + SellerId: "seller_id8", + Authorization: models.ToPointer("Bearer <>"), + Page: models.ToPointer(2), + PerPage: models.ToPointer(100), +} + +apiResponse, err := salesCommissionsController.ListSalesReps(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "id": 48, - "full_name": "John Candy", - "subscriptions_count": 2, - "mrr_data": { - "november_2019": { - "mrr": "$0.00", - "usage": "$0.00", - "recurring": "$0.00" - }, - "december_2019": { - "mrr": "$0.00", - "usage": "$0.00", - "recurring": "$0.00" - }, - "january_2020": { - "mrr": "$400.00", - "usage": "$0.00", - "recurring": "$400.00" - }, - "february_2020": { - "mrr": "$400.00", - "usage": "$0.00", - "recurring": "$400.00" - }, - "march_2020": { - "mrr": "$400.00", - "usage": "$0.00", - "recurring": "$400.00" - }, - "april_2020": { - "mrr": "$400.00", - "usage": "$0.00", - "recurring": "$400.00" - } - }, - "test_mode": true - }, - { - "id": 49, - "full_name": "Josh Acme", - "subscriptions_count": 1, - "mrr_data": { - "november_2019": { - "mrr": "$0.00", - "usage": "$0.00", - "recurring": "$0.00" - }, - "december_2019": { - "mrr": "$0.00", - "usage": "$0.00", - "recurring": "$0.00" - }, - "january_2020": { - "mrr": "$200.00", - "usage": "$0.00", - "recurring": "$200.00" - }, - "february_2020": { - "mrr": "$200.00", - "usage": "$0.00", - "recurring": "$200.00" - }, - "march_2020": { - "mrr": "$200.00", - "usage": "$0.00", - "recurring": "$200.00" - }, - "april_2020": { - "mrr": "$200.00", - "usage": "$0.00", - "recurring": "$200.00" - } - }, - "test_mode": true - } -] -``` - - -# Read Sales Rep - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "id": 48, + "full_name": "John Candy", + "subscriptions_count": 2, + "mrr_data": { + "november_2019": { + "mrr": "$0.00", + "usage": "$0.00", + "recurring": "$0.00" + }, + "december_2019": { + "mrr": "$0.00", + "usage": "$0.00", + "recurring": "$0.00" + }, + "january_2020": { + "mrr": "$400.00", + "usage": "$0.00", + "recurring": "$400.00" + }, + "february_2020": { + "mrr": "$400.00", + "usage": "$0.00", + "recurring": "$400.00" + }, + "march_2020": { + "mrr": "$400.00", + "usage": "$0.00", + "recurring": "$400.00" + }, + "april_2020": { + "mrr": "$400.00", + "usage": "$0.00", + "recurring": "$400.00" + } + }, + "test_mode": true + }, + { + "id": 49, + "full_name": "Josh Acme", + "subscriptions_count": 1, + "mrr_data": { + "november_2019": { + "mrr": "$0.00", + "usage": "$0.00", + "recurring": "$0.00" + }, + "december_2019": { + "mrr": "$0.00", + "usage": "$0.00", + "recurring": "$0.00" + }, + "january_2020": { + "mrr": "$200.00", + "usage": "$0.00", + "recurring": "$200.00" + }, + "february_2020": { + "mrr": "$200.00", + "usage": "$0.00", + "recurring": "$200.00" + }, + "march_2020": { + "mrr": "$200.00", + "usage": "$0.00", + "recurring": "$200.00" + }, + "april_2020": { + "mrr": "$200.00", + "usage": "$0.00", + "recurring": "$200.00" + } + }, + "test_mode": true + } +] +``` + + +# Read Sales Rep + Endpoint returns sales rep and attached subscriptions details. ## Modified Authentication Process @@ -248,39 +256,39 @@ The Sales Commission API differs from other Chargify API endpoints. This resourc Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. -> Note: The request is at seller level, it means `<>` variable will be replaced by `app` - -```go -ReadSalesRep( - ctx context.Context, - sellerId string, - salesRepId string, - authorization *string, - liveMode *bool, - page *int, +> Note: The request is at seller level, it means `<>` variable will be replaced by `app` + +```go +ReadSalesRep( + ctx context.Context, + sellerId string, + salesRepId string, + authorization *string, + liveMode *bool, + page *int, perPage *int) ( models.ApiResponse[models.SaleRep], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `sellerId` | `string` | Template, Required | The Chargify id of your seller account | -| `salesRepId` | `string` | Template, Required | The Chargify id of sales rep. | -| `authorization` | `*string` | Header, Optional | For authorization use user API key. See details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). | -| `liveMode` | `*bool` | Query, Optional | This parameter indicates if records should be fetched from live mode sites. Default value is true. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. | - -## Response Type - -[`models.SaleRep`](../../doc/models/sale-rep.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `sellerId` | `string` | Template, Required | The Chargify id of your seller account | +| `salesRepId` | `string` | Template, Required | The Chargify id of sales rep. | +| `authorization` | `*string` | Header, Optional | For authorization use user API key. See details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). | +| `liveMode` | `*bool` | Query, Optional | This parameter indicates if records should be fetched from live mode sites. Default value is true. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 100. | + +## Response Type + +[`models.SaleRep`](../../doc/models/sale-rep.md) + +## Example Usage + +```go ctx := context.Background() sellerId := "seller_id8" salesRepId := "sales_rep_id4" @@ -295,43 +303,43 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "id": 48, - "full_name": "John Candy", - "subscriptions_count": 2, - "test_mode": true, - "subscriptions": [ - { - "id": 81746, - "site_name": "Chargify", - "subscription_url": "https://chargify9.staging-chargify.com/subscriptions/81746", - "customer_name": "Ziomek Ziomeczek", - "created_at": "2020-01-03T02:36:27-05:00", - "mrr": "$200.00", - "usage": "$0.00", - "recurring": "$200.00", - "last_payment": "2020-04-03T03:40:27-04:00", - "churn_date": null - }, - { - "id": 83790, - "site_name": "Chargify", - "subscription_url": "https://chargify9.staging-chargify.com/subscriptions/83790", - "customer_name": "George Bush", - "created_at": "2020-01-17T07:34:32-05:00", - "mrr": "$200.00", - "usage": "$0.00", - "recurring": "$200.00", - "last_payment": "2020-04-17T08:41:03-04:00", - "churn_date": null - } - ] -} -``` - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "id": 48, + "full_name": "John Candy", + "subscriptions_count": 2, + "test_mode": true, + "subscriptions": [ + { + "id": 81746, + "site_name": "Chargify", + "subscription_url": "https://chargify9.staging-chargify.com/subscriptions/81746", + "customer_name": "Ziomek Ziomeczek", + "created_at": "2020-01-03T02:36:27-05:00", + "mrr": "$200.00", + "usage": "$0.00", + "recurring": "$200.00", + "last_payment": "2020-04-03T03:40:27-04:00", + "churn_date": null + }, + { + "id": 83790, + "site_name": "Chargify", + "subscription_url": "https://chargify9.staging-chargify.com/subscriptions/83790", + "customer_name": "George Bush", + "created_at": "2020-01-17T07:34:32-05:00", + "mrr": "$200.00", + "usage": "$0.00", + "recurring": "$200.00", + "last_payment": "2020-04-17T08:41:03-04:00", + "churn_date": null + } + ] +} +``` + diff --git a/doc/controllers/sites.md b/doc/controllers/sites.md index 3c0db4cf..7f751b96 100644 --- a/doc/controllers/sites.md +++ b/doc/controllers/sites.md @@ -1,22 +1,22 @@ -# Sites - -```go -sitesController := client.SitesController() -``` - -## Class Name - -`SitesController` - -## Methods - +# Sites + +```go +sitesController := client.SitesController() +``` + +## Class Name + +`SitesController` + +## Methods + * [Read Site](../../doc/controllers/sites.md#read-site) * [Clear Site](../../doc/controllers/sites.md#clear-site) -* [List Chargify Js Public Keys](../../doc/controllers/sites.md#list-chargify-js-public-keys) - - -# Read Site - +* [List Chargify Js Public Keys](../../doc/controllers/sites.md#list-chargify-js-public-keys) + + +# Read Site + This endpoint allows you to fetch some site data. Full documentation on Sites in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407870738587). @@ -32,22 +32,22 @@ If site has RI enabled then you will see more settings like: "whopays_default_payer": "self" You can read more about these settings here: -[Who Pays & Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) - -```go -ReadSite( +[Who Pays & Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) + +```go +ReadSite( ctx context.Context) ( models.ApiResponse[models.SiteResponse], - error) -``` - -## Response Type - -[`models.SiteResponse`](../../doc/models/site-response.md) - -## Example Usage - -```go + error) +``` + +## Response Type + +[`models.SiteResponse`](../../doc/models/site-response.md) + +## Example Usage + +```go ctx := context.Background() apiResponse, err := sitesController.ReadSite(ctx) if err != nil { @@ -56,87 +56,87 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "site": { - "id": 0, - "name": "string", - "subdomain": "string", - "currency": "string", - "seller_id": 0, - "non_primary_currencies": [ - "string" - ], - "relationship_invoicing_enabled": true, - "customer_hierarchy_enabled": true, - "whopays_enabled": true, - "whopays_default_payer": "string", - "default_payment_collection_method": "string", - "organization_address": { - "street": null, - "line2": null, - "city": null, - "state": null, - "zip": null, - "country": null, - "name": "string", - "phone": "string" - }, - "tax_configuration": { - "kind": "custom", - "fully_configured": true, - "destination_address": "shipping_then_billing" - }, - "net_terms": { - "default_net_terms": 0, - "automatic_net_terms": 0, - "remittance_net_terms": 0, - "net_terms_on_remittance_signups_enabled": false, - "custom_net_terms_enabled": false - }, - "test": true, - "allocation_settings": { - "upgrade_charge": "prorated", - "downgrade_credit": "none", - "accrue_charge": "true" - } - } -} -``` - - -# Clear Site - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "site": { + "id": 0, + "name": "string", + "subdomain": "string", + "currency": "string", + "seller_id": 0, + "non_primary_currencies": [ + "string" + ], + "relationship_invoicing_enabled": true, + "customer_hierarchy_enabled": true, + "whopays_enabled": true, + "whopays_default_payer": "string", + "default_payment_collection_method": "string", + "organization_address": { + "street": null, + "line2": null, + "city": null, + "state": null, + "zip": null, + "country": null, + "name": "string", + "phone": "string" + }, + "tax_configuration": { + "kind": "custom", + "fully_configured": true, + "destination_address": "shipping_then_billing" + }, + "net_terms": { + "default_net_terms": 0, + "automatic_net_terms": 0, + "remittance_net_terms": 0, + "net_terms_on_remittance_signups_enabled": false, + "custom_net_terms_enabled": false + }, + "test": true, + "allocation_settings": { + "upgrade_charge": "prorated", + "downgrade_credit": "none", + "accrue_charge": "true" + } + } +} +``` + + +# Clear Site + This call is asynchronous and there may be a delay before the site data is fully deleted. If you are clearing site data for an automated test, you will need to build in a delay and/or check that there are no products, etc., in the site before proceeding. -**This functionality will only work on sites in TEST mode. Attempts to perform this on sites in “live” mode will result in a response of 403 FORBIDDEN.** - -```go -ClearSite( - ctx context.Context, +**This functionality will only work on sites in TEST mode. Attempts to perform this on sites in “live” mode will result in a response of 403 FORBIDDEN.** + +```go +ClearSite( + ctx context.Context, cleanupScope *models.CleanupScope) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `cleanupScope` | [`*models.CleanupScope`](../../doc/models/cleanup-scope.md) | Query, Optional | `all`: Will clear all products, customers, and related subscriptions from the site.
`customers`: Will clear only customers and related subscriptions (leaving the products untouched) for the site.
Revenue will also be reset to 0.
Use in query `cleanup_scope=all`. | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `cleanupScope` | [`*models.CleanupScope`](../../doc/models/cleanup-scope.md) | Query, Optional | `all`: Will clear all products, customers, and related subscriptions from the site.
`customers`: Will clear only customers and related subscriptions (leaving the products untouched) for the site.
Revenue will also be reset to 0.
Use in query `cleanup_scope=all`. | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() cleanupScope := models.CleanupScope("all") @@ -145,66 +145,70 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - - -# List Chargify Js Public Keys - -This endpoint returns public keys used for Chargify.js. - -```go -ListChargifyJsPublicKeys( - ctx context.Context,input ListChargifyJsPublicKeysInput) ( +} +``` + + +# List Chargify Js Public Keys + +This endpoint returns public keys used for Chargify.js. + +```go +ListChargifyJsPublicKeys( + ctx context.Context, + input ListChargifyJsPublicKeysInput) ( models.ApiResponse[models.ListPublicKeysResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | - -## Response Type - -[`models.ListPublicKeysResponse`](../../doc/models/list-public-keys-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | + +## Response Type + +[`models.ListPublicKeysResponse`](../../doc/models/list-public-keys-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -apiResponse, err := sitesController.ListChargifyJsPublicKeys(ctx, &page, &perPage) +collectedInput := advancedbilling.ListChargifyJsPublicKeysInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +} + +apiResponse, err := sitesController.ListChargifyJsPublicKeys(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "chargify_js_keys": [ - { - "public_key": "chjs_ftrxt7c4fv6f74wchjs_5zyn7gnwv", - "requires_security_token": false, - "created_at": "2021-01-01T05:00:00-04:00" - } - ], - "meta": { - "total_count": 1, - "current_page": 1, - "total_pages": 1, - "per_page": 10 - } -} -``` - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "chargify_js_keys": [ + { + "public_key": "chjs_ftrxt7c4fv6f74wchjs_5zyn7gnwv", + "requires_security_token": false, + "created_at": "2021-01-01T05:00:00-04:00" + } + ], + "meta": { + "total_count": 1, + "current_page": 1, + "total_pages": 1, + "per_page": 10 + } +} +``` + diff --git a/doc/controllers/subscription-components.md b/doc/controllers/subscription-components.md index 9df8dbb8..5fa8b8bc 100644 --- a/doc/controllers/subscription-components.md +++ b/doc/controllers/subscription-components.md @@ -1,15 +1,15 @@ -# Subscription Components - -```go -subscriptionComponentsController := client.SubscriptionComponentsController() -``` - -## Class Name - -`SubscriptionComponentsController` - -## Methods - +# Subscription Components + +```go +subscriptionComponentsController := client.SubscriptionComponentsController() +``` + +## Class Name + +`SubscriptionComponentsController` + +## Methods + * [Read Subscription Component](../../doc/controllers/subscription-components.md#read-subscription-component) * [List Subscription Components](../../doc/controllers/subscription-components.md#list-subscription-components) * [Bulk Update Subscription Components Price Points](../../doc/controllers/subscription-components.md#bulk-update-subscription-components-price-points) @@ -26,36 +26,36 @@ subscriptionComponentsController := client.SubscriptionComponentsController() * [Deactivate Event Based Component](../../doc/controllers/subscription-components.md#deactivate-event-based-component) * [Record Event](../../doc/controllers/subscription-components.md#record-event) * [Bulk Record Events](../../doc/controllers/subscription-components.md#bulk-record-events) -* [List Subscription Components for Site](../../doc/controllers/subscription-components.md#list-subscription-components-for-site) - - -# Read Subscription Component - -This request will list information regarding a specific component owned by a subscription. - -```go -ReadSubscriptionComponent( - ctx context.Context, - subscriptionId int, +* [List Subscription Components for Site](../../doc/controllers/subscription-components.md#list-subscription-components-for-site) + + +# Read Subscription Component + +This request will list information regarding a specific component owned by a subscription. + +```go +ReadSubscriptionComponent( + ctx context.Context, + subscriptionId int, componentId int) ( models.ApiResponse[models.SubscriptionComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component. Alternatively, the component's handle prefixed by `handle:` | - -## Response Type - -[`models.SubscriptionComponentResponse`](../../doc/models/subscription-component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | `int` | Template, Required | The Chargify id of the component. Alternatively, the component's handle prefixed by `handle:` | + +## Response Type + +[`models.SubscriptionComponentResponse`](../../doc/models/subscription-component-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 componentId := 222 @@ -67,172 +67,182 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "component": { - "component_id": 193028, - "subscription_id": 14593192, - "allocated_quantity": 1, - "pricing_scheme": "per_unit", - "name": "Users", - "kind": "quantity_based_component", - "unit_name": "Users", - "price_point_id": 1, - "price_point_handle": "top-tier", - "enabled": true - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# List Subscription Components - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "component": { + "component_id": 193028, + "subscription_id": 14593192, + "allocated_quantity": 1, + "pricing_scheme": "per_unit", + "name": "Users", + "kind": "quantity_based_component", + "unit_name": "Users", + "price_point_id": 1, + "price_point_handle": "top-tier", + "enabled": true + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# List Subscription Components + This request will list a subscription's applied components. ## Archived Components -When requesting to list components for a given subscription, if the subscription contains **archived** components they will be listed in the server response. - -```go -ListSubscriptionComponents( - ctx context.Context,input ListSubscriptionComponentsInput) ( +When requesting to list components for a given subscription, if the subscription contains **archived** components they will be listed in the server response. + +```go +ListSubscriptionComponents( + ctx context.Context, + input ListSubscriptionComponentsInput) ( models.ApiResponse[[]models.SubscriptionComponentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `dateField` | [`*models.SubscriptionListDateField`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Use in query `date_field=updated_at`. | -| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | -| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | -| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. | -| `pricePointIds` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching components allocation only if price point id is present. Use in query `price_point_ids=not_null`. | -| `productFamilyIds` | `[]int` | Query, Optional | Allows fetching components allocation with matching product family id based on provided ids. Use in query `product_family_ids=1,2,3`. | -| `sort` | [`*models.ListSubscriptionComponentsSort`](../../doc/models/list-subscription-components-sort.md) | Query, Optional | The attribute by which to sort. Use in query `sort=updated_at`. | -| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | -| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. | -| `include` | [`*models.ListSubscriptionComponentsInclude`](../../doc/models/list-subscription-components-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=subscription`. | -| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching components allocation with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | -| `filterCurrencies` | `[]string` | Query, Optional | Allows fetching components allocation with matching currency based on provided values. Use in query `filter[currencies]=EUR,USD`. | - -## Response Type - -[`[]models.SubscriptionComponentResponse`](../../doc/models/subscription-component-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `dateField` | [`*models.SubscriptionListDateField`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Use in query `date_field=updated_at`. | +| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | +| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. | +| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. | +| `pricePointIds` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching components allocation only if price point id is present. Use in query `price_point_ids=not_null`. | +| `productFamilyIds` | `[]int` | Query, Optional | Allows fetching components allocation with matching product family id based on provided ids. Use in query `product_family_ids=1,2,3`. | +| `sort` | [`*models.ListSubscriptionComponentsSort`](../../doc/models/list-subscription-components-sort.md) | Query, Optional | The attribute by which to sort. Use in query `sort=updated_at`. | +| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. | +| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. | +| `include` | [`*models.ListSubscriptionComponentsInclude`](../../doc/models/list-subscription-components-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=subscription`. | +| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching components allocation with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | +| `filterCurrencies` | `[]string` | Query, Optional | Allows fetching components allocation with matching currency based on provided values. Use in query `filter[currencies]=EUR,USD`. | + +## Response Type + +[`[]models.SubscriptionComponentResponse`](../../doc/models/subscription-component-response.md) + +## Example Usage + +```go ctx := context.Background() -subscriptionId := 222 -dateField := models.SubscriptionListDateField("updated_at") -pricePointIds := models.IncludeNotNull("not_null") -productFamilyIds := []int{1, 2, 3} -sort := models.ListSubscriptionComponentsSort("updated_at") -include := models.ListSubscriptionComponentsInclude("subscription")Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') -apiResponse, err := subscriptionComponentsController.ListSubscriptionComponents(ctx, subscriptionId, &dateField, nil, nil, nil, &pricePointIds, productFamilyIds, &sort, nil, nil, &include, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key')) +collectedInput := advancedbilling.ListSubscriptionComponentsInput{ + SubscriptionId: 222, + DateField: models.ToPointer(models.SubscriptionListDateField("updated_at")), + PricePointIds: models.ToPointer(models.IncludeNotNull("not_null")), + ProductFamilyIds: []int{1, 2, 3}, + Sort: models.ToPointer(models.ListSubscriptionComponentsSort("updated_at")), + Include: models.ToPointer(models.ListSubscriptionComponentsInclude("subscription")), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := subscriptionComponentsController.ListSubscriptionComponents(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "component": { - "component_id": 0, - "subscription_id": 0, - "allocated_quantity": 0, - "pricing_scheme": "per_unit", - "name": "string", - "kind": "quantity_based_component", - "unit_name": "string", - "price_point_id": 0, - "price_point_handle": "string", - "price_point_type": "default", - "price_point_name": "string", - "enabled": true, - "unit_balance": 0, - "id": 0, - "created_at": "2022-02-22T14:07:00-05:00", - "updated_at": "2022-02-22T14:07:00-05:00", - "component_handle": "string", - "archived_at": null - } - } -] -``` - - -# Bulk Update Subscription Components Price Points - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "component": { + "component_id": 0, + "subscription_id": 0, + "allocated_quantity": 0, + "pricing_scheme": "per_unit", + "name": "string", + "kind": "quantity_based_component", + "unit_name": "string", + "price_point_id": 0, + "price_point_handle": "string", + "price_point_type": "default", + "price_point_name": "string", + "enabled": true, + "unit_balance": 0, + "id": 0, + "created_at": "2022-02-22T14:07:00-05:00", + "updated_at": "2022-02-22T14:07:00-05:00", + "component_handle": "string", + "archived_at": null + } + } +] +``` + + +# Bulk Update Subscription Components Price Points + Updates the price points on one or more of a subscription's components. The `price_point` key can take either a: 1. Price point id (integer) 2. Price point handle (string) -3. `"_default"` string, which will reset the price point to the component's current default price point. - -```go -BulkUpdateSubscriptionComponentsPricePoints( - ctx context.Context, - subscriptionId int, +3. `"_default"` string, which will reset the price point to the component's current default price point. + +```go +BulkUpdateSubscriptionComponentsPricePoints( + ctx context.Context, + subscriptionId int, body *models.BulkComponentsPricePointAssignment) ( models.ApiResponse[models.BulkComponentsPricePointAssignment], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.BulkComponentsPricePointAssignment`](../../doc/models/bulk-components-price-point-assignment.md) | Body, Optional | - | - -## Response Type - -[`models.BulkComponentsPricePointAssignment`](../../doc/models/bulk-components-price-point-assignment.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.BulkComponentsPricePointAssignment`](../../doc/models/bulk-components-price-point-assignment.md) | Body, Optional | - | + +## Response Type + +[`models.BulkComponentsPricePointAssignment`](../../doc/models/bulk-components-price-point-assignment.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 +bodyComponents0PricePoint := models.ComponentPricePointAssignmentPricePointContainer.FromNumber(1022) + bodyComponents0 := models.ComponentPricePointAssignment{ ComponentId: models.ToPointer(997), - PricePoint: models.ToPointer(interface{}("[key1, val1][key2, val2]")), + PricePoint: models.ToPointer(bodyComponents0PricePoint), } +bodyComponents1PricePoint := models.ComponentPricePointAssignmentPricePointContainer.FromString("wholesale-handle") + bodyComponents1 := models.ComponentPricePointAssignment{ ComponentId: models.ToPointer(998), - PricePoint: models.ToPointer(interface{}("[key1, val1][key2, val2]")), + PricePoint: models.ToPointer(bodyComponents1PricePoint), } +bodyComponents2PricePoint := models.ComponentPricePointAssignmentPricePointContainer.FromString("_default") + bodyComponents2 := models.ComponentPricePointAssignment{ ComponentId: models.ToPointer(999), - PricePoint: models.ToPointer(interface{}("[key1, val1][key2, val2]")), + PricePoint: models.ToPointer(bodyComponents2PricePoint), } bodyComponents := []models.ComponentPricePointAssignment{bodyComponents0, bodyComponents1, bodyComponents2} @@ -247,60 +257,60 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "components": [ - { - "component_id": 123, - "price_point": 456 - }, - { - "component_id": 789, - "price_point": 987 - } - ] -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ComponentPricePointErrorException`](../../doc/models/component-price-point-error-exception.md) | - - -# Bulk Reset Subscription Components Price Points - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "components": [ + { + "component_id": 123, + "price_point": 456 + }, + { + "component_id": 789, + "price_point": 987 + } + ] +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ComponentPricePointErrorException`](../../doc/models/component-price-point-error-exception.md) | + + +# Bulk Reset Subscription Components Price Points + Resets all of a subscription's components to use the current default. -**Note**: this will update the price point for all of the subscription's components, even ones that have not been allocated yet. - -```go -BulkResetSubscriptionComponentsPricePoints( - ctx context.Context, +**Note**: this will update the price point for all of the subscription's components, even ones that have not been allocated yet. + +```go +BulkResetSubscriptionComponentsPricePoints( + ctx context.Context, subscriptionId int) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -311,113 +321,113 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 80293620, - "state": "active", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2023-11-23T10:28:34-05:00", - "created_at": "2023-11-23T10:28:34-05:00", - "updated_at": "2023-11-23T10:28:34-05:00", - "expires_at": null, - "balance_in_cents": 50504234, - "current_period_ends_at": "2023-11-23T10:28:34-05:00", - "next_assessment_at": "2023-11-23T10:28:34-05:00", - "canceled_at": null, - "cancellation_message": "lorem ipsum", - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "remittance", - "snap_day": null, - "cancellation_method": "dunning", - "current_period_started_at": "2023-11-23T10:28:34-05:00", - "previous_state": "active", - "signup_payment_id": -45156092, - "signup_revenue": "do aliquip ea", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": -49740952, - "product_price_in_cents": 87617888, - "product_version_number": 13656635, - "payment_type": null, - "referral_code": null, - "coupon_use_count": null, - "coupon_uses_allowed": null, - "reason_code": null, - "automatically_resume_at": null, - "current_billing_amount_in_cents": -26151968, - "customer": { - "id": 15208337, - "first_name": "ipsum culpa in labore eiusmod", - "last_name": "esse", - "organization": null, - "email": "ex eiusmod", - "created_at": "2021-05-05T16:00:21-04:00", - "updated_at": "2021-05-05T16:00:21-04:00", - "reference": "laboris ea cupidatat", - "address": null, - "address_2": null, - "city": "id eiusmod proident", - "state": "magna eiusmod anim non", - "zip": null, - "country": null, - "phone": null, - "portal_invite_last_sent_at": null, - "portal_invite_last_accepted_at": "2021-05-05T20:00:21-04:00", - "portal_customer_created_at": "2021-05-05T16:00:21-04:00", - "cc_emails": "eiusmod sunt", - "tax_exempt": true - }, - "product": { - "id": -74447756, - "name": "eu mollit nulla ut aute", - "handle": "esse dolor anim", - "description": "Lorem ut et non", - "accounting_code": "nisi", - "request_credit_card": false, - "expiration_interval": 1, - "expiration_interval_unit": "day", - "created_at": "2022-11-23T10:28:34-05:00", - "updated_at": "2022-11-23T10:28:34-05:00", - "price_in_cents": -4151649, - "interval": 20680876, - "interval_unit": "day", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "day", - "archived_at": null, - "require_credit_card": true, - "return_params": "magna eu", - "taxable": true, - "update_return_url": "exercitation in", - "tax_code": "Excepteur aliqua sunt in", - "initial_charge_after_trial": true, - "version_number": 41642597, - "update_return_params": "dolore labore", - "product_family": { - "id": -5356997, - "name": "officia amet Lorem proident enim", - "description": "Duis", - "handle": "ea dolore dolore sunt", - "accounting_code": null - }, - "public_signup_pages": [] - } - } -} -``` - - -# Allocate Component - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 80293620, + "state": "active", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2023-11-23T10:28:34-05:00", + "created_at": "2023-11-23T10:28:34-05:00", + "updated_at": "2023-11-23T10:28:34-05:00", + "expires_at": null, + "balance_in_cents": 50504234, + "current_period_ends_at": "2023-11-23T10:28:34-05:00", + "next_assessment_at": "2023-11-23T10:28:34-05:00", + "canceled_at": null, + "cancellation_message": "lorem ipsum", + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "remittance", + "snap_day": null, + "cancellation_method": "dunning", + "current_period_started_at": "2023-11-23T10:28:34-05:00", + "previous_state": "active", + "signup_payment_id": -45156092, + "signup_revenue": "do aliquip ea", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": -49740952, + "product_price_in_cents": 87617888, + "product_version_number": 13656635, + "payment_type": null, + "referral_code": null, + "coupon_use_count": null, + "coupon_uses_allowed": null, + "reason_code": null, + "automatically_resume_at": null, + "current_billing_amount_in_cents": -26151968, + "customer": { + "id": 15208337, + "first_name": "ipsum culpa in labore eiusmod", + "last_name": "esse", + "organization": null, + "email": "ex eiusmod", + "created_at": "2021-05-05T16:00:21-04:00", + "updated_at": "2021-05-05T16:00:21-04:00", + "reference": "laboris ea cupidatat", + "address": null, + "address_2": null, + "city": "id eiusmod proident", + "state": "magna eiusmod anim non", + "zip": null, + "country": null, + "phone": null, + "portal_invite_last_sent_at": null, + "portal_invite_last_accepted_at": "2021-05-05T20:00:21-04:00", + "portal_customer_created_at": "2021-05-05T16:00:21-04:00", + "cc_emails": "eiusmod sunt", + "tax_exempt": true + }, + "product": { + "id": -74447756, + "name": "eu mollit nulla ut aute", + "handle": "esse dolor anim", + "description": "Lorem ut et non", + "accounting_code": "nisi", + "request_credit_card": false, + "expiration_interval": 1, + "expiration_interval_unit": "day", + "created_at": "2022-11-23T10:28:34-05:00", + "updated_at": "2022-11-23T10:28:34-05:00", + "price_in_cents": -4151649, + "interval": 20680876, + "interval_unit": "day", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "day", + "archived_at": null, + "require_credit_card": true, + "return_params": "magna eu", + "taxable": true, + "update_return_url": "exercitation in", + "tax_code": "Excepteur aliqua sunt in", + "initial_charge_after_trial": true, + "version_number": 41642597, + "update_return_params": "dolore labore", + "product_family": { + "id": -5356997, + "name": "officia amet Lorem proident enim", + "description": "Duis", + "handle": "ea dolore dolore sunt", + "accounting_code": null + }, + "public_signup_pages": [] + } + } +} +``` + + +# Allocate Component + This endpoint creates a new allocation, setting the current allocated quantity for the Component and recording a memo. **Notice**: Allocations can only be updated for Quantity, On/Off, and Prepaid Components. @@ -466,33 +476,33 @@ See the tables below for valid values. 1. Allocation API call top level (outside of the `allocations` array) 2. [Site-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-schemes) -**NOTE: Proration uses the current price of the component as well as the current tax rates. Changes to either may cause the prorated charge/credit to be wrong.** - -```go -AllocateComponent( - ctx context.Context, - subscriptionId int, - componentId int, +**NOTE: Proration uses the current price of the component as well as the current tax rates. Changes to either may cause the prorated charge/credit to be wrong.** + +```go +AllocateComponent( + ctx context.Context, + subscriptionId int, + componentId int, body *models.CreateAllocationRequest) ( models.ApiResponse[models.AllocationResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component | -| `body` | [`*models.CreateAllocationRequest`](../../doc/models/create-allocation-request.md) | Body, Optional | - | - -## Response Type - -[`models.AllocationResponse`](../../doc/models/allocation-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | `int` | Template, Required | The Chargify id of the component | +| `body` | [`*models.CreateAllocationRequest`](../../doc/models/create-allocation-request.md) | Body, Optional | - | + +## Response Type + +[`models.AllocationResponse`](../../doc/models/allocation-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 componentId := 222 @@ -513,46 +523,46 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "allocation": { - "component_id": 4034995, - "subscription_id": 23737320, - "quantity": 3, - "previous_quantity": 2, - "memo": "dolore cupidatat elit", - "timestamp": "2022-11-23T10:28:34-05:00", - "proration_upgrade_scheme": "laboris ipsum dolore", - "proration_downgrade_scheme": "eiusmod dolore", - "price_point_id": -69720370, - "previous_price_point_id": -76493052, - "accrue_charge": true, - "upgrade_charge": "full", - "downgrade_credit": "full", - "payment": { - "id": -44566528, - "amount_in_cents": 123, - "success": false, - "memo": "aliqua" - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Allocations - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "allocation": { + "component_id": 4034995, + "subscription_id": 23737320, + "quantity": 3, + "previous_quantity": 2, + "memo": "dolore cupidatat elit", + "timestamp": "2022-11-23T10:28:34-05:00", + "proration_upgrade_scheme": "laboris ipsum dolore", + "proration_downgrade_scheme": "eiusmod dolore", + "price_point_id": -69720370, + "previous_price_point_id": -76493052, + "accrue_charge": true, + "upgrade_charge": "full", + "downgrade_credit": "full", + "payment": { + "id": -44566528, + "amount_in_cents": 123, + "success": false, + "memo": "aliqua" + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Allocations + This endpoint returns the 50 most recent Allocations, ordered by most recent first. ## On/Off Components @@ -572,33 +582,33 @@ puts component.allocated_quantity component = Chargify::Subscription.find(7).component(1) puts component.allocated_quantity # => 23 -``` - -```go -ListAllocations( - ctx context.Context, - subscriptionId int, - componentId int, +``` + +```go +ListAllocations( + ctx context.Context, + subscriptionId int, + componentId int, page *int) ( models.ApiResponse[[]models.AllocationResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | - -## Response Type - -[`[]models.AllocationResponse`](../../doc/models/allocation-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | `int` | Template, Required | The Chargify id of the component | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | + +## Response Type + +[`[]models.AllocationResponse`](../../doc/models/allocation-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 componentId := 222 @@ -611,93 +621,93 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "allocation": { - "allocation_id": 2370199, - "component_id": 41028, - "subscription_id": 352827, - "quantity": 10, - "previous_quantity": 0, - "memo": "Recoding component allocation", - "timestamp": "2024-02-28T09:31:05Z", - "proration_upgrade_scheme": "full-price-attempt-capture", - "proration_downgrade_scheme": "no-prorate", - "price_point_id": 2957424, - "price_point_handle": "uuid:03190e20-b84a-013c-ca77-0286551bb34f", - "price_point_name": "Original", - "previous_price_point_id": 2957424, - "component_handle": "test-prepaid-component-4982065948", - "accrue_charge": false, - "upgrade_charge": "full", - "downgrade_credit": "none", - "created_at": "2024-02-28T04:31:05-05:00", - "initiate_dunning": false, - "expires_at": "2024-08-03T20:00:00-04:00", - "used_quantity": 5, - "charge_id": 11586076 - } - }, - { - "allocation": { - "memo": null, - "timestamp": "2012-11-20T21:48:09Z", - "quantity": 3, - "previous_quantity": 0, - "component_id": 11960, - "subscription_id": 2585595, - "proration_upgrade_scheme": "no-prorate", - "proration_downgrade_scheme": "no-prorate" - } - } -] -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Allocate Components - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "allocation": { + "allocation_id": 2370199, + "component_id": 41028, + "subscription_id": 352827, + "quantity": 10, + "previous_quantity": 0, + "memo": "Recoding component allocation", + "timestamp": "2024-02-28T09:31:05Z", + "proration_upgrade_scheme": "full-price-attempt-capture", + "proration_downgrade_scheme": "no-prorate", + "price_point_id": 2957424, + "price_point_handle": "uuid:03190e20-b84a-013c-ca77-0286551bb34f", + "price_point_name": "Original", + "previous_price_point_id": 2957424, + "component_handle": "test-prepaid-component-4982065948", + "accrue_charge": false, + "upgrade_charge": "full", + "downgrade_credit": "none", + "created_at": "2024-02-28T04:31:05-05:00", + "initiate_dunning": false, + "expires_at": "2024-08-03T20:00:00-04:00", + "used_quantity": 5, + "charge_id": 11586076 + } + }, + { + "allocation": { + "memo": null, + "timestamp": "2012-11-20T21:48:09Z", + "quantity": 3, + "previous_quantity": 0, + "component_id": 11960, + "subscription_id": 2585595, + "proration_upgrade_scheme": "no-prorate", + "proration_downgrade_scheme": "no-prorate" + } + } +] +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Allocate Components + Creates multiple allocations, setting the current allocated quantity for each of the components and recording a memo. The charges and/or credits that are created will be rolled up into a single total which is used to determine whether this is an upgrade or a downgrade. Be aware of the Order of Resolutions explained below in determining the proration scheme. A `component_id` is required for each allocation. -This endpoint only responds to JSON. It is not available for XML. - -```go -AllocateComponents( - ctx context.Context, - subscriptionId int, +This endpoint only responds to JSON. It is not available for XML. + +```go +AllocateComponents( + ctx context.Context, + subscriptionId int, body *models.AllocateComponents) ( models.ApiResponse[[]models.AllocationResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.AllocateComponents`](../../doc/models/allocate-components.md) | Body, Optional | - | - -## Response Type - -[`[]models.AllocationResponse`](../../doc/models/allocation-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.AllocateComponents`](../../doc/models/allocate-components.md) | Body, Optional | - | + +## Response Type + +[`[]models.AllocationResponse`](../../doc/models/allocation-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -727,93 +737,93 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "allocation": { - "component_id": 193159, - "subscription_id": 15540611, - "quantity": 10, - "previous_quantity": 0, - "memo": "foo", - "timestamp": "2016-12-08T19:09:15Z", - "proration_upgrade_scheme": "prorate-attempt-capture", - "proration_downgrade_scheme": "no-prorate", - "payment": { - "amount_in_cents": 1451, - "success": true, - "memo": "Payment for: Prorated component allocation changes.", - "id": 165473487 - } - } - }, - { - "allocation": { - "component_id": 277221, - "subscription_id": 15540611, - "quantity": 5, - "previous_quantity": 0, - "memo": "bar", - "timestamp": "2016-12-08T19:09:15Z", - "proration_upgrade_scheme": "prorate-attempt-capture", - "proration_downgrade_scheme": "no-prorate", - "payment": { - "amount_in_cents": 1451, - "success": true, - "memo": "Payment for: Prorated component allocation changes.", - "id": 165473487 - } - } - } -] -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Preview Allocations - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "allocation": { + "component_id": 193159, + "subscription_id": 15540611, + "quantity": 10, + "previous_quantity": 0, + "memo": "foo", + "timestamp": "2016-12-08T19:09:15Z", + "proration_upgrade_scheme": "prorate-attempt-capture", + "proration_downgrade_scheme": "no-prorate", + "payment": { + "amount_in_cents": 1451, + "success": true, + "memo": "Payment for: Prorated component allocation changes.", + "id": 165473487 + } + } + }, + { + "allocation": { + "component_id": 277221, + "subscription_id": 15540611, + "quantity": 5, + "previous_quantity": 0, + "memo": "bar", + "timestamp": "2016-12-08T19:09:15Z", + "proration_upgrade_scheme": "prorate-attempt-capture", + "proration_downgrade_scheme": "no-prorate", + "payment": { + "amount_in_cents": 1451, + "success": true, + "memo": "Payment for: Prorated component allocation changes.", + "id": 165473487 + } + } + } +] +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Preview Allocations + Chargify offers the ability to preview a potential subscription's **quantity-based** or **on/off** component allocation in the middle of the current billing period. This is useful if you want users to be able to see the effect of a component operation before actually doing it. ## Fine-grained Component Control: Use with multiple `upgrade_charge`s or `downgrade_credits` When the allocation uses multiple different types of `upgrade_charge`s or `downgrade_credit`s, the Allocation is viewed as an Allocation which uses "Fine-Grained Component Control". As a result, the response will not include `direction` and `proration` within the `allocation_preview`, but at the `line_items` and `allocations` level respectfully. -See example below for Fine-Grained Component Control response. - -```go -PreviewAllocations( - ctx context.Context, - subscriptionId int, +See example below for Fine-Grained Component Control response. + +```go +PreviewAllocations( + ctx context.Context, + subscriptionId int, body *models.PreviewAllocationsRequest) ( models.ApiResponse[models.AllocationPreviewResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.PreviewAllocationsRequest`](../../doc/models/preview-allocations-request.md) | Body, Optional | - | - -## Response Type - -[`models.AllocationPreviewResponse`](../../doc/models/allocation-preview-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.PreviewAllocationsRequest`](../../doc/models/preview-allocations-request.md) | Body, Optional | - | + +## Response Type + +[`models.AllocationPreviewResponse`](../../doc/models/allocation-preview-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -821,13 +831,15 @@ bodyEffectiveProrationDate, err := time.Parse(models.DEFAULT_DATE, "2023-11-01") if err != nil { log.Fatalln(err) } +bodyAllocations0PricePointId := models.CreateAllocationPricePointIdContainer.FromNumber(325826) + bodyAllocations0 := models.CreateAllocation{ Quantity: float64(10), ComponentId: models.ToPointer(554108), Memo: models.ToPointer("NOW"), ProrationDowngradeScheme: models.ToPointer("prorate"), ProrationUpgradeScheme: models.ToPointer("prorate-attempt-capture"), - PricePointId: models.NewOptional(models.ToPointer(interface{}("[key1, val1][key2, val2]"))), + PricePointId: models.NewOptional(models.ToPointer(bodyAllocations0PricePointId)), } bodyAllocations := []models.CreateAllocation{bodyAllocations0} @@ -843,121 +855,121 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "allocation_preview": { - "start_date": "2019-05-02T15:26:46Z", - "end_date": "2019-05-08T15:26:46Z", - "period_type": "prorated", - "total_in_cents": 150, - "total_discount_in_cents": 0, - "total_tax_in_cents": 0, - "subtotal_in_cents": 150, - "existing_balance_in_cents": 0, - "accrue_charge": true, - "line_items": [ - { - "direction": "upgrade", - "transaction_type": "charge", - "kind": "quantity_based_component", - "amount_in_cents": 100, - "taxable_amount_in_cents": 0, - "discount_amount_in_cents": 0, - "memo": "Foo: 0 to 10 foo", - "component_id": 123, - "component_handle": "foo" - }, - { - "direction": "downgrade", - "transaction_type": "credit", - "kind": "quantity_based_component", - "amount_in_cents": -20, - "taxable_amount_in_cents": 0, - "discount_amount_in_cents": 0, - "memo": "Foo: 10 to 5 bar", - "component_id": 456, - "component_handle": "bar" - }, - { - "direction": "upgrade", - "transaction_type": "credit", - "kind": "quantity_based_component", - "amount_in_cents": 70, - "taxable_amount_in_cents": 0, - "discount_amount_in_cents": 0, - "memo": "Foo: 0 to 10 baz", - "component_id": 789, - "component_handle": "baz" - } - ], - "allocations": [ - { - "accrue_charge": true, - "upgrade_charge": "prorated", - "downgrade_credit": "full", - "component_handle": "foo", - "component_id": 123, - "memo": "foo", - "previous_price_point_id": 123, - "previous_quantity": 0, - "price_point_id": 123, - "proration_downgrade_scheme": "full", - "proration_upgrade_scheme": "prorate-delay-capture", - "quantity": 10, - "subscription_id": 123456, - "timestamp": null - }, - { - "accrue_charge": true, - "upgrade_charge": "full", - "downgrade_credit": "prorated", - "component_handle": "bar", - "component_id": 456, - "memo": "foo", - "previous_price_point_id": 456, - "previous_quantity": 10, - "price_point_id": 456, - "proration_downgrade_scheme": "prorate", - "proration_upgrade_scheme": "full-price-delay-capture", - "quantity": 5, - "subscription_id": 123456, - "timestamp": null - }, - { - "accrue_charge": true, - "upgrade_charge": "full", - "downgrade_credit": "none", - "component_handle": "baz", - "component_id": 789, - "memo": "foo", - "previous_price_point_id": 789, - "previous_quantity": 0, - "price_point_id": 789, - "proration_downgrade_scheme": "no-prorate", - "proration_upgrade_scheme": "full-price-delay-capture", - "quantity": 10, - "subscription_id": 123456, - "timestamp": null - } - ] - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ComponentAllocationErrorException`](../../doc/models/component-allocation-error-exception.md) | - - -# Update Prepaid Usage Allocation Expiration Date - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "allocation_preview": { + "start_date": "2019-05-02T15:26:46Z", + "end_date": "2019-05-08T15:26:46Z", + "period_type": "prorated", + "total_in_cents": 150, + "total_discount_in_cents": 0, + "total_tax_in_cents": 0, + "subtotal_in_cents": 150, + "existing_balance_in_cents": 0, + "accrue_charge": true, + "line_items": [ + { + "direction": "upgrade", + "transaction_type": "charge", + "kind": "quantity_based_component", + "amount_in_cents": 100, + "taxable_amount_in_cents": 0, + "discount_amount_in_cents": 0, + "memo": "Foo: 0 to 10 foo", + "component_id": 123, + "component_handle": "foo" + }, + { + "direction": "downgrade", + "transaction_type": "credit", + "kind": "quantity_based_component", + "amount_in_cents": -20, + "taxable_amount_in_cents": 0, + "discount_amount_in_cents": 0, + "memo": "Foo: 10 to 5 bar", + "component_id": 456, + "component_handle": "bar" + }, + { + "direction": "upgrade", + "transaction_type": "credit", + "kind": "quantity_based_component", + "amount_in_cents": 70, + "taxable_amount_in_cents": 0, + "discount_amount_in_cents": 0, + "memo": "Foo: 0 to 10 baz", + "component_id": 789, + "component_handle": "baz" + } + ], + "allocations": [ + { + "accrue_charge": true, + "upgrade_charge": "prorated", + "downgrade_credit": "full", + "component_handle": "foo", + "component_id": 123, + "memo": "foo", + "previous_price_point_id": 123, + "previous_quantity": 0, + "price_point_id": 123, + "proration_downgrade_scheme": "full", + "proration_upgrade_scheme": "prorate-delay-capture", + "quantity": 10, + "subscription_id": 123456, + "timestamp": null + }, + { + "accrue_charge": true, + "upgrade_charge": "full", + "downgrade_credit": "prorated", + "component_handle": "bar", + "component_id": 456, + "memo": "foo", + "previous_price_point_id": 456, + "previous_quantity": 10, + "price_point_id": 456, + "proration_downgrade_scheme": "prorate", + "proration_upgrade_scheme": "full-price-delay-capture", + "quantity": 5, + "subscription_id": 123456, + "timestamp": null + }, + { + "accrue_charge": true, + "upgrade_charge": "full", + "downgrade_credit": "none", + "component_handle": "baz", + "component_id": 789, + "memo": "foo", + "previous_price_point_id": 789, + "previous_quantity": 0, + "price_point_id": 789, + "proration_downgrade_scheme": "no-prorate", + "proration_upgrade_scheme": "full-price-delay-capture", + "quantity": 10, + "subscription_id": 123456, + "timestamp": null + } + ] + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ComponentAllocationErrorException`](../../doc/models/component-allocation-error-exception.md) | + + +# Update Prepaid Usage Allocation Expiration Date + When the expiration interval options are selected on a prepaid usage component price point, all allocations will be created with an expiration date. This expiration date can be changed after the fact to allow for extending or shortening the allocation's active window. In order to change a prepaid usage allocation's expiration date, a PUT call must be made to the allocation's endpoint with a new expiration date. @@ -968,35 +980,35 @@ A few limitations exist when changing an allocation's expiration date: - An expiration date can only be changed for an allocation that belongs to a price point with expiration interval options explicitly set. - An expiration date can be changed towards the future with no limitations. -- An expiration date can be changed towards the past (essentially expiring it) up to the subscription's current period beginning date. - -```go -UpdatePrepaidUsageAllocationExpirationDate( - ctx context.Context, - subscriptionId int, - componentId int, - allocationId int, +- An expiration date can be changed towards the past (essentially expiring it) up to the subscription's current period beginning date. + +```go +UpdatePrepaidUsageAllocationExpirationDate( + ctx context.Context, + subscriptionId int, + componentId int, + allocationId int, body *models.UpdateAllocationExpirationDate) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component | -| `allocationId` | `int` | Template, Required | The Chargify id of the allocation | -| `body` | [`*models.UpdateAllocationExpirationDate`](../../doc/models/update-allocation-expiration-date.md) | Body, Optional | - | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | `int` | Template, Required | The Chargify id of the component | +| `allocationId` | `int` | Template, Required | The Chargify id of the allocation | +| `body` | [`*models.UpdateAllocationExpirationDate`](../../doc/models/update-allocation-expiration-date.md) | Body, Optional | - | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 componentId := 222 @@ -1019,19 +1031,19 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionComponentAllocationErrorException`](../../doc/models/subscription-component-allocation-error-exception.md) | - - -# Delete Prepaid Usage Allocation - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionComponentAllocationErrorException`](../../doc/models/subscription-component-allocation-error-exception.md) | + + +# Delete Prepaid Usage Allocation + Prepaid Usage components are unique in that their allocations are always additive. In order to reduce a subscription's allocated quantity for a prepaid usage component each allocation must be destroyed individually via this endpoint. ## Credit Scheme @@ -1040,35 +1052,35 @@ By default, destroying an allocation will generate a service credit on the subsc 1. `none`: The allocation will be destroyed and the balances will be updated but no service credit or refund will be created. 2. `credit`: The allocation will be destroyed and the balances will be updated and a service credit will be generated. This is also the default behavior if the `credit_scheme` param is not passed. -3. `refund`: The allocation will be destroyed and the balances will be updated and a refund will be issued along with a Credit Note. - -```go -DeletePrepaidUsageAllocation( - ctx context.Context, - subscriptionId int, - componentId int, - allocationId int, +3. `refund`: The allocation will be destroyed and the balances will be updated and a refund will be issued along with a Credit Note. + +```go +DeletePrepaidUsageAllocation( + ctx context.Context, + subscriptionId int, + componentId int, + allocationId int, body *models.CreditSchemeRequest) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component | -| `allocationId` | `int` | Template, Required | The Chargify id of the allocation | -| `body` | [`*models.CreditSchemeRequest`](../../doc/models/credit-scheme-request.md) | Body, Optional | - | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | `int` | Template, Required | The Chargify id of the component | +| `allocationId` | `int` | Template, Required | The Chargify id of the allocation | +| `body` | [`*models.CreditSchemeRequest`](../../doc/models/credit-scheme-request.md) | Body, Optional | - | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 componentId := 222 @@ -1083,19 +1095,19 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionComponentAllocationErrorException`](../../doc/models/subscription-component-allocation-error-exception.md) | - - -# Create Usage - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionComponentAllocationErrorException`](../../doc/models/subscription-component-allocation-error-exception.md) | + + +# Create Usage + ## Documentation Full documentation on how to create Components in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#creating-components). Additionally, for information on how to record component usage against a subscription, please see the following resources: @@ -1151,36 +1163,37 @@ The `unit_balance` has a floor of `0`; negative unit balances are never allowed. Q. Is it possible to record metered usage for more than one component at a time? -A. No. Usage should be reported as one API call per component on a single subscription. For example, to record that a subscriber has sent both an SMS Message and an Email, send an API call for each. - -```go -CreateUsage( - ctx context.Context, - subscriptionId int, - componentId interface{}, +A. No. Usage should be reported as one API call per component on a single subscription. For example, to record that a subscriber has sent both an SMS Message and an Email, send an API call for each. + +```go +CreateUsage( + ctx context.Context, + subscriptionId int, + componentId models.CreateUsageComponentId, body *models.CreateUsageRequest) ( models.ApiResponse[models.UsageResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `interface{}` | Template, Required | Either the Chargify id for the component or the component's handle prefixed by `handle:` | -| `body` | [`*models.CreateUsageRequest`](../../doc/models/create-usage-request.md) | Body, Optional | - | - -## Response Type - -[`models.UsageResponse`](../../doc/models/usage-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | [`models.CreateUsageComponentId`](../../doc/models/containers/create-usage-component-id.md) | Template, Required | This is a container for one-of cases. | +| `body` | [`*models.CreateUsageRequest`](../../doc/models/create-usage-request.md) | Body, Optional | - | + +## Response Type + +[`models.UsageResponse`](../../doc/models/usage-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 -componentId := interface{}("[key1, val1][key2, val2]") + +componentId := models.CreateUsageComponentIdContainer.FromNumber(144) bodyUsage := models.CreateUsage{ Quantity: models.ToPointer(float64(1000)), @@ -1199,35 +1212,35 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "usage": { - "id": 138522957, - "memo": "My memo", - "created_at": "2017-11-13T10:05:32-06:00", - "price_point_id": 149416, - "quantity": 1000, - "component_id": 500093, - "component_handle": "handle", - "subscription_id": 22824464 - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Usages - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "usage": { + "id": 138522957, + "memo": "My memo", + "created_at": "2017-11-13T10:05:32-06:00", + "price_point_id": 149416, + "quantity": 1000, + "component_id": 500093, + "component_handle": "handle", + "subscription_id": 22824464 + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Usages + This request will return a list of the usages associated with a subscription for a particular metered component. This will display the previously recorded components for a subscription. This endpoint is not compatible with quantity-based components. @@ -1242,116 +1255,122 @@ Note: The `since_date` and `until_date` attributes each default to midnight on t ## Read Usage by Handle -Use this endpoint to read the previously recorded components for a subscription. You can now specify either the component id (integer) or the component handle prefixed by "handle:" to specify the unique identifier for the component you are working with. - -```go -ListUsages( - ctx context.Context,input ListUsagesInput) ( +Use this endpoint to read the previously recorded components for a subscription. You can now specify either the component id (integer) or the component handle prefixed by "handle:" to specify the unique identifier for the component you are working with. + +```go +ListUsages( + ctx context.Context, + input ListUsagesInput) ( models.ApiResponse[[]models.UsageResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `interface{}` | Template, Required | Either the Chargify id for the component or the component's handle prefixed by `handle:` | -| `sinceId` | `*int` | Query, Optional | Returns usages with an id greater than or equal to the one specified | -| `maxId` | `*int` | Query, Optional | Returns usages with an id less than or equal to the one specified | -| `sinceDate` | `*time.Time` | Query, Optional | Returns usages with a created_at date greater than or equal to midnight (12:00 AM) on the date specified. | -| `untilDate` | `*time.Time` | Query, Optional | Returns usages with a created_at date less than or equal to midnight (12:00 AM) on the date specified. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | - -## Response Type - -[`[]models.UsageResponse`](../../doc/models/usage-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | [`models.ListUsagesInputComponentId`](../../doc/models/containers/list-usages-input-component-id.md) | Template, Required | This is a container for one-of cases. | +| `sinceId` | `*int` | Query, Optional | Returns usages with an id greater than or equal to the one specified | +| `maxId` | `*int` | Query, Optional | Returns usages with an id less than or equal to the one specified | +| `sinceDate` | `*time.Time` | Query, Optional | Returns usages with a created_at date greater than or equal to midnight (12:00 AM) on the date specified. | +| `untilDate` | `*time.Time` | Query, Optional | Returns usages with a created_at date less than or equal to midnight (12:00 AM) on the date specified. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | + +## Response Type + +[`[]models.UsageResponse`](../../doc/models/usage-response.md) + +## Example Usage + +```go ctx := context.Background() -subscriptionId := 222 -componentId := interface{}("[key1, val1][key2, val2]") -page := 2 -perPage := 50 -apiResponse, err := subscriptionComponentsController.ListUsages(ctx, subscriptionId, componentId, nil, nil, nil, nil, &page, &perPage) +collectedInputComponentId := models.ListUsagesInputComponentIdContainer.FromNumber(144) + +collectedInput := advancedbilling.ListUsagesInput{ + SubscriptionId: 222, + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + ComponentId: collectedInputComponentId, +} + +apiResponse, err := subscriptionComponentsController.ListUsages(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "usage": { - "id": 178534642, - "memo": "20", - "created_at": "2018-08-03T11:58:42-05:00", - "price_point_id": 242632, - "quantity": "20.0", - "component_id": 500093, - "component_handle": "handle", - "subscription_id": 22824464 - } - }, - { - "usage": { - "id": 178534591, - "memo": "10", - "created_at": "2018-08-03T11:58:29-05:00", - "price_point_id": 242632, - "quantity": "10.0", - "component_id": 500093, - "component_handle": "handle", - "subscription_id": 22824464 - } - } -] -``` - - -# Activate Event Based Component - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "usage": { + "id": 178534642, + "memo": "20", + "created_at": "2018-08-03T11:58:42-05:00", + "price_point_id": 242632, + "quantity": "20.0", + "component_id": 500093, + "component_handle": "handle", + "subscription_id": 22824464 + } + }, + { + "usage": { + "id": 178534591, + "memo": "10", + "created_at": "2018-08-03T11:58:29-05:00", + "price_point_id": 242632, + "quantity": "10.0", + "component_id": 500093, + "component_handle": "handle", + "subscription_id": 22824464 + } + } +] +``` + + +# Activate Event Based Component + In order to bill your subscribers on your Events data under the Events-Based Billing feature, the components must be activated for the subscriber. Learn more about the role of activation in the [Events-Based Billing docs](https://chargify.zendesk.com/hc/en-us/articles/4407720810907#activating-components-for-subscribers). Use this endpoint to activate an event-based component for a single subscription. Activating an event-based component causes Chargify to bill for events when the subscription is renewed. -*Note: it is possible to stream events for a subscription at any time, regardless of component activation status. The activation status only determines if the subscription should be billed for event-based component usage at renewal.* - -```go -ActivateEventBasedComponent( - ctx context.Context, - subscriptionId int, +*Note: it is possible to stream events for a subscription at any time, regardless of component activation status. The activation status only determines if the subscription should be billed for event-based component usage at renewal.* + +```go +ActivateEventBasedComponent( + ctx context.Context, + subscriptionId int, componentId int) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | `int` | Template, Required | The Chargify id of the component | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 componentId := 222 @@ -1361,37 +1380,37 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - - -# Deactivate Event Based Component - -Use this endpoint to deactivate an event-based component for a single subscription. Deactivating the event-based component causes Chargify to ignore related events at subscription renewal. - -```go -DeactivateEventBasedComponent( - ctx context.Context, - subscriptionId int, +} +``` + + +# Deactivate Event Based Component + +Use this endpoint to deactivate an event-based component for a single subscription. Deactivating the event-based component causes Chargify to ignore related events at subscription renewal. + +```go +DeactivateEventBasedComponent( + ctx context.Context, + subscriptionId int, componentId int) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `componentId` | `int` | Template, Required | The Chargify id of the component | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `componentId` | `int` | Template, Required | The Chargify id of the component | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 componentId := 222 @@ -1401,12 +1420,12 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - - -# Record Event - +} +``` + + +# Record Event + ## Documentation Events-Based Billing is an evolved form of metered billing that is based on data-rich events streamed in real-time from your system to Chargify. @@ -1425,35 +1444,35 @@ Use this endpoint to record a single event. ``` https://events.chargify.com/my-site-subdomain/events/my-stream-api-handle -``` - -```go -RecordEvent( - ctx context.Context, - subdomain string, - apiHandle string, - storeUid *string, +``` + +```go +RecordEvent( + ctx context.Context, + subdomain string, + apiHandle string, + storeUid *string, body *models.EBBEvent) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subdomain` | `string` | Template, Required | Your site's subdomain | -| `apiHandle` | `string` | Template, Required | Identifies the Stream for which the event should be published. | -| `storeUid` | `*string` | Query, Optional | If you've attached your own Keen project as a Chargify event data-store, use this parameter to indicate the data-store. | -| `body` | [`*models.EBBEvent`](../../doc/models/ebb-event.md) | Body, Optional | - | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subdomain` | `string` | Template, Required | Your site's subdomain | +| `apiHandle` | `string` | Template, Required | Identifies the Stream for which the event should be published. | +| `storeUid` | `*string` | Query, Optional | If you've attached your own Keen project as a Chargify event data-store, use this parameter to indicate the data-store. | +| `body` | [`*models.EBBEvent`](../../doc/models/ebb-event.md) | Body, Optional | - | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subdomain := "subdomain4" apiHandle := "api_handle6" @@ -1476,45 +1495,45 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - - -# Bulk Record Events - +} +``` + + +# Bulk Record Events + Use this endpoint to record a collection of events. *Note: this endpoint differs from the standard Chargify endpoints in that the subdomain will be `events` and your site subdomain will be included in the URL path.* -A maximum of 1000 events can be published in a single request. A 422 will be returned if this limit is exceeded. - -```go -BulkRecordEvents( - ctx context.Context, - subdomain string, - apiHandle string, - storeUid *string, +A maximum of 1000 events can be published in a single request. A 422 will be returned if this limit is exceeded. + +```go +BulkRecordEvents( + ctx context.Context, + subdomain string, + apiHandle string, + storeUid *string, body []models.EBBEvent) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subdomain` | `string` | Template, Required | Your site's subdomain | -| `apiHandle` | `string` | Template, Required | Identifies the Stream for which the events should be published. | -| `storeUid` | `*string` | Query, Optional | If you've attached your own Keen project as a Chargify event data-store, use this parameter to indicate the data-store. | -| `body` | [`[]models.EBBEvent`](../../doc/models/ebb-event.md) | Body, Optional | - | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subdomain` | `string` | Template, Required | Your site's subdomain | +| `apiHandle` | `string` | Template, Required | Identifies the Stream for which the events should be published. | +| `storeUid` | `*string` | Query, Optional | If you've attached your own Keen project as a Chargify event data-store, use this parameter to indicate the data-store. | +| `body` | [`[]models.EBBEvent`](../../doc/models/ebb-event.md) | Body, Optional | - | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subdomain := "subdomain4" apiHandle := "api_handle6" @@ -1533,76 +1552,80 @@ body0 := models.EBBEvent{ } body := []models.EBBEvent{body0} -resp, err := subscriptionComponentsController.BulkRecordEvents(ctx, subdomain, apiHandle, nil, body) +resp, err := subscriptionComponentsController.BulkRecordEvents(ctx, subdomain, apiHandle, nil, &body) if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - - -# List Subscription Components for Site - -This request will list components applied to each subscription. - -```go -ListSubscriptionComponentsForSite( - ctx context.Context,input ListSubscriptionComponentsForSiteInput) ( +} +``` + + +# List Subscription Components for Site + +This request will list components applied to each subscription. + +```go +ListSubscriptionComponentsForSite( + ctx context.Context, + input ListSubscriptionComponentsForSiteInput) ( models.ApiResponse[models.ListSubscriptionComponentsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `sort` | [`*models.ListSubscriptionComponentsSort`](../../doc/models/list-subscription-components-sort.md) | Query, Optional | The attribute by which to sort. Use in query: `sort=updated_at`. | -| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | -| `dateField` | [`*models.SubscriptionListDateField`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Use in query: `date_field=updated_at`. | -| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `start_date=2011-12-15`. | -| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `start_datetime=2022-07-01 09:00:05`. | -| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `end_date=2011-12-16`. | -| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `end_datetime=2022-07-01 09:00:05`. | -| `subscriptionIds` | `[]int` | Query, Optional | Allows fetching components allocation with matching subscription id based on provided ids. Use in query `subscription_ids=1,2,3`. | -| `pricePointIds` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching components allocation only if price point id is present. Use in query `price_point_ids=not_null`. | -| `productFamilyIds` | `[]int` | Query, Optional | Allows fetching components allocation with matching product family id based on provided ids. Use in query `product_family_ids=1,2,3`. | -| `include` | [`*models.ListSubscriptionComponentsInclude`](../../doc/models/list-subscription-components-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=subscription`. | -| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching components allocation with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | -| `filterCurrencies` | `[]string` | Query, Optional | Allows fetching components allocation with matching currency based on provided values. Use in query `filter[currencies]=USD,EUR`. | -| `filterSubscriptionStates` | [`[]models.SubscriptionStateFilter`](../../doc/models/subscription-state-filter.md) | Query, Optional | Allows fetching components allocations that belong to the subscription with matching states based on provided values. To use this filter you also have to include the following param in the request `include=subscription`. Use in query `filter[subscription][states]=active,canceled&include=subscription`. | -| `filterSubscriptionDateField` | [`*models.SubscriptionListDateField`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. To use this filter you also have to include the following param in the request `include=subscription`. | -| `filterSubscriptionStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. To use this filter you also have to include the following param in the request `include=subscription`. | -| `filterSubscriptionStartDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. To use this filter you also have to include the following param in the request `include=subscription`. | -| `filterSubscriptionEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components that belong to the subscription with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. To use this filter you also have to include the following param in the request `include=subscription`. | -| `filterSubscriptionEndDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. To use this filter you also have to include the following param in the request `include=subscription`. | - -## Response Type - -[`models.ListSubscriptionComponentsResponse`](../../doc/models/list-subscription-components-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `sort` | [`*models.ListSubscriptionComponentsSort`](../../doc/models/list-subscription-components-sort.md) | Query, Optional | The attribute by which to sort. Use in query: `sort=updated_at`. | +| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | +| `dateField` | [`*models.SubscriptionListDateField`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Use in query: `date_field=updated_at`. | +| `startDate` | `*string` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `start_date=2011-12-15`. | +| `startDatetime` | `*string` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `start_datetime=2022-07-01 09:00:05`. | +| `endDate` | `*string` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `end_date=2011-12-16`. | +| `endDatetime` | `*string` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `end_datetime=2022-07-01 09:00:05`. | +| `subscriptionIds` | `[]int` | Query, Optional | Allows fetching components allocation with matching subscription id based on provided ids. Use in query `subscription_ids=1,2,3`. | +| `pricePointIds` | [`*models.IncludeNotNull`](../../doc/models/include-not-null.md) | Query, Optional | Allows fetching components allocation only if price point id is present. Use in query `price_point_ids=not_null`. | +| `productFamilyIds` | `[]int` | Query, Optional | Allows fetching components allocation with matching product family id based on provided ids. Use in query `product_family_ids=1,2,3`. | +| `include` | [`*models.ListSubscriptionComponentsInclude`](../../doc/models/list-subscription-components-include.md) | Query, Optional | Allows including additional data in the response. Use in query `include=subscription`. | +| `filterUseSiteExchangeRate` | `*bool` | Query, Optional | Allows fetching components allocation with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. | +| `filterCurrencies` | `[]string` | Query, Optional | Allows fetching components allocation with matching currency based on provided values. Use in query `filter[currencies]=USD,EUR`. | +| `filterSubscriptionStates` | [`[]models.SubscriptionStateFilter`](../../doc/models/subscription-state-filter.md) | Query, Optional | Allows fetching components allocations that belong to the subscription with matching states based on provided values. To use this filter you also have to include the following param in the request `include=subscription`. Use in query `filter[subscription][states]=active,canceled&include=subscription`. | +| `filterSubscriptionDateField` | [`*models.SubscriptionListDateField`](../../doc/models/subscription-list-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. To use this filter you also have to include the following param in the request `include=subscription`. | +| `filterSubscriptionStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. To use this filter you also have to include the following param in the request `include=subscription`. | +| `filterSubscriptionStartDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. To use this filter you also have to include the following param in the request `include=subscription`. | +| `filterSubscriptionEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components that belong to the subscription with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. To use this filter you also have to include the following param in the request `include=subscription`. | +| `filterSubscriptionEndDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. To use this filter you also have to include the following param in the request `include=subscription`. | + +## Response Type + +[`models.ListSubscriptionComponentsResponse`](../../doc/models/list-subscription-components-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -sort := models.ListSubscriptionComponentsSort("updated_at") -dateField := models.SubscriptionListDateField("updated_at") -subscriptionIds := []int{1, 2, 3} -pricePointIds := models.IncludeNotNull("not_null") -productFamilyIds := []int{1, 2, 3} -include := models.ListSubscriptionComponentsInclude("subscription")Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') - -apiResponse, err := subscriptionComponentsController.ListSubscriptionComponentsForSite(ctx, &page, &perPage, &sort, nil, &dateField, nil, nil, nil, nil, subscriptionIds, &pricePointIds, productFamilyIds, &include, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key')) +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') +collectedInput := advancedbilling.ListSubscriptionComponentsForSiteInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + Sort: models.ToPointer(models.ListSubscriptionComponentsSort("updated_at")), + DateField: models.ToPointer(models.SubscriptionListDateField("updated_at")), + SubscriptionIds: []int{1, 2, 3}, + PricePointIds: models.ToPointer(models.IncludeNotNull("not_null")), + ProductFamilyIds: []int{1, 2, 3}, + Include: models.ToPointer(models.ListSubscriptionComponentsInclude("subscription")), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := subscriptionComponentsController.ListSubscriptionComponentsForSite(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - +} +``` + diff --git a/doc/controllers/subscription-group-invoice-account.md b/doc/controllers/subscription-group-invoice-account.md index 98e31568..4c418bcf 100644 --- a/doc/controllers/subscription-group-invoice-account.md +++ b/doc/controllers/subscription-group-invoice-account.md @@ -1,48 +1,48 @@ -# Subscription Group Invoice Account - -```go -subscriptionGroupInvoiceAccountController := client.SubscriptionGroupInvoiceAccountController() -``` - -## Class Name - -`SubscriptionGroupInvoiceAccountController` - -## Methods - +# Subscription Group Invoice Account + +```go +subscriptionGroupInvoiceAccountController := client.SubscriptionGroupInvoiceAccountController() +``` + +## Class Name + +`SubscriptionGroupInvoiceAccountController` + +## Methods + * [Create Subscription Group Prepayment](../../doc/controllers/subscription-group-invoice-account.md#create-subscription-group-prepayment) * [List Prepayments for Subscription Group](../../doc/controllers/subscription-group-invoice-account.md#list-prepayments-for-subscription-group) * [Issue Subscription Group Service Credit](../../doc/controllers/subscription-group-invoice-account.md#issue-subscription-group-service-credit) -* [Deduct Subscription Group Service Credit](../../doc/controllers/subscription-group-invoice-account.md#deduct-subscription-group-service-credit) - - -# Create Subscription Group Prepayment - -A prepayment can be added for a subscription group identified by the group's `uid`. This endpoint requires a `amount`, `details`, `method`, and `memo`. On success, the prepayment will be added to the group's prepayment balance. - -```go -CreateSubscriptionGroupPrepayment( - ctx context.Context, - uid string, +* [Deduct Subscription Group Service Credit](../../doc/controllers/subscription-group-invoice-account.md#deduct-subscription-group-service-credit) + + +# Create Subscription Group Prepayment + +A prepayment can be added for a subscription group identified by the group's `uid`. This endpoint requires a `amount`, `details`, `method`, and `memo`. On success, the prepayment will be added to the group's prepayment balance. + +```go +CreateSubscriptionGroupPrepayment( + ctx context.Context, + uid string, body *models.SubscriptionGroupPrepaymentRequest) ( models.ApiResponse[models.SubscriptionGroupPrepaymentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `body` | [`*models.SubscriptionGroupPrepaymentRequest`](../../doc/models/subscription-group-prepayment-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionGroupPrepaymentResponse`](../../doc/models/subscription-group-prepayment-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `body` | [`*models.SubscriptionGroupPrepaymentRequest`](../../doc/models/subscription-group-prepayment-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionGroupPrepaymentResponse`](../../doc/models/subscription-group-prepayment-response.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -53,134 +53,140 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "id": 6049554, - "amount_in_cents": 10000, - "ending_balance_in_cents": 5000, - "entry_type": "Debit", - "memo": "Debit from invoice account." -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Prepayments for Subscription Group - -This request will list a subscription group's prepayments. - -```go -ListPrepaymentsForSubscriptionGroup( - ctx context.Context,input ListPrepaymentsForSubscriptionGroupInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "id": 6049554, + "amount_in_cents": 10000, + "ending_balance_in_cents": 5000, + "entry_type": "Debit", + "memo": "Debit from invoice account." +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Prepayments for Subscription Group + +This request will list a subscription group's prepayments. + +```go +ListPrepaymentsForSubscriptionGroup( + ctx context.Context, + input ListPrepaymentsForSubscriptionGroupInput) ( models.ApiResponse[models.ListSubscriptionGroupPrepaymentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `filterDateField` | [`*models.ListSubscriptionGroupPrepaymentDateField`](../../doc/models/list-subscription-group-prepayment-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `filter[date_field]=created_at`. | -| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field.
Returns prepayments with a timestamp up to and including 11:59:59PM in your site's time zone on the date specified.
Use in query: `filter[end_date]=2011-12-15`. | -| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field.
Returns prepayments with a timestamp at or after midnight (12:00:00 AM) in your site's time zone on the date specified.
Use in query: `filter[start_date]=2011-12-15`. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | - -## Response Type - -[`models.ListSubscriptionGroupPrepaymentResponse`](../../doc/models/list-subscription-group-prepayment-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `filterDateField` | [`*models.ListSubscriptionGroupPrepaymentDateField`](../../doc/models/list-subscription-group-prepayment-date-field.md) | Query, Optional | The type of filter you would like to apply to your search.
Use in query: `filter[date_field]=created_at`. | +| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field.
Returns prepayments with a timestamp up to and including 11:59:59PM in your site's time zone on the date specified.
Use in query: `filter[end_date]=2011-12-15`. | +| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field.
Returns prepayments with a timestamp at or after midnight (12:00:00 AM) in your site's time zone on the date specified.
Use in query: `filter[start_date]=2011-12-15`. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | + +## Response Type + +[`models.ListSubscriptionGroupPrepaymentResponse`](../../doc/models/list-subscription-group-prepayment-response.md) + +## Example Usage + +```go ctx := context.Background() -uid := "uid0"Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') -page := 2 -perPage := 50 +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') +collectedInput := advancedbilling.ListPrepaymentsForSubscriptionGroupInput{ + Uid: "uid0", +Liquid error: Value cannot be null. (Parameter 'key') Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} -apiResponse, err := subscriptionGroupInvoiceAccountController.ListPrepaymentsForSubscriptionGroup(ctx, uid, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), &page, &perPage) +apiResponse, err := subscriptionGroupInvoiceAccountController.ListPrepaymentsForSubscriptionGroup(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "prepayments": [ - { - "prepayment": { - "id": 142, - "subscription_group_uid": "grp_b4qhx3bvx72t8", - "amount_in_cents": 10000, - "remaining_amount_in_cents": 10000, - "details": "test", - "external": true, - "memo": "test", - "payment_type": "cash", - "created_at": "2023-06-21T04:37:02-04:00" - } - } - ] -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Issue Subscription Group Service Credit - -Credit can be issued for a subscription group identified by the group's `uid`. Credit will be added to the group in the amount specified in the request body. The credit will be applied to group member invoices as they are generated. - -```go -IssueSubscriptionGroupServiceCredit( - ctx context.Context, - uid string, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "prepayments": [ + { + "prepayment": { + "id": 142, + "subscription_group_uid": "grp_b4qhx3bvx72t8", + "amount_in_cents": 10000, + "remaining_amount_in_cents": 10000, + "details": "test", + "external": true, + "memo": "test", + "payment_type": "cash", + "created_at": "2023-06-21T04:37:02-04:00" + } + } + ] +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Issue Subscription Group Service Credit + +Credit can be issued for a subscription group identified by the group's `uid`. Credit will be added to the group in the amount specified in the request body. The credit will be applied to group member invoices as they are generated. + +```go +IssueSubscriptionGroupServiceCredit( + ctx context.Context, + uid string, body *models.IssueServiceCreditRequest) ( models.ApiResponse[models.ServiceCreditResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `body` | [`*models.IssueServiceCreditRequest`](../../doc/models/issue-service-credit-request.md) | Body, Optional | - | - -## Response Type - -[`models.ServiceCreditResponse`](../../doc/models/service-credit-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `body` | [`*models.IssueServiceCreditRequest`](../../doc/models/issue-service-credit-request.md) | Body, Optional | - | + +## Response Type + +[`models.ServiceCreditResponse`](../../doc/models/service-credit-response.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" +bodyServiceCreditAmount := models.IssueServiceCreditAmountContainer.FromPrecision(float64(10)) + bodyServiceCredit := models.IssueServiceCredit{ - Amount: interface{}("[key1, val1][key2, val2]"), Memo: "Credit the group account", + Amount: bodyServiceCreditAmount, } body := models.IssueServiceCreditRequest{ @@ -194,63 +200,65 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "service_credit": { - "id": 101, - "amount_in_cents": 1000, - "ending_balance_in_cents": 2000, - "entry_type": "Credit", - "memo": "Credit to group account" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Deduct Subscription Group Service Credit - -Credit can be deducted for a subscription group identified by the group's `uid`. Credit will be deducted from the group in the amount specified in the request body. - -```go -DeductSubscriptionGroupServiceCredit( - ctx context.Context, - uid string, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "service_credit": { + "id": 101, + "amount_in_cents": 1000, + "ending_balance_in_cents": 2000, + "entry_type": "Credit", + "memo": "Credit to group account" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Deduct Subscription Group Service Credit + +Credit can be deducted for a subscription group identified by the group's `uid`. Credit will be deducted from the group in the amount specified in the request body. + +```go +DeductSubscriptionGroupServiceCredit( + ctx context.Context, + uid string, body *models.DeductServiceCreditRequest) ( models.ApiResponse[models.ServiceCredit], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `body` | [`*models.DeductServiceCreditRequest`](../../doc/models/deduct-service-credit-request.md) | Body, Optional | - | - -## Response Type - -[`models.ServiceCredit`](../../doc/models/service-credit.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `body` | [`*models.DeductServiceCreditRequest`](../../doc/models/deduct-service-credit-request.md) | Body, Optional | - | + +## Response Type + +[`models.ServiceCredit`](../../doc/models/service-credit.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" +bodyDeductionAmount := models.DeductServiceCreditAmountContainer.FromPrecision(float64(10)) + bodyDeduction := models.DeductServiceCredit{ - Amount: interface{}("[key1, val1][key2, val2]"), Memo: "Deduct from group account", + Amount: bodyDeductionAmount, } body := models.DeductServiceCreditRequest{ @@ -264,24 +272,24 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "id": 100, - "amount_in_cents": 1000, - "ending_balance_in_cents": 0, - "entry_type": "Debit", - "memo": "Debit from group account" -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "id": 100, + "amount_in_cents": 1000, + "ending_balance_in_cents": 0, + "entry_type": "Debit", + "memo": "Debit from group account" +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/controllers/subscription-group-status.md b/doc/controllers/subscription-group-status.md index 07f50deb..a6bb2176 100644 --- a/doc/controllers/subscription-group-status.md +++ b/doc/controllers/subscription-group-status.md @@ -1,50 +1,50 @@ -# Subscription Group Status - -```go -subscriptionGroupStatusController := client.SubscriptionGroupStatusController() -``` - -## Class Name - -`SubscriptionGroupStatusController` - -## Methods - +# Subscription Group Status + +```go +subscriptionGroupStatusController := client.SubscriptionGroupStatusController() +``` + +## Class Name + +`SubscriptionGroupStatusController` + +## Methods + * [Cancel Subscriptions in Group](../../doc/controllers/subscription-group-status.md#cancel-subscriptions-in-group) * [Initiate Delayed Cancellation for Group](../../doc/controllers/subscription-group-status.md#initiate-delayed-cancellation-for-group) * [Cancel Delayed Cancellation for Group](../../doc/controllers/subscription-group-status.md#cancel-delayed-cancellation-for-group) -* [Reactivate Subscription Group](../../doc/controllers/subscription-group-status.md#reactivate-subscription-group) - - -# Cancel Subscriptions in Group - +* [Reactivate Subscription Group](../../doc/controllers/subscription-group-status.md#reactivate-subscription-group) + + +# Cancel Subscriptions in Group + This endpoint will immediately cancel all subscriptions within the specified group. The group is identified by it's `uid` passed in the URL. To successfully cancel the group, the primary subscription must be on automatic billing. The group members as well must be on automatic billing or they must be prepaid. -In order to cancel a subscription group while also charging for any unbilled usage on metered or prepaid components, the `charge_unbilled_usage=true` parameter must be included in the request. - -```go -CancelSubscriptionsInGroup( - ctx context.Context, - uid string, +In order to cancel a subscription group while also charging for any unbilled usage on metered or prepaid components, the `charge_unbilled_usage=true` parameter must be included in the request. + +```go +CancelSubscriptionsInGroup( + ctx context.Context, + uid string, body *models.CancelGroupedSubscriptionsRequest) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `body` | [`*models.CancelGroupedSubscriptionsRequest`](../../doc/models/cancel-grouped-subscriptions-request.md) | Body, Optional | - | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `body` | [`*models.CancelGroupedSubscriptionsRequest`](../../doc/models/cancel-grouped-subscriptions-request.md) | Body, Optional | - | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -57,43 +57,43 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Initiate Delayed Cancellation for Group - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Initiate Delayed Cancellation for Group + This endpoint will schedule all subscriptions within the specified group to be canceled at the end of their billing period. The group is identified by it's uid passed in the URL. -All subscriptions in the group must be on automatic billing in order to successfully cancel them, and the group must not be in a "past_due" state. - -```go -InitiateDelayedCancellationForGroup( - ctx context.Context, +All subscriptions in the group must be on automatic billing in order to successfully cancel them, and the group must not be in a "past_due" state. + +```go +InitiateDelayedCancellationForGroup( + ctx context.Context, uid string) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -102,41 +102,41 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Cancel Delayed Cancellation for Group - -Removing the delayed cancellation on a subscription group will ensure that the subscriptions do not get canceled at the end of the period. The request will reset the `cancel_at_end_of_period` flag to false on each member in the group. - -```go -CancelDelayedCancellationForGroup( - ctx context.Context, +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Cancel Delayed Cancellation for Group + +Removing the delayed cancellation on a subscription group will ensure that the subscriptions do not get canceled at the end of the period. The request will reset the `cancel_at_end_of_period` flag to false on each member in the group. + +```go +CancelDelayedCancellationForGroup( + ctx context.Context, uid string) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -145,18 +145,18 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Reactivate Subscription Group - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Reactivate Subscription Group + This endpoint will attempt to reactivate or resume a cancelled subscription group. Upon reactivation, any canceled invoices created after the beginning of the primary subscription's billing period will be reopened and payment will be attempted on them. If the subscription group is being reactivated (as opposed to resumed), new charges will also be assessed for the new billing period. Whether a subscription group is reactivated (a new billing period is created) or resumed (the current billing period is respected) will depend on the parameters that are sent with the request as well as the date of the request relative to the primary subscription's period. @@ -175,31 +175,31 @@ In this case, a subscription group can only be reactivated with a new billing pe Member subscriptions can have billing periods that are longer than the primary (e.g. a monthly primary with annual group members). If the primary subscription in a group cannot be reactivated within the current period, but other group members can be, passing `resume_members=true` will resume the existing billing period for eligible group members. The primary subscription will begin a new billing period. -For calendar billing subscriptions, the new billing period created will be a partial one, spanning from the date of reactivation to the next corresponding calendar renewal date. - -```go -ReactivateSubscriptionGroup( - ctx context.Context, - uid string, +For calendar billing subscriptions, the new billing period created will be a partial one, spanning from the date of reactivation to the next corresponding calendar renewal date. + +```go +ReactivateSubscriptionGroup( + ctx context.Context, + uid string, body *models.ReactivateSubscriptionGroupRequest) ( models.ApiResponse[models.ReactivateSubscriptionGroupResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `body` | [`*models.ReactivateSubscriptionGroupRequest`](../../doc/models/reactivate-subscription-group-request.md) | Body, Optional | - | - -## Response Type - -[`models.ReactivateSubscriptionGroupResponse`](../../doc/models/reactivate-subscription-group-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `body` | [`*models.ReactivateSubscriptionGroupRequest`](../../doc/models/reactivate-subscription-group-request.md) | Body, Optional | - | + +## Response Type + +[`models.ReactivateSubscriptionGroupResponse`](../../doc/models/reactivate-subscription-group-response.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -214,31 +214,31 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "uid": "grp_93wgm89cbjkw6", - "scheme": 1, - "customer_id": 1, - "payment_profile_id": 1, - "subscription_ids": [ - 1, - 2 - ], - "primary_subscription_id": 1, - "next_assessment_at": "2020-06-18T12:00:00-04:00", - "state": "active", - "cancel_at_end_of_period": false -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "uid": "grp_93wgm89cbjkw6", + "scheme": 1, + "customer_id": 1, + "payment_profile_id": 1, + "subscription_ids": [ + 1, + 2 + ], + "primary_subscription_id": 1, + "next_assessment_at": "2020-06-18T12:00:00-04:00", + "state": "active", + "cancel_at_end_of_period": false +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/controllers/subscription-groups.md b/doc/controllers/subscription-groups.md index 37f42745..93008553 100644 --- a/doc/controllers/subscription-groups.md +++ b/doc/controllers/subscription-groups.md @@ -1,15 +1,15 @@ -# Subscription Groups - -```go -subscriptionGroupsController := client.SubscriptionGroupsController() -``` - -## Class Name - -`SubscriptionGroupsController` - -## Methods - +# Subscription Groups + +```go +subscriptionGroupsController := client.SubscriptionGroupsController() +``` + +## Class Name + +`SubscriptionGroupsController` + +## Methods + * [Signup With Subscription Group](../../doc/controllers/subscription-groups.md#signup-with-subscription-group) * [Create Subscription Group](../../doc/controllers/subscription-groups.md#create-subscription-group) * [List Subscription Groups](../../doc/controllers/subscription-groups.md#list-subscription-groups) @@ -18,11 +18,11 @@ subscriptionGroupsController := client.SubscriptionGroupsController() * [Delete Subscription Group](../../doc/controllers/subscription-groups.md#delete-subscription-group) * [Find Subscription Group](../../doc/controllers/subscription-groups.md#find-subscription-group) * [Add Subscription to Group](../../doc/controllers/subscription-groups.md#add-subscription-to-group) -* [Remove Subscription From Group](../../doc/controllers/subscription-groups.md#remove-subscription-from-group) - - -# Signup With Subscription Group - +* [Remove Subscription From Group](../../doc/controllers/subscription-groups.md#remove-subscription-from-group) + + +# Signup With Subscription Group + Create multiple subscriptions at once under the same customer and consolidate them into a subscription group. You must provide one and only one of the `payer_id`/`payer_reference`/`payer_attributes` for the customer attached to the group. @@ -31,29 +31,29 @@ You must provide one and only one of the `payment_profile_id`/`credit_card_attri Only one of the `subscriptions` can have `"primary": true` attribute set. -When passing product to a subscription you can use either `product_id` or `product_handle` or `offer_id`. You can also use `custom_price` instead. - -```go -SignupWithSubscriptionGroup( - ctx context.Context, +When passing product to a subscription you can use either `product_id` or `product_handle` or `offer_id`. You can also use `custom_price` instead. + +```go +SignupWithSubscriptionGroup( + ctx context.Context, body *models.SubscriptionGroupSignupRequest) ( models.ApiResponse[models.SubscriptionGroupSignupResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.SubscriptionGroupSignupRequest`](../../doc/models/subscription-group-signup-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionGroupSignupResponse`](../../doc/models/subscription-group-signup-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.SubscriptionGroupSignupRequest`](../../doc/models/subscription-group-signup-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionGroupSignupResponse`](../../doc/models/subscription-group-signup-response.md) + +## Example Usage + +```go ctx := context.Background() bodySubscriptionGroupSubscriptions0 := models.SubscriptionGroupSignupItem{ @@ -87,45 +87,45 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionGroupSignupErrorResponseException`](../../doc/models/subscription-group-signup-error-response-exception.md) | - - -# Create Subscription Group - -Creates a subscription group with given members. - -```go -CreateSubscriptionGroup( - ctx context.Context, +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionGroupSignupErrorResponseException`](../../doc/models/subscription-group-signup-error-response-exception.md) | + + +# Create Subscription Group + +Creates a subscription group with given members. + +```go +CreateSubscriptionGroup( + ctx context.Context, body *models.CreateSubscriptionGroupRequest) ( models.ApiResponse[models.SubscriptionGroupResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.CreateSubscriptionGroupRequest`](../../doc/models/create-subscription-group-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionGroupResponse`](../../doc/models/subscription-group-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.CreateSubscriptionGroupRequest`](../../doc/models/create-subscription-group-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionGroupResponse`](../../doc/models/subscription-group-response.md) + +## Example Usage + +```go ctx := context.Background() bodySubscriptionGroup := models.CreateSubscriptionGroup{ - SubscriptionId: interface{}("[key1, val1][key2, val2]"), + SubscriptionId: 1, MemberIds: []int{2, 3, 4}, } @@ -140,234 +140,240 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription_group": { - "customer_id": 1, - "payment_profile": { - "id": 1, - "first_name": "t", - "last_name": "t", - "masked_card_number": "XXXX-XXXX-XXXX-1" - }, - "payment_collection_method": "automatic", - "subscription_ids": [ - 1, - 2 - ], - "created_at": "2021-01-21T05:47:38-05:00" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SingleStringErrorResponseException`](../../doc/models/single-string-error-response-exception.md) | - - -# List Subscription Groups - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription_group": { + "customer_id": 1, + "payment_profile": { + "id": 1, + "first_name": "t", + "last_name": "t", + "masked_card_number": "XXXX-XXXX-XXXX-1" + }, + "payment_collection_method": "automatic", + "subscription_ids": [ + 1, + 2 + ], + "created_at": "2021-01-21T05:47:38-05:00" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionGroupCreateErrorResponseException`](../../doc/models/subscription-group-create-error-response-exception.md) | + + +# List Subscription Groups + Returns an array of subscription groups for the site. The response is paginated and will return a `meta` key with pagination information. #### Account Balance Information -Account balance information for the subscription groups is not returned by default. If this information is desired, the `include[]=account_balances` parameter must be provided with the request. - -```go -ListSubscriptionGroups( - ctx context.Context,input ListSubscriptionGroupsInput) ( +Account balance information for the subscription groups is not returned by default. If this information is desired, the `include[]=account_balances` parameter must be provided with the request. + +```go +ListSubscriptionGroups( + ctx context.Context, + input ListSubscriptionGroupsInput) ( models.ApiResponse[models.ListSubscriptionGroupsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `include` | `*string` | Query, Optional | A list of additional information to include in the response. The following values are supported:

- `account_balances`: Account balance information for the subscription groups. Use in query: `include[]=account_balances` | - -## Response Type - -[`models.ListSubscriptionGroupsResponse`](../../doc/models/list-subscription-groups-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `include` | [`[]models.SubscriptionGroupsListInclude`](../../doc/models/subscription-groups-list-include.md) | Query, Optional | A list of additional information to include in the response. The following values are supported:

- `account_balances`: Account balance information for the subscription groups. Use in query: `include[]=account_balances` | + +## Response Type + +[`models.ListSubscriptionGroupsResponse`](../../doc/models/list-subscription-groups-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -apiResponse, err := subscriptionGroupsController.ListSubscriptionGroups(ctx, &page, &perPage, nil) +collectedInput := advancedbilling.ListSubscriptionGroupsInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +Liquid error: Value cannot be null. (Parameter 'key')} + +apiResponse, err := subscriptionGroupsController.ListSubscriptionGroups(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription_groups": [ - { - "uid": "grp_952mvqcnk53wq", - "scheme": 1, - "customer_id": 88498000, - "payment_profile_id": 93063018, - "subscription_ids": [ - 42768907, - 82370782 - ], - "primary_subscription_id": 69844395, - "next_assessment_at": "2021-05-05T16:00:21-04:00", - "state": "active", - "cancel_at_end_of_period": false, - "account_balances": { - "prepayments": { - "balance_in_cents": 0 - }, - "service_credits": { - "balance_in_cents": 0 - }, - "pending_discounts": { - "balance_in_cents": 0 - } - } - } - ], - "meta": { - "current_page": 1, - "total_count": 1 - } -} -``` - - -# Read Subscription Group - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription_groups": [ + { + "uid": "grp_952mvqcnk53wq", + "scheme": 1, + "customer_id": 88498000, + "payment_profile_id": 93063018, + "subscription_ids": [ + 42768907, + 82370782 + ], + "primary_subscription_id": 69844395, + "next_assessment_at": "2021-05-05T16:00:21-04:00", + "state": "active", + "cancel_at_end_of_period": false, + "account_balances": { + "prepayments": { + "balance_in_cents": 0 + }, + "service_credits": { + "balance_in_cents": 0 + }, + "pending_discounts": { + "balance_in_cents": 0 + } + } + } + ], + "meta": { + "current_page": 1, + "total_count": 1 + } +} +``` + + +# Read Subscription Group + Use this endpoint to find subscription group details. #### Current Billing Amount in Cents -Current billing amount for the subscription group is not returned by default. If this information is desired, the `include[]=current_billing_amount_in_cents` parameter must be provided with the request. - -```go -ReadSubscriptionGroup( - ctx context.Context, - uid string) ( +Current billing amount for the subscription group is not returned by default. If this information is desired, the `include[]=current_billing_amount_in_cents` parameter must be provided with the request. + +```go +ReadSubscriptionGroup( + ctx context.Context, + uid string, + include []models.SubscriptionGroupInclude) ( models.ApiResponse[models.FullSubscriptionGroupResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | - -## Response Type - -[`models.FullSubscriptionGroupResponse`](../../doc/models/full-subscription-group-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `include` | [`[]models.SubscriptionGroupInclude`](../../doc/models/subscription-group-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include[]=current_billing_amount_in_cents`. | + +## Response Type + +[`models.FullSubscriptionGroupResponse`](../../doc/models/full-subscription-group-response.md) + +## Example Usage + +```go ctx := context.Background() -uid := "uid0" +uid := "uid0"Liquid error: Value cannot be null. (Parameter 'key') -apiResponse, err := subscriptionGroupsController.ReadSubscriptionGroup(ctx, uid) +apiResponse, err := subscriptionGroupsController.ReadSubscriptionGroup(ctx, uid, Liquid error: Value cannot be null. (Parameter 'key')) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "uid": "grp_939ktzq8v4477", - "scheme": 1, - "customer_id": 400, - "payment_profile_id": 567, - "subscription_ids": [ - 101, - 102, - 103 - ], - "primary_subscription_id": 101, - "next_assessment_at": "2020-08-01T14:00:00-05:00", - "state": "active", - "cancel_at_end_of_period": false, - "current_billing_amount_in_cents": 11500, - "customer": { - "first_name": "Mark", - "last_name": "Wannabewahlberg", - "organization": "The Funky Bunch", - "email": "markymark@example.com", - "reference": "4c92223b-bc16-4d0d-87ff-b177a89a2655" - }, - "account_balances": { - "prepayments": { - "balance_in_cents": 0 - }, - "service_credits": { - "balance_in_cents": 0 - }, - "open_invoices": { - "balance_in_cents": 4400 - }, - "pending_discounts": { - "balance_in_cents": 0 - } - } -} -``` - - -# Update Subscription Group Members - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "uid": "grp_939ktzq8v4477", + "scheme": 1, + "customer_id": 400, + "payment_profile_id": 567, + "subscription_ids": [ + 101, + 102, + 103 + ], + "primary_subscription_id": 101, + "next_assessment_at": "2020-08-01T14:00:00-05:00", + "state": "active", + "cancel_at_end_of_period": false, + "current_billing_amount_in_cents": 11500, + "customer": { + "first_name": "Mark", + "last_name": "Wannabewahlberg", + "organization": "The Funky Bunch", + "email": "markymark@example.com", + "reference": "4c92223b-bc16-4d0d-87ff-b177a89a2655" + }, + "account_balances": { + "prepayments": { + "balance_in_cents": 0 + }, + "service_credits": { + "balance_in_cents": 0 + }, + "open_invoices": { + "balance_in_cents": 4400 + }, + "pending_discounts": { + "balance_in_cents": 0 + } + } +} +``` + + +# Update Subscription Group Members + Use this endpoint to update subscription group members. -`"member_ids": []` should contain an array of both subscription IDs to set as group members and subscription IDs already present in the groups. Not including them will result in removing them from subscription group. To clean up members, just leave the array empty. - -```go -UpdateSubscriptionGroupMembers( - ctx context.Context, - uid string, +`"member_ids": []` should contain an array of both subscription IDs to set as group members and subscription IDs already present in the groups. Not including them will result in removing them from subscription group. To clean up members, just leave the array empty. + +```go +UpdateSubscriptionGroupMembers( + ctx context.Context, + uid string, body *models.UpdateSubscriptionGroupRequest) ( models.ApiResponse[models.SubscriptionGroupResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | -| `body` | [`*models.UpdateSubscriptionGroupRequest`](../../doc/models/update-subscription-group-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionGroupResponse`](../../doc/models/subscription-group-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | +| `body` | [`*models.UpdateSubscriptionGroupRequest`](../../doc/models/update-subscription-group-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionGroupResponse`](../../doc/models/subscription-group-response.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -386,63 +392,63 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription_group": { - "customer_id": 1, - "payment_profile": { - "id": 1, - "first_name": "t", - "last_name": "t", - "masked_card_number": "XXXX-XXXX-XXXX-1" - }, - "payment_collection_method": "automatic", - "subscription_ids": [ - 1 - ], - "created_at": "2021-01-21T05:47:38-05:00" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionGroupUpdateErrorResponseException`](../../doc/models/subscription-group-update-error-response-exception.md) | - - -# Delete Subscription Group - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription_group": { + "customer_id": 1, + "payment_profile": { + "id": 1, + "first_name": "t", + "last_name": "t", + "masked_card_number": "XXXX-XXXX-XXXX-1" + }, + "payment_collection_method": "automatic", + "subscription_ids": [ + 1 + ], + "created_at": "2021-01-21T05:47:38-05:00" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionGroupUpdateErrorResponseException`](../../doc/models/subscription-group-update-error-response-exception.md) | + + +# Delete Subscription Group + Use this endpoint to delete subscription group. -Only groups without members can be deleted - -```go -DeleteSubscriptionGroup( - ctx context.Context, +Only groups without members can be deleted + +```go +DeleteSubscriptionGroup( + ctx context.Context, uid string) ( models.ApiResponse[models.DeleteSubscriptionGroupResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `uid` | `string` | Template, Required | The uid of the subscription group | - -## Response Type - -[`models.DeleteSubscriptionGroupResponse`](../../doc/models/delete-subscription-group-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `uid` | `string` | Template, Required | The uid of the subscription group | + +## Response Type + +[`models.DeleteSubscriptionGroupResponse`](../../doc/models/delete-subscription-group-response.md) + +## Example Usage + +```go ctx := context.Background() uid := "uid0" @@ -453,52 +459,52 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "uid": "grp_99w5xp9y5xycy", - "deleted": true -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Find Subscription Group - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "uid": "grp_99w5xp9y5xycy", + "deleted": true +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Find Subscription Group + Use this endpoint to find subscription group associated with subscription. -If the subscription is not in a group endpoint will return 404 code. - -```go -FindSubscriptionGroup( - ctx context.Context, +If the subscription is not in a group endpoint will return 404 code. + +```go +FindSubscriptionGroup( + ctx context.Context, subscriptionId string) ( models.ApiResponse[models.FullSubscriptionGroupResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `string` | Query, Required | The Chargify id of the subscription associated with the subscription group | - -## Response Type - -[`models.FullSubscriptionGroupResponse`](../../doc/models/full-subscription-group-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `string` | Query, Required | The Chargify id of the subscription associated with the subscription group | + +## Response Type + +[`models.FullSubscriptionGroupResponse`](../../doc/models/full-subscription-group-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := "subscription_id0" @@ -509,59 +515,59 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "uid": "grp_939ktzq8v4477", - "scheme": 1, - "customer_id": 400, - "payment_profile_id": 567, - "subscription_ids": [ - 101, - 102, - 103 - ], - "primary_subscription_id": 101, - "next_assessment_at": "2020-08-01T14:00:00-05:00", - "state": "active", - "cancel_at_end_of_period": false, - "customer": { - "first_name": "Mark", - "last_name": "Wannabewahlberg", - "organization": "The Funky Bunch", - "email": "markymark@example.com", - "reference": "4c92223b-bc16-4d0d-87ff-b177a89a2655" - }, - "account_balances": { - "prepayments": { - "balance_in_cents": 0 - }, - "service_credits": { - "balance_in_cents": 0 - }, - "open_invoices": { - "balance_in_cents": 4400 - }, - "pending_discounts": { - "balance_in_cents": 0 - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Add Subscription to Group - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "uid": "grp_939ktzq8v4477", + "scheme": 1, + "customer_id": 400, + "payment_profile_id": 567, + "subscription_ids": [ + 101, + 102, + 103 + ], + "primary_subscription_id": 101, + "next_assessment_at": "2020-08-01T14:00:00-05:00", + "state": "active", + "cancel_at_end_of_period": false, + "customer": { + "first_name": "Mark", + "last_name": "Wannabewahlberg", + "organization": "The Funky Bunch", + "email": "markymark@example.com", + "reference": "4c92223b-bc16-4d0d-87ff-b177a89a2655" + }, + "account_balances": { + "prepayments": { + "balance_in_cents": 0 + }, + "service_credits": { + "balance_in_cents": 0 + }, + "open_invoices": { + "balance_in_cents": 4400 + }, + "pending_discounts": { + "balance_in_cents": 0 + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Add Subscription to Group + For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to add existing subscriptions to subscription groups. Passing `group` parameters with a `target` containing a `type` and optional `id` is all that's needed. When the `target` parameter specifies a `"customer"` or `"subscription"` that is already part of a hierarchy, the subscription will become a member of the customer's subscription group. If the target customer or subscription is not part of a subscription group, a new group will be created and the subscription will become part of the group with the specified target customer set as the responsible payer for the group's subscriptions. @@ -575,36 +581,54 @@ Rather than specifying a customer, the `target` parameter could instead simply h * `"eldest"` which indicates the subscription will be paid for by the root-level customer in the subscribing customer's hierarchy. To create a new subscription into a subscription group, please reference the following: -[Create Subscription in a Subscription Group](https://developers.chargify.com/docs/api-docs/d571659cf0f24-create-subscription#subscription-in-a-subscription-group) - -```go -AddSubscriptionToGroup( - ctx context.Context, - subscriptionId int, +[Create Subscription in a Subscription Group](https://developers.chargify.com/docs/api-docs/d571659cf0f24-create-subscription#subscription-in-a-subscription-group) + +```go +AddSubscriptionToGroup( + ctx context.Context, + subscriptionId int, body *models.AddSubscriptionToAGroup) ( models.ApiResponse[models.SubscriptionGroupResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.AddSubscriptionToAGroup`](../../doc/models/add-subscription-to-a-group.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionGroupResponse`](../../doc/models/subscription-group-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.AddSubscriptionToAGroup`](../../doc/models/add-subscription-to-a-group.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionGroupResponse`](../../doc/models/subscription-group-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 +bodyGroupGroupSettingsTarget := models.GroupTarget{ + Type: models.GroupTargetType("subscription"), + Id: models.ToPointer(32987), +} + +bodyGroupGroupSettingsBilling := models.GroupBilling{ + Accrue: models.ToPointer(true), + AlignDate: models.ToPointer(true), + Prorate: models.ToPointer(true), +} + +bodyGroupGroupSettings := models.GroupSettings{ + Target: bodyGroupGroupSettingsTarget, + Billing: models.ToPointer(bodyGroupGroupSettingsBilling), +} + +bodyGroup := models.AddSubscriptionToAGroupGroupContainer.FromGroupSettings(bodyGroupGroupSettings) + body := models.AddSubscriptionToAGroup{ - Group: models.ToPointer(interface{}("[target, DotLiquid.Hash][billing, DotLiquid.Hash]")), + Group: models.ToPointer(bodyGroup), } apiResponse, err := subscriptionGroupsController.AddSubscriptionToGroup(ctx, subscriptionId, &body) @@ -614,57 +638,57 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription_group": { - "customer_id": 130690, - "payment_profile": { - "id": 32055, - "first_name": "Marty", - "last_name": "McFly", - "masked_card_number": "XXXX-XXXX-XXXX-1111" - }, - "subscription_ids": [ - 32988, - 33060, - 32986 - ], - "created_at": "2018-08-30T17:14:30-04:00" - } -} -``` - - -# Remove Subscription From Group - -For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to remove existing subscription from subscription group. - -```go -RemoveSubscriptionFromGroup( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription_group": { + "customer_id": 130690, + "payment_profile": { + "id": 32055, + "first_name": "Marty", + "last_name": "McFly", + "masked_card_number": "XXXX-XXXX-XXXX-1111" + }, + "subscription_ids": [ + 32988, + 33060, + 32986 + ], + "created_at": "2018-08-30T17:14:30-04:00" + } +} +``` + + +# Remove Subscription From Group + +For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to remove existing subscription from subscription group. + +```go +RemoveSubscriptionFromGroup( + ctx context.Context, subscriptionId int) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -673,13 +697,13 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/controllers/subscription-invoice-account.md b/doc/controllers/subscription-invoice-account.md index cf64409a..2943f1e9 100644 --- a/doc/controllers/subscription-invoice-account.md +++ b/doc/controllers/subscription-invoice-account.md @@ -1,48 +1,48 @@ -# Subscription Invoice Account - -```go -subscriptionInvoiceAccountController := client.SubscriptionInvoiceAccountController() -``` - -## Class Name - -`SubscriptionInvoiceAccountController` - -## Methods - +# Subscription Invoice Account + +```go +subscriptionInvoiceAccountController := client.SubscriptionInvoiceAccountController() +``` + +## Class Name + +`SubscriptionInvoiceAccountController` + +## Methods + * [Read Account Balances](../../doc/controllers/subscription-invoice-account.md#read-account-balances) * [Create Prepayment](../../doc/controllers/subscription-invoice-account.md#create-prepayment) * [List Prepayments](../../doc/controllers/subscription-invoice-account.md#list-prepayments) * [Issue Service Credit](../../doc/controllers/subscription-invoice-account.md#issue-service-credit) * [Deduct Service Credit](../../doc/controllers/subscription-invoice-account.md#deduct-service-credit) -* [Refund Prepayment](../../doc/controllers/subscription-invoice-account.md#refund-prepayment) - - -# Read Account Balances - -Returns the `balance_in_cents` of the Subscription's Pending Discount, Service Credit, and Prepayment accounts, as well as the sum of the Subscription's open, payable invoices. - -```go -ReadAccountBalances( - ctx context.Context, +* [Refund Prepayment](../../doc/controllers/subscription-invoice-account.md#refund-prepayment) + + +# Read Account Balances + +Returns the `balance_in_cents` of the Subscription's Pending Discount, Service Credit, and Prepayment accounts, as well as the sum of the Subscription's open, payable invoices. + +```go +ReadAccountBalances( + ctx context.Context, subscriptionId int) ( models.ApiResponse[models.AccountBalances], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -[`models.AccountBalances`](../../doc/models/account-balances.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +[`models.AccountBalances`](../../doc/models/account-balances.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -53,43 +53,43 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Create Prepayment - +} +``` + + +# Create Prepayment + ## Create Prepayment In order to specify a prepayment made against a subscription, specify the `amount, memo, details, method`. When the `method` specified is `"credit_card_on_file"`, the prepayment amount will be collected using the default credit card payment profile and applied to the prepayment account balance. This is especially useful for manual replenishment of prepaid subscriptions. -Please note that you **can't** pass `amount_in_cents`. - -```go -CreatePrepayment( - ctx context.Context, - subscriptionId int, +Please note that you **can't** pass `amount_in_cents`. + +```go +CreatePrepayment( + ctx context.Context, + subscriptionId int, body *models.CreatePrepaymentRequest) ( models.ApiResponse[models.CreatePrepaymentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.CreatePrepaymentRequest`](../../doc/models/create-prepayment-request.md) | Body, Optional | - | - -## Response Type - -[`models.CreatePrepaymentResponse`](../../doc/models/create-prepayment-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.CreatePrepaymentRequest`](../../doc/models/create-prepayment-request.md) | Body, Optional | - | + +## Response Type + +[`models.CreatePrepaymentResponse`](../../doc/models/create-prepayment-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -111,131 +111,143 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "prepayment": { - "id": 1, - "subscription_id": 1, - "amount_in_cents": 10000, - "memo": "John Doe - Prepayment", - "created_at": "2020-07-31T05:52:32-04:00", - "starting_balance_in_cents": 0, - "ending_balance_in_cents": -10000 - } -} -``` - - -# List Prepayments - -This request will list a subscription's prepayments. - -```go -ListPrepayments( - ctx context.Context,input ListPrepaymentsInput) ( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "prepayment": { + "id": 1, + "subscription_id": 1, + "amount_in_cents": 10000, + "memo": "John Doe - Prepayment", + "created_at": "2020-07-31T05:52:32-04:00", + "starting_balance_in_cents": 0, + "ending_balance_in_cents": -10000 + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | `ApiError` | + + +# List Prepayments + +This request will list a subscription's prepayments. + +```go +ListPrepayments( + ctx context.Context, + input ListPrepaymentsInput) ( models.ApiResponse[models.PrepaymentsResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `filterDateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. created_at - Time when prepayment was created. application_at - Time when prepayment was applied to invoice. Use in query `filter[date_field]=created_at`. | -| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns prepayments with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `filter[start_date]=2011-12-15`. | -| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns prepayments with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `filter[end_date]=2011-12-15`. | - -## Response Type - -[`models.PrepaymentsResponse`](../../doc/models/prepayments-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `filterDateField` | [`*models.BasicDateField`](../../doc/models/basic-date-field.md) | Query, Optional | The type of filter you would like to apply to your search. created_at - Time when prepayment was created. application_at - Time when prepayment was applied to invoice. Use in query `filter[date_field]=created_at`. | +| `filterStartDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns prepayments with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `filter[start_date]=2011-12-15`. | +| `filterEndDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns prepayments with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `filter[end_date]=2011-12-15`. | + +## Response Type + +[`models.PrepaymentsResponse`](../../doc/models/prepayments-response.md) + +## Example Usage + +```go ctx := context.Background() -subscriptionId := 222 -page := 2 -perPage := 50Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key') +collectedInput := advancedbilling.ListPrepaymentsInput{ + SubscriptionId: 222, + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')Liquid error: Value cannot be null. (Parameter 'key')} -apiResponse, err := subscriptionInvoiceAccountController.ListPrepayments(ctx, subscriptionId, &page, &perPage, Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key'), Liquid error: Value cannot be null. (Parameter 'key')) +apiResponse, err := subscriptionInvoiceAccountController.ListPrepayments(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "prepayments": [ - { - "id": 17, - "subscription_id": 3558750, - "amount_in_cents": 2000, - "remaining_amount_in_cents": 1100, - "refunded_amount_in_cents": 0, - "external": true, - "memo": "test", - "details": "test details", - "payment_type": "cash", - "created_at": "2022-01-18T22:45:41+11:00" - } - ] -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Issue Service Credit - -Credit will be added to the subscription in the amount specified in the request body. The credit is subsequently applied to the next generated invoice. - -```go -IssueServiceCredit( - ctx context.Context, - subscriptionId int, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "prepayments": [ + { + "id": 17, + "subscription_id": 3558750, + "amount_in_cents": 2000, + "remaining_amount_in_cents": 1100, + "refunded_amount_in_cents": 0, + "external": true, + "memo": "test", + "details": "test details", + "payment_type": "cash", + "created_at": "2022-01-18T22:45:41+11:00" + } + ] +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Issue Service Credit + +Credit will be added to the subscription in the amount specified in the request body. The credit is subsequently applied to the next generated invoice. + +```go +IssueServiceCredit( + ctx context.Context, + subscriptionId int, body *models.IssueServiceCreditRequest) ( models.ApiResponse[models.ServiceCredit], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.IssueServiceCreditRequest`](../../doc/models/issue-service-credit-request.md) | Body, Optional | - | - -## Response Type - -[`models.ServiceCredit`](../../doc/models/service-credit.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.IssueServiceCreditRequest`](../../doc/models/issue-service-credit-request.md) | Body, Optional | - | + +## Response Type + +[`models.ServiceCredit`](../../doc/models/service-credit.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 +bodyServiceCreditAmount := models.IssueServiceCreditAmountContainer.FromString("1") + bodyServiceCredit := models.IssueServiceCredit{ - Amount: interface{}("[key1, val1][key2, val2]"), Memo: "Courtesy credit", + Amount: bodyServiceCreditAmount, } body := models.IssueServiceCreditRequest{ @@ -249,55 +261,57 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "id": 101, - "amount_in_cents": 1000, - "ending_balance_in_cents": 2000, - "entry_type": "Credit", - "memo": "Credit to group account" -} -``` - - -# Deduct Service Credit - -Credit will be removed from the subscription in the amount specified in the request body. The credit amount being deducted must be equal to or less than the current credit balance. - -```go -DeductServiceCredit( - ctx context.Context, - subscriptionId int, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "id": 101, + "amount_in_cents": 1000, + "ending_balance_in_cents": 2000, + "entry_type": "Credit", + "memo": "Credit to group account" +} +``` + + +# Deduct Service Credit + +Credit will be removed from the subscription in the amount specified in the request body. The credit amount being deducted must be equal to or less than the current credit balance. + +```go +DeductServiceCredit( + ctx context.Context, + subscriptionId int, body *models.DeductServiceCreditRequest) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.DeductServiceCreditRequest`](../../doc/models/deduct-service-credit-request.md) | Body, Optional | - | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.DeductServiceCreditRequest`](../../doc/models/deduct-service-credit-request.md) | Body, Optional | - | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 +bodyDeductionAmount := models.DeductServiceCreditAmountContainer.FromString("1") + bodyDeduction := models.DeductServiceCredit{ - Amount: interface{}("[key1, val1][key2, val2]"), Memo: "Deduction", + Amount: bodyDeductionAmount, } body := models.DeductServiceCreditRequest{ @@ -309,47 +323,47 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Refund Prepayment - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Refund Prepayment + This endpoint will refund, completely or partially, a particular prepayment applied to a subscription. The `prepayment_id` will be the account transaction ID of the original payment. The prepayment must have some amount remaining in order to be refunded. -The amount may be passed either as a decimal, with `amount`, or an integer in cents, with `amount_in_cents`. - -```go -RefundPrepayment( - ctx context.Context, - subscriptionId int, - prepaymentId string, +The amount may be passed either as a decimal, with `amount`, or an integer in cents, with `amount_in_cents`. + +```go +RefundPrepayment( + ctx context.Context, + subscriptionId int, + prepaymentId string, body *models.RefundPrepaymentRequest) ( models.ApiResponse[models.PrepaymentResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `prepaymentId` | `string` | Template, Required | id of prepayment | -| `body` | [`*models.RefundPrepaymentRequest`](../../doc/models/refund-prepayment-request.md) | Body, Optional | - | - -## Response Type - -[`models.PrepaymentResponse`](../../doc/models/prepayment-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `prepaymentId` | `string` | Template, Required | id of prepayment | +| `body` | [`*models.RefundPrepaymentRequest`](../../doc/models/refund-prepayment-request.md) | Body, Optional | - | + +## Response Type + +[`models.PrepaymentResponse`](../../doc/models/prepayment-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 prepaymentId := "prepayment_id8" @@ -361,14 +375,14 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 400 | Bad Request | [`RefundPrepaymentBaseErrorsResponseException`](../../doc/models/refund-prepayment-base-errors-response-exception.md) | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity | [`RefundPrepaymentAggregatedErrorsResponseException`](../../doc/models/refund-prepayment-aggregated-errors-response-exception.md) | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 400 | Bad Request | [`RefundPrepaymentBaseErrorsResponseException`](../../doc/models/refund-prepayment-base-errors-response-exception.md) | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity | [`RefundPrepaymentAggregatedErrorsResponseException`](../../doc/models/refund-prepayment-aggregated-errors-response-exception.md) | + diff --git a/doc/controllers/subscription-notes.md b/doc/controllers/subscription-notes.md index 8dbd2262..245a5170 100644 --- a/doc/controllers/subscription-notes.md +++ b/doc/controllers/subscription-notes.md @@ -1,24 +1,24 @@ -# Subscription Notes - -```go -subscriptionNotesController := client.SubscriptionNotesController() -``` - -## Class Name - -`SubscriptionNotesController` - -## Methods - +# Subscription Notes + +```go +subscriptionNotesController := client.SubscriptionNotesController() +``` + +## Class Name + +`SubscriptionNotesController` + +## Methods + * [Create Subscription Note](../../doc/controllers/subscription-notes.md#create-subscription-note) * [List Subscription Notes](../../doc/controllers/subscription-notes.md#list-subscription-notes) * [Read Subscription Note](../../doc/controllers/subscription-notes.md#read-subscription-note) * [Update Subscription Note](../../doc/controllers/subscription-notes.md#update-subscription-note) -* [Delete Subscription Note](../../doc/controllers/subscription-notes.md#delete-subscription-note) - - -# Create Subscription Note - +* [Delete Subscription Note](../../doc/controllers/subscription-notes.md#delete-subscription-note) + + +# Create Subscription Note + Use the following method to create a note for a subscription. ## How to Use Subscription Notes @@ -27,31 +27,31 @@ Notes allow you to record information about a particular Subscription in a free If you have structured data such as birth date, color, etc., consider using Metadata instead. -Full documentation on how to use Notes in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404434903181-Subscription-Summary#notes). - -```go -CreateSubscriptionNote( - ctx context.Context, - subscriptionId int, +Full documentation on how to use Notes in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404434903181-Subscription-Summary#notes). + +```go +CreateSubscriptionNote( + ctx context.Context, + subscriptionId int, body *models.UpdateSubscriptionNoteRequest) ( models.ApiResponse[models.SubscriptionNoteResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.UpdateSubscriptionNoteRequest`](../../doc/models/update-subscription-note-request.md) | Body, Optional | Updatable fields for Subscription Note | - -## Response Type - -[`models.SubscriptionNoteResponse`](../../doc/models/subscription-note-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.UpdateSubscriptionNoteRequest`](../../doc/models/update-subscription-note-request.md) | Body, Optional | Updatable fields for Subscription Note | + +## Response Type + +[`models.SubscriptionNoteResponse`](../../doc/models/subscription-note-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -71,106 +71,110 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# List Subscription Notes - -Use this method to retrieve a list of Notes associated with a Subscription. The response will be an array of Notes. - -```go -ListSubscriptionNotes( - ctx context.Context,input ListSubscriptionNotesInput) ( +} +``` + + +# List Subscription Notes + +Use this method to retrieve a list of Notes associated with a Subscription. The response will be an array of Notes. + +```go +ListSubscriptionNotes( + ctx context.Context, + input ListSubscriptionNotesInput) ( models.ApiResponse[[]models.SubscriptionNoteResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | - -## Response Type - -[`[]models.SubscriptionNoteResponse`](../../doc/models/subscription-note-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | + +## Response Type + +[`[]models.SubscriptionNoteResponse`](../../doc/models/subscription-note-response.md) + +## Example Usage + +```go ctx := context.Background() -subscriptionId := 222 -page := 2 -perPage := 50 -apiResponse, err := subscriptionNotesController.ListSubscriptionNotes(ctx, subscriptionId, &page, &perPage) +collectedInput := advancedbilling.ListSubscriptionNotesInput{ + SubscriptionId: 222, + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +} + +apiResponse, err := subscriptionNotesController.ListSubscriptionNotes(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "note": { - "body": "Test note.", - "created_at": "2015-06-15T13:26:47-04:00", - "id": 5, - "sticky": false, - "subscription_id": 100046, - "updated_at": "2015-06-15T13:28:12-04:00" - } - }, - { - "note": { - "body": "Another test note.", - "created_at": "2015-06-15T12:04:46-04:00", - "id": 4, - "sticky": false, - "subscription_id": 100046, - "updated_at": "2015-06-15T13:26:33-04:00" - } - } -] -``` - - -# Read Subscription Note - -Once you have obtained the ID of the note you wish to read, use this method to show a particular note attached to a subscription. - -```go -ReadSubscriptionNote( - ctx context.Context, - subscriptionId int, +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "note": { + "body": "Test note.", + "created_at": "2015-06-15T13:26:47-04:00", + "id": 5, + "sticky": false, + "subscription_id": 100046, + "updated_at": "2015-06-15T13:28:12-04:00" + } + }, + { + "note": { + "body": "Another test note.", + "created_at": "2015-06-15T12:04:46-04:00", + "id": 4, + "sticky": false, + "subscription_id": 100046, + "updated_at": "2015-06-15T13:26:33-04:00" + } + } +] +``` + + +# Read Subscription Note + +Once you have obtained the ID of the note you wish to read, use this method to show a particular note attached to a subscription. + +```go +ReadSubscriptionNote( + ctx context.Context, + subscriptionId int, noteId int) ( models.ApiResponse[models.SubscriptionNoteResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `noteId` | `int` | Template, Required | The Chargify id of the note | - -## Response Type - -[`models.SubscriptionNoteResponse`](../../doc/models/subscription-note-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `noteId` | `int` | Template, Required | The Chargify id of the note | + +## Response Type + +[`models.SubscriptionNoteResponse`](../../doc/models/subscription-note-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 noteId := 66 @@ -182,54 +186,54 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "note": { - "body": "Test note.", - "created_at": "2015-06-15T13:26:47-04:00", - "id": 5, - "sticky": false, - "subscription_id": 100046, - "updated_at": "2015-06-15T13:28:12-04:00" - } -} -``` - - -# Update Subscription Note - -Use the following method to update a note for a Subscription. - -```go -UpdateSubscriptionNote( - ctx context.Context, - subscriptionId int, - noteId int, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "note": { + "body": "Test note.", + "created_at": "2015-06-15T13:26:47-04:00", + "id": 5, + "sticky": false, + "subscription_id": 100046, + "updated_at": "2015-06-15T13:28:12-04:00" + } +} +``` + + +# Update Subscription Note + +Use the following method to update a note for a Subscription. + +```go +UpdateSubscriptionNote( + ctx context.Context, + subscriptionId int, + noteId int, body *models.UpdateSubscriptionNoteRequest) ( models.ApiResponse[models.SubscriptionNoteResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `noteId` | `int` | Template, Required | The Chargify id of the note | -| `body` | [`*models.UpdateSubscriptionNoteRequest`](../../doc/models/update-subscription-note-request.md) | Body, Optional | Updatable fields for Subscription Note | - -## Response Type - -[`models.SubscriptionNoteResponse`](../../doc/models/subscription-note-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `noteId` | `int` | Template, Required | The Chargify id of the note | +| `body` | [`*models.UpdateSubscriptionNoteRequest`](../../doc/models/update-subscription-note-request.md) | Body, Optional | Updatable fields for Subscription Note | + +## Response Type + +[`models.SubscriptionNoteResponse`](../../doc/models/subscription-note-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 noteId := 66 @@ -250,37 +254,37 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Delete Subscription Note - -Use the following method to delete a note for a Subscription. - -```go -DeleteSubscriptionNote( - ctx context.Context, - subscriptionId int, +} +``` + + +# Delete Subscription Note + +Use the following method to delete a note for a Subscription. + +```go +DeleteSubscriptionNote( + ctx context.Context, + subscriptionId int, noteId int) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `noteId` | `int` | Template, Required | The Chargify id of the note | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `noteId` | `int` | Template, Required | The Chargify id of the note | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 noteId := 66 @@ -290,6 +294,6 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - +} +``` + diff --git a/doc/controllers/subscription-products.md b/doc/controllers/subscription-products.md index b81b429c..6567ba9e 100644 --- a/doc/controllers/subscription-products.md +++ b/doc/controllers/subscription-products.md @@ -1,21 +1,21 @@ -# Subscription Products - -```go -subscriptionProductsController := client.SubscriptionProductsController() -``` - -## Class Name - -`SubscriptionProductsController` - -## Methods - +# Subscription Products + +```go +subscriptionProductsController := client.SubscriptionProductsController() +``` + +## Class Name + +`SubscriptionProductsController` + +## Methods + * [Migrate Subscription Product](../../doc/controllers/subscription-products.md#migrate-subscription-product) -* [Preview Subscription Product Migration](../../doc/controllers/subscription-products.md#preview-subscription-product-migration) - - -# Migrate Subscription Product - +* [Preview Subscription Product Migration](../../doc/controllers/subscription-products.md#preview-subscription-product-migration) + + +# Migrate Subscription Product + In order to create a migration, you must pass the `product_id` or `product_handle` in the object when you send a POST request. You may also pass either a `product_price_point_id` or `product_price_point_handle` to choose which price point the subscription is moved to. If no price point identifier is passed the subscription will be moved to the products default price point. The response will be the updated subscription. ## Valid Subscriptions @@ -71,31 +71,31 @@ You may wish to redirect customers to different pages depending on whether their 5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied 6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. 7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known -8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not. - -```go -MigrateSubscriptionProduct( - ctx context.Context, - subscriptionId int, +8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not. + +```go +MigrateSubscriptionProduct( + ctx context.Context, + subscriptionId int, body *models.SubscriptionProductMigrationRequest) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.SubscriptionProductMigrationRequest`](../../doc/models/subscription-product-migration-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.SubscriptionProductMigrationRequest`](../../doc/models/subscription-product-migration-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -116,171 +116,171 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 15054201, - "state": "trialing", - "trial_started_at": "2016-11-03T13:43:36-04:00", - "trial_ended_at": "2016-11-10T12:43:36-05:00", - "activated_at": "2016-11-02T10:20:57-04:00", - "created_at": "2016-11-02T10:20:55-04:00", - "updated_at": "2016-11-03T13:43:36-04:00", - "expires_at": null, - "balance_in_cents": -13989, - "current_period_ends_at": "2016-11-10T12:43:36-05:00", - "next_assessment_at": "2016-11-10T12:43:36-05:00", - "canceled_at": null, - "cancellation_message": null, - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "automatic", - "snap_day": null, - "cancellation_method": null, - "current_period_started_at": "2016-11-03T13:43:35-04:00", - "previous_state": "active", - "signup_payment_id": 160680121, - "signup_revenue": "0.00", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": 14000, - "product_price_in_cents": 1000, - "product_version_number": 6, - "payment_type": "credit_card", - "referral_code": "ghnhvy", - "coupon_use_count": null, - "coupon_uses_allowed": null, - "customer": { - "id": 14543792, - "first_name": "Frankie", - "last_name": "Test", - "organization": null, - "email": "testfrankie111@test.com", - "created_at": "2016-11-02T10:20:55-04:00", - "updated_at": "2016-11-02T10:20:58-04:00", - "reference": null, - "address": null, - "address_2": null, - "city": null, - "state": null, - "zip": null, - "country": null, - "phone": "5555551212", - "portal_invite_last_sent_at": "2016-11-02T10:20:58-04:00", - "portal_invite_last_accepted_at": null, - "verified": false, - "portal_customer_created_at": "2016-11-02T10:20:58-04:00", - "cc_emails": null - }, - "product": { - "id": 3861800, - "name": "Trial Product", - "handle": "trial-product", - "description": "Trial period with payment expected at end of trial.", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2016-07-08T09:53:55-04:00", - "updated_at": "2016-09-05T13:00:36-04:00", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": 0, - "trial_interval": 7, - "trial_interval_unit": "day", - "archived_at": null, - "require_credit_card": true, - "return_params": "", - "taxable": false, - "update_return_url": "", - "initial_charge_after_trial": false, - "version_number": 6, - "update_return_params": "", - "product_family": { - "id": 527890, - "name": "Acme Projects", - "description": "", - "handle": "billing-plans", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 294791, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/xv52yrcc3byx/trial-product" - } - ] - }, - "credit_card": { - "id": 10088716, - "first_name": "F", - "last_name": "NB", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2017, - "customer_id": 14543792, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "123 Montana Way", - "billing_city": "Billings", - "billing_state": "MT", - "billing_zip": "59101", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": "Apt. 10", - "payment_type": "credit_card" - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Preview Subscription Product Migration - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 15054201, + "state": "trialing", + "trial_started_at": "2016-11-03T13:43:36-04:00", + "trial_ended_at": "2016-11-10T12:43:36-05:00", + "activated_at": "2016-11-02T10:20:57-04:00", + "created_at": "2016-11-02T10:20:55-04:00", + "updated_at": "2016-11-03T13:43:36-04:00", + "expires_at": null, + "balance_in_cents": -13989, + "current_period_ends_at": "2016-11-10T12:43:36-05:00", + "next_assessment_at": "2016-11-10T12:43:36-05:00", + "canceled_at": null, + "cancellation_message": null, + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "automatic", + "snap_day": null, + "cancellation_method": null, + "current_period_started_at": "2016-11-03T13:43:35-04:00", + "previous_state": "active", + "signup_payment_id": 160680121, + "signup_revenue": "0.00", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": 14000, + "product_price_in_cents": 1000, + "product_version_number": 6, + "payment_type": "credit_card", + "referral_code": "ghnhvy", + "coupon_use_count": null, + "coupon_uses_allowed": null, + "customer": { + "id": 14543792, + "first_name": "Frankie", + "last_name": "Test", + "organization": null, + "email": "testfrankie111@test.com", + "created_at": "2016-11-02T10:20:55-04:00", + "updated_at": "2016-11-02T10:20:58-04:00", + "reference": null, + "address": null, + "address_2": null, + "city": null, + "state": null, + "zip": null, + "country": null, + "phone": "5555551212", + "portal_invite_last_sent_at": "2016-11-02T10:20:58-04:00", + "portal_invite_last_accepted_at": null, + "verified": false, + "portal_customer_created_at": "2016-11-02T10:20:58-04:00", + "cc_emails": null + }, + "product": { + "id": 3861800, + "name": "Trial Product", + "handle": "trial-product", + "description": "Trial period with payment expected at end of trial.", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2016-07-08T09:53:55-04:00", + "updated_at": "2016-09-05T13:00:36-04:00", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": 0, + "trial_interval": 7, + "trial_interval_unit": "day", + "archived_at": null, + "require_credit_card": true, + "return_params": "", + "taxable": false, + "update_return_url": "", + "initial_charge_after_trial": false, + "version_number": 6, + "update_return_params": "", + "product_family": { + "id": 527890, + "name": "Acme Projects", + "description": "", + "handle": "billing-plans", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 294791, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/xv52yrcc3byx/trial-product" + } + ] + }, + "credit_card": { + "id": 10088716, + "first_name": "F", + "last_name": "NB", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2017, + "customer_id": 14543792, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": "123 Montana Way", + "billing_city": "Billings", + "billing_state": "MT", + "billing_zip": "59101", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": "Apt. 10", + "payment_type": "credit_card" + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Preview Subscription Product Migration + ## Previewing a future date It is also possible to preview the migration for a date in the future, as long as it's still within the subscription's current billing period, by passing a `proration_date` along with the request (eg: `"proration_date": "2020-12-18T18:25:43.511Z"`). -This will calculate the prorated adjustment, charge, payment and credit applied values assuming the migration is done at that date in the future as opposed to right now. - -```go -PreviewSubscriptionProductMigration( - ctx context.Context, - subscriptionId int, +This will calculate the prorated adjustment, charge, payment and credit applied values assuming the migration is done at that date in the future as opposed to right now. + +```go +PreviewSubscriptionProductMigration( + ctx context.Context, + subscriptionId int, body *models.SubscriptionMigrationPreviewRequest) ( models.ApiResponse[models.SubscriptionMigrationPreviewResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.SubscriptionMigrationPreviewRequest`](../../doc/models/subscription-migration-preview-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionMigrationPreviewResponse`](../../doc/models/subscription-migration-preview-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.SubscriptionMigrationPreviewRequest`](../../doc/models/subscription-migration-preview-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionMigrationPreviewResponse`](../../doc/models/subscription-migration-preview-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -299,25 +299,25 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "migration": { - "prorated_adjustment_in_cents": 0, - "charge_in_cents": 5000, - "payment_due_in_cents": 0, - "credit_applied_in_cents": 0 - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "migration": { + "prorated_adjustment_in_cents": 0, + "charge_in_cents": 5000, + "payment_due_in_cents": 0, + "credit_applied_in_cents": 0 + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/controllers/subscription-status.md b/doc/controllers/subscription-status.md index 7b74e620..504f34b9 100644 --- a/doc/controllers/subscription-status.md +++ b/doc/controllers/subscription-status.md @@ -1,15 +1,15 @@ -# Subscription Status - -```go -subscriptionStatusController := client.SubscriptionStatusController() -``` - -## Class Name - -`SubscriptionStatusController` - -## Methods - +# Subscription Status + +```go +subscriptionStatusController := client.SubscriptionStatusController() +``` + +## Class Name + +`SubscriptionStatusController` + +## Methods + * [Retry Subscription](../../doc/controllers/subscription-status.md#retry-subscription) * [Cancel Subscription](../../doc/controllers/subscription-status.md#cancel-subscription) * [Resume Subscription](../../doc/controllers/subscription-status.md#resume-subscription) @@ -19,11 +19,11 @@ subscriptionStatusController := client.SubscriptionStatusController() * [Initiate Delayed Cancellation](../../doc/controllers/subscription-status.md#initiate-delayed-cancellation) * [Cancel Delayed Cancellation](../../doc/controllers/subscription-status.md#cancel-delayed-cancellation) * [Cancel Dunning](../../doc/controllers/subscription-status.md#cancel-dunning) -* [Preview Renewal](../../doc/controllers/subscription-status.md#preview-renewal) - - -# Retry Subscription - +* [Preview Renewal](../../doc/controllers/subscription-status.md#preview-renewal) + + +# Retry Subscription + Chargify offers the ability to retry collecting the balance due on a past due Subscription without waiting for the next scheduled attempt. ## Successful Reactivation @@ -32,29 +32,29 @@ The response will be `200 OK` with the updated Subscription. ## Failed Reactivation -The response will be `422 "Unprocessable Entity`. - -```go -RetrySubscription( - ctx context.Context, +The response will be `422 "Unprocessable Entity`. + +```go +RetrySubscription( + ctx context.Context, subscriptionId int) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -65,180 +65,180 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 46330, - "state": "active", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2018-10-22T13:10:46-06:00", - "created_at": "2018-10-22T13:10:46-06:00", - "updated_at": "2021-06-10T09:23:43-06:00", - "expires_at": null, - "balance_in_cents": 18600, - "current_period_ends_at": "2021-06-22T13:10:46-06:00", - "next_assessment_at": "2021-06-22T13:10:46-06:00", - "canceled_at": null, - "cancellation_message": null, - "next_product_id": null, - "cancel_at_end_of_period": null, - "payment_collection_method": "automatic", - "snap_day": null, - "cancellation_method": null, - "product_price_point_id": 3464, - "next_product_price_point_id": null, - "receives_invoice_emails": null, - "net_terms": null, - "locale": null, - "currency": "USD", - "reference": null, - "scheduled_cancellation_at": null, - "current_period_started_at": "2021-05-22T13:10:46-06:00", - "previous_state": "past_due", - "signup_payment_id": 651268, - "signup_revenue": "6.00", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": 600, - "product_price_in_cents": 600, - "product_version_number": 501, - "payment_type": null, - "referral_code": "rzqvrx", - "coupon_use_count": null, - "coupon_uses_allowed": null, - "reason_code": null, - "automatically_resume_at": null, - "coupon_codes": [], - "offer_id": null, - "credit_balance_in_cents": 0, - "prepayment_balance_in_cents": 0, - "payer_id": 142365, - "stored_credential_transaction_id": null, - "next_product_handle": null, - "on_hold_at": null, - "prepaid_dunning": false, - "customer": { - "id": 142365, - "first_name": "Lavern", - "last_name": "Fahey", - "organization": null, - "email": "millie2@example.com", - "created_at": "2018-10-22T13:10:46-06:00", - "updated_at": "2018-10-22T13:10:46-06:00", - "reference": null, - "address": null, - "address_2": null, - "city": null, - "state": null, - "zip": null, - "country": null, - "phone": null, - "portal_invite_last_sent_at": null, - "portal_invite_last_accepted_at": null, - "verified": false, - "portal_customer_created_at": "2018-10-22T13:10:46-06:00", - "vat_number": null, - "cc_emails": "john@example.com, sue@example.com", - "tax_exempt": false, - "parent_id": null, - "locale": null - }, - "product": { - "id": 8080, - "name": "Pro Versions", - "handle": null, - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "month", - "created_at": "2019-02-15T10:15:00-07:00", - "updated_at": "2019-02-15T10:30:34-07:00", - "price_in_cents": 600, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": true, - "return_params": "", - "require_shipping_address": false, - "request_billing_address": false, - "require_billing_address": false, - "taxable": false, - "update_return_url": "", - "tax_code": "", - "initial_charge_after_trial": false, - "default_product_price_point_id": 3464, - "version_number": 501, - "update_return_params": "", - "product_price_point_id": 3464, - "product_price_point_name": "Default", - "product_price_point_handle": "uuid:5305c3f0-1375-0137-5619-065dfbfdc636", - "product_family": { - "id": 37, - "name": "Acme Projects", - "description": null, - "handle": "acme-projects", - "accounting_code": null, - "created_at": "2013-02-20T15:05:51-07:00", - "updated_at": "2013-02-20T15:05:51-07:00" - }, - "public_signup_pages": [ - { - "id": 1540, - "return_url": null, - "return_params": "", - "url": "https://acme-test.staging-chargifypay.com/subscribe/2f6y53rrqgsf" - } - ] - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Cancel Subscription - -The DELETE action causes the cancellation of the Subscription. This means, the method sets the Subscription state to "canceled". - -```go -CancelSubscription( - ctx context.Context, - subscriptionId int, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 46330, + "state": "active", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2018-10-22T13:10:46-06:00", + "created_at": "2018-10-22T13:10:46-06:00", + "updated_at": "2021-06-10T09:23:43-06:00", + "expires_at": null, + "balance_in_cents": 18600, + "current_period_ends_at": "2021-06-22T13:10:46-06:00", + "next_assessment_at": "2021-06-22T13:10:46-06:00", + "canceled_at": null, + "cancellation_message": null, + "next_product_id": null, + "cancel_at_end_of_period": null, + "payment_collection_method": "automatic", + "snap_day": null, + "cancellation_method": null, + "product_price_point_id": 3464, + "next_product_price_point_id": null, + "receives_invoice_emails": null, + "net_terms": null, + "locale": null, + "currency": "USD", + "reference": null, + "scheduled_cancellation_at": null, + "current_period_started_at": "2021-05-22T13:10:46-06:00", + "previous_state": "past_due", + "signup_payment_id": 651268, + "signup_revenue": "6.00", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": 600, + "product_price_in_cents": 600, + "product_version_number": 501, + "payment_type": null, + "referral_code": "rzqvrx", + "coupon_use_count": null, + "coupon_uses_allowed": null, + "reason_code": null, + "automatically_resume_at": null, + "coupon_codes": [], + "offer_id": null, + "credit_balance_in_cents": 0, + "prepayment_balance_in_cents": 0, + "payer_id": 142365, + "stored_credential_transaction_id": null, + "next_product_handle": null, + "on_hold_at": null, + "prepaid_dunning": false, + "customer": { + "id": 142365, + "first_name": "Lavern", + "last_name": "Fahey", + "organization": null, + "email": "millie2@example.com", + "created_at": "2018-10-22T13:10:46-06:00", + "updated_at": "2018-10-22T13:10:46-06:00", + "reference": null, + "address": null, + "address_2": null, + "city": null, + "state": null, + "zip": null, + "country": null, + "phone": null, + "portal_invite_last_sent_at": null, + "portal_invite_last_accepted_at": null, + "verified": false, + "portal_customer_created_at": "2018-10-22T13:10:46-06:00", + "vat_number": null, + "cc_emails": "john@example.com, sue@example.com", + "tax_exempt": false, + "parent_id": null, + "locale": null + }, + "product": { + "id": 8080, + "name": "Pro Versions", + "handle": null, + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "month", + "created_at": "2019-02-15T10:15:00-07:00", + "updated_at": "2019-02-15T10:30:34-07:00", + "price_in_cents": 600, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": true, + "return_params": "", + "require_shipping_address": false, + "request_billing_address": false, + "require_billing_address": false, + "taxable": false, + "update_return_url": "", + "tax_code": "", + "initial_charge_after_trial": false, + "default_product_price_point_id": 3464, + "version_number": 501, + "update_return_params": "", + "product_price_point_id": 3464, + "product_price_point_name": "Default", + "product_price_point_handle": "uuid:5305c3f0-1375-0137-5619-065dfbfdc636", + "product_family": { + "id": 37, + "name": "Acme Projects", + "description": null, + "handle": "acme-projects", + "accounting_code": null, + "created_at": "2013-02-20T15:05:51-07:00", + "updated_at": "2013-02-20T15:05:51-07:00" + }, + "public_signup_pages": [ + { + "id": 1540, + "return_url": null, + "return_params": "", + "url": "https://acme-test.staging-chargifypay.com/subscribe/2f6y53rrqgsf" + } + ] + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Cancel Subscription + +The DELETE action causes the cancellation of the Subscription. This means, the method sets the Subscription state to "canceled". + +```go +CancelSubscription( + ctx context.Context, + subscriptionId int, body *models.CancellationRequest) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.CancellationRequest`](../../doc/models/cancellation-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.CancellationRequest`](../../doc/models/cancellation-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -249,180 +249,180 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 15254809, - "state": "canceled", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2016-11-15T15:33:44-05:00", - "created_at": "2016-11-15T15:33:44-05:00", - "updated_at": "2016-11-15T17:13:06-05:00", - "expires_at": null, - "balance_in_cents": 0, - "current_period_ends_at": "2017-08-29T12:00:00-04:00", - "next_assessment_at": "2017-08-29T12:00:00-04:00", - "canceled_at": "2016-11-15T17:13:06-05:00", - "cancellation_message": "Canceling the subscription via the API", - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "automatic", - "snap_day": null, - "cancellation_method": "merchant_api", - "current_period_started_at": "2016-11-15T15:33:44-05:00", - "previous_state": "active", - "signup_payment_id": 0, - "signup_revenue": "0.00", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": 0, - "product_price_in_cents": 1000, - "product_version_number": 7, - "payment_type": "credit_card", - "referral_code": "tg8qbq", - "coupon_use_count": null, - "coupon_uses_allowed": null, - "customer": { - "id": 14731081, - "first_name": "John", - "last_name": "Doe", - "organization": "Acme Widgets", - "email": "john.doe@example.com", - "created_at": "2016-11-15T15:33:44-05:00", - "updated_at": "2016-11-15T15:33:45-05:00", - "reference": "123", - "address": null, - "address_2": null, - "city": null, - "state": null, - "zip": null, - "country": null, - "phone": null, - "portal_invite_last_sent_at": "2016-11-15T15:33:45-05:00", - "portal_invite_last_accepted_at": null, - "verified": false, - "portal_customer_created_at": "2016-11-15T15:33:45-05:00", - "cc_emails": null - }, - "product": { - "id": 3792003, - "name": "$10 Basic Plan", - "handle": "basic", - "description": "lorem ipsum", - "accounting_code": "basic", - "request_credit_card": false, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2016-03-24T13:38:39-04:00", - "updated_at": "2016-11-03T13:03:05-04:00", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "day", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": false, - "return_params": "", - "taxable": false, - "update_return_url": "", - "initial_charge_after_trial": false, - "version_number": 7, - "update_return_params": "", - "product_family": { - "id": 527890, - "name": "Acme Projects", - "description": "", - "handle": "billing-plans", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 281054, - "return_url": "http://www.example.com?successfulsignup", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/kqvmfrbgd89q/basic" - }, - { - "id": 281240, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/dkffht5dxfd8/basic" - }, - { - "id": 282694, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/jwffwgdd95s8/basic" - } - ] - }, - "credit_card": { - "id": 10202898, - "first_name": "John", - "last_name": "Doe", - "masked_card_number": "XXXX-XXXX-XXXX-1111", - "card_type": "visa", - "expiration_month": 12, - "expiration_year": 2020, - "customer_id": 14731081, - "current_vault": "authorizenet", - "vault_token": "12345", - "billing_address": null, - "billing_city": null, - "billing_state": null, - "billing_zip": null, - "billing_country": null, - "customer_vault_token": "67890", - "billing_address_2": null, - "payment_type": "credit_card" - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | `ApiError` | - - -# Resume Subscription - -Resume a paused (on-hold) subscription. If the normal next renewal date has not passed, the subscription will return to active and will renew on that date. Otherwise, it will behave like a reactivation, setting the billing date to 'now' and charging the subscriber. - -```go -ResumeSubscription( - ctx context.Context, - subscriptionId int, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 15254809, + "state": "canceled", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2016-11-15T15:33:44-05:00", + "created_at": "2016-11-15T15:33:44-05:00", + "updated_at": "2016-11-15T17:13:06-05:00", + "expires_at": null, + "balance_in_cents": 0, + "current_period_ends_at": "2017-08-29T12:00:00-04:00", + "next_assessment_at": "2017-08-29T12:00:00-04:00", + "canceled_at": "2016-11-15T17:13:06-05:00", + "cancellation_message": "Canceling the subscription via the API", + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "automatic", + "snap_day": null, + "cancellation_method": "merchant_api", + "current_period_started_at": "2016-11-15T15:33:44-05:00", + "previous_state": "active", + "signup_payment_id": 0, + "signup_revenue": "0.00", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": 0, + "product_price_in_cents": 1000, + "product_version_number": 7, + "payment_type": "credit_card", + "referral_code": "tg8qbq", + "coupon_use_count": null, + "coupon_uses_allowed": null, + "customer": { + "id": 14731081, + "first_name": "John", + "last_name": "Doe", + "organization": "Acme Widgets", + "email": "john.doe@example.com", + "created_at": "2016-11-15T15:33:44-05:00", + "updated_at": "2016-11-15T15:33:45-05:00", + "reference": "123", + "address": null, + "address_2": null, + "city": null, + "state": null, + "zip": null, + "country": null, + "phone": null, + "portal_invite_last_sent_at": "2016-11-15T15:33:45-05:00", + "portal_invite_last_accepted_at": null, + "verified": false, + "portal_customer_created_at": "2016-11-15T15:33:45-05:00", + "cc_emails": null + }, + "product": { + "id": 3792003, + "name": "$10 Basic Plan", + "handle": "basic", + "description": "lorem ipsum", + "accounting_code": "basic", + "request_credit_card": false, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2016-03-24T13:38:39-04:00", + "updated_at": "2016-11-03T13:03:05-04:00", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "day", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": false, + "return_params": "", + "taxable": false, + "update_return_url": "", + "initial_charge_after_trial": false, + "version_number": 7, + "update_return_params": "", + "product_family": { + "id": 527890, + "name": "Acme Projects", + "description": "", + "handle": "billing-plans", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 281054, + "return_url": "http://www.example.com?successfulsignup", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/kqvmfrbgd89q/basic" + }, + { + "id": 281240, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/dkffht5dxfd8/basic" + }, + { + "id": 282694, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/jwffwgdd95s8/basic" + } + ] + }, + "credit_card": { + "id": 10202898, + "first_name": "John", + "last_name": "Doe", + "masked_card_number": "XXXX-XXXX-XXXX-1111", + "card_type": "visa", + "expiration_month": 12, + "expiration_year": 2020, + "customer_id": 14731081, + "current_vault": "authorizenet", + "vault_token": "12345", + "billing_address": null, + "billing_city": null, + "billing_state": null, + "billing_zip": null, + "billing_country": null, + "customer_vault_token": "67890", + "billing_address_2": null, + "payment_type": "credit_card" + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | `ApiError` | + + +# Resume Subscription + +Resume a paused (on-hold) subscription. If the normal next renewal date has not passed, the subscription will return to active and will renew on that date. Otherwise, it will behave like a reactivation, setting the billing date to 'now' and charging the subscriber. + +```go +ResumeSubscription( + ctx context.Context, + subscriptionId int, calendarBillingResumptionCharge *models.ResumptionCharge) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `calendarBillingResumptionCharge` | [`*models.ResumptionCharge`](../../doc/models/resumption-charge.md) | Query, Optional | (For calendar billing subscriptions only) The way that the resumed subscription's charge should be handled | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `calendarBillingResumptionCharge` | [`*models.ResumptionCharge`](../../doc/models/resumption-charge.md) | Query, Optional | (For calendar billing subscriptions only) The way that the resumed subscription's charge should be handled | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222Liquid error: Value cannot be null. (Parameter 'key') @@ -433,156 +433,156 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 18220670, - "state": "active", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2017-06-27T13:45:15-05:00", - "created_at": "2017-06-27T13:45:13-05:00", - "updated_at": "2017-06-30T09:26:50-05:00", - "expires_at": null, - "balance_in_cents": 10000, - "current_period_ends_at": "2017-06-30T12:00:00-05:00", - "next_assessment_at": "2017-06-30T12:00:00-05:00", - "canceled_at": null, - "cancellation_message": null, - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "automatic", - "snap_day": "end", - "cancellation_method": null, - "current_period_started_at": "2017-06-27T13:45:13-05:00", - "previous_state": "active", - "signup_payment_id": 191819284, - "signup_revenue": "0.00", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": 0, - "product_price_in_cents": 0, - "product_version_number": 1, - "payment_type": null, - "referral_code": "d3pw7f", - "coupon_use_count": null, - "coupon_uses_allowed": null, - "reason_code": null, - "automatically_resume_at": null, - "current_billing_amount_in_cents": 10000, - "customer": { - "id": 17780587, - "first_name": "Catie", - "last_name": "Test", - "organization": "Acme, Inc.", - "email": "catie@example.com", - "created_at": "2017-06-27T13:01:05-05:00", - "updated_at": "2017-06-30T09:23:10-05:00", - "reference": "123ABC", - "address": "123 Anywhere Street", - "address_2": "Apartment #10", - "city": "Los Angeles", - "state": "CA", - "zip": "90210", - "country": "US", - "phone": "555-555-5555", - "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", - "portal_invite_last_accepted_at": null, - "verified": true, - "portal_customer_created_at": "2017-06-27T13:01:08-05:00", - "cc_emails": "support@example.com", - "tax_exempt": true - }, - "product": { - "id": 4470347, - "name": "Zero Dollar Product", - "handle": "zero-dollar-product", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2017-03-23T10:54:12-05:00", - "updated_at": "2017-04-20T15:18:46-05:00", - "price_in_cents": 0, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": false, - "return_params": "", - "taxable": false, - "update_return_url": "", - "tax_code": "", - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": "", - "product_family": { - "id": 997233, - "name": "Acme Products", - "description": "", - "handle": "acme-products", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 316810, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" - } - ] - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Pause Subscription - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 18220670, + "state": "active", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2017-06-27T13:45:15-05:00", + "created_at": "2017-06-27T13:45:13-05:00", + "updated_at": "2017-06-30T09:26:50-05:00", + "expires_at": null, + "balance_in_cents": 10000, + "current_period_ends_at": "2017-06-30T12:00:00-05:00", + "next_assessment_at": "2017-06-30T12:00:00-05:00", + "canceled_at": null, + "cancellation_message": null, + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "automatic", + "snap_day": "end", + "cancellation_method": null, + "current_period_started_at": "2017-06-27T13:45:13-05:00", + "previous_state": "active", + "signup_payment_id": 191819284, + "signup_revenue": "0.00", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": 0, + "product_price_in_cents": 0, + "product_version_number": 1, + "payment_type": null, + "referral_code": "d3pw7f", + "coupon_use_count": null, + "coupon_uses_allowed": null, + "reason_code": null, + "automatically_resume_at": null, + "current_billing_amount_in_cents": 10000, + "customer": { + "id": 17780587, + "first_name": "Catie", + "last_name": "Test", + "organization": "Acme, Inc.", + "email": "catie@example.com", + "created_at": "2017-06-27T13:01:05-05:00", + "updated_at": "2017-06-30T09:23:10-05:00", + "reference": "123ABC", + "address": "123 Anywhere Street", + "address_2": "Apartment #10", + "city": "Los Angeles", + "state": "CA", + "zip": "90210", + "country": "US", + "phone": "555-555-5555", + "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", + "portal_invite_last_accepted_at": null, + "verified": true, + "portal_customer_created_at": "2017-06-27T13:01:08-05:00", + "cc_emails": "support@example.com", + "tax_exempt": true + }, + "product": { + "id": 4470347, + "name": "Zero Dollar Product", + "handle": "zero-dollar-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2017-03-23T10:54:12-05:00", + "updated_at": "2017-04-20T15:18:46-05:00", + "price_in_cents": 0, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": false, + "return_params": "", + "taxable": false, + "update_return_url": "", + "tax_code": "", + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": "", + "product_family": { + "id": 997233, + "name": "Acme Products", + "description": "", + "handle": "acme-products", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 316810, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" + } + ] + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Pause Subscription + This will place the subscription in the on_hold state and it will not renew. ## Limitations -You may not place a subscription on hold if the `next_billing` date is within 24 hours. - -```go -PauseSubscription( - ctx context.Context, - subscriptionId int, +You may not place a subscription on hold if the `next_billing` date is within 24 hours. + +```go +PauseSubscription( + ctx context.Context, + subscriptionId int, body *models.PauseRequest) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.PauseRequest`](../../doc/models/pause-request.md) | Body, Optional | Allows to pause a Subscription | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.PauseRequest`](../../doc/models/pause-request.md) | Body, Optional | Allows to pause a Subscription | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -605,158 +605,158 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 18220670, - "state": "on_hold", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2017-06-27T13:45:15-05:00", - "created_at": "2017-06-27T13:45:13-05:00", - "updated_at": "2017-06-30T09:26:50-05:00", - "expires_at": null, - "balance_in_cents": 10000, - "current_period_ends_at": "2017-06-30T12:00:00-05:00", - "next_assessment_at": "2017-06-30T12:00:00-05:00", - "canceled_at": null, - "cancellation_message": null, - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "automatic", - "snap_day": "end", - "cancellation_method": null, - "current_period_started_at": "2017-06-27T13:45:13-05:00", - "previous_state": "active", - "signup_payment_id": 191819284, - "signup_revenue": "0.00", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": 0, - "product_price_in_cents": 0, - "product_version_number": 1, - "payment_type": null, - "referral_code": "d3pw7f", - "coupon_use_count": null, - "coupon_uses_allowed": null, - "reason_code": null, - "automatically_resume_at": null, - "current_billing_amount_in_cents": 10000, - "customer": { - "id": 17780587, - "first_name": "Catie", - "last_name": "Test", - "organization": "Acme, Inc.", - "email": "catie@example.com", - "created_at": "2017-06-27T13:01:05-05:00", - "updated_at": "2017-06-30T09:23:10-05:00", - "reference": "123ABC", - "address": "123 Anywhere Street", - "address_2": "Apartment #10", - "city": "Los Angeles", - "state": "CA", - "zip": "90210", - "country": "US", - "phone": "555-555-5555", - "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", - "portal_invite_last_accepted_at": null, - "verified": true, - "portal_customer_created_at": "2017-06-27T13:01:08-05:00", - "cc_emails": "support@example.com", - "tax_exempt": true - }, - "product": { - "id": 4470347, - "name": "Zero Dollar Product", - "handle": "zero-dollar-product", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2017-03-23T10:54:12-05:00", - "updated_at": "2017-04-20T15:18:46-05:00", - "price_in_cents": 0, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": false, - "return_params": "", - "taxable": false, - "update_return_url": "", - "tax_code": "", - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": "", - "product_family": { - "id": 997233, - "name": "Acme Products", - "description": "", - "handle": "acme-products", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 316810, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" - } - ] - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Update Automatic Subscription Resumption - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 18220670, + "state": "on_hold", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2017-06-27T13:45:15-05:00", + "created_at": "2017-06-27T13:45:13-05:00", + "updated_at": "2017-06-30T09:26:50-05:00", + "expires_at": null, + "balance_in_cents": 10000, + "current_period_ends_at": "2017-06-30T12:00:00-05:00", + "next_assessment_at": "2017-06-30T12:00:00-05:00", + "canceled_at": null, + "cancellation_message": null, + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "automatic", + "snap_day": "end", + "cancellation_method": null, + "current_period_started_at": "2017-06-27T13:45:13-05:00", + "previous_state": "active", + "signup_payment_id": 191819284, + "signup_revenue": "0.00", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": 0, + "product_price_in_cents": 0, + "product_version_number": 1, + "payment_type": null, + "referral_code": "d3pw7f", + "coupon_use_count": null, + "coupon_uses_allowed": null, + "reason_code": null, + "automatically_resume_at": null, + "current_billing_amount_in_cents": 10000, + "customer": { + "id": 17780587, + "first_name": "Catie", + "last_name": "Test", + "organization": "Acme, Inc.", + "email": "catie@example.com", + "created_at": "2017-06-27T13:01:05-05:00", + "updated_at": "2017-06-30T09:23:10-05:00", + "reference": "123ABC", + "address": "123 Anywhere Street", + "address_2": "Apartment #10", + "city": "Los Angeles", + "state": "CA", + "zip": "90210", + "country": "US", + "phone": "555-555-5555", + "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", + "portal_invite_last_accepted_at": null, + "verified": true, + "portal_customer_created_at": "2017-06-27T13:01:08-05:00", + "cc_emails": "support@example.com", + "tax_exempt": true + }, + "product": { + "id": 4470347, + "name": "Zero Dollar Product", + "handle": "zero-dollar-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2017-03-23T10:54:12-05:00", + "updated_at": "2017-04-20T15:18:46-05:00", + "price_in_cents": 0, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": false, + "return_params": "", + "taxable": false, + "update_return_url": "", + "tax_code": "", + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": "", + "product_family": { + "id": 997233, + "name": "Acme Products", + "description": "", + "handle": "acme-products", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 316810, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" + } + ] + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Update Automatic Subscription Resumption + Once a subscription has been paused / put on hold, you can update the date which was specified to automatically resume the subscription. To update a subscription's resume date, use this method to change or update the `automatically_resume_at` date. ### Remove the resume date -Alternately, you can change the `automatically_resume_at` to `null` if you would like the subscription to not have a resume date. - -```go -UpdateAutomaticSubscriptionResumption( - ctx context.Context, - subscriptionId int, +Alternately, you can change the `automatically_resume_at` to `null` if you would like the subscription to not have a resume date. + +```go +UpdateAutomaticSubscriptionResumption( + ctx context.Context, + subscriptionId int, body *models.PauseRequest) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.PauseRequest`](../../doc/models/pause-request.md) | Body, Optional | Allows to pause a Subscription | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.PauseRequest`](../../doc/models/pause-request.md) | Body, Optional | Allows to pause a Subscription | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -779,140 +779,140 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 20359140, - "state": "on_hold", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2018-01-05T17:15:50-06:00", - "created_at": "2018-01-05T17:15:49-06:00", - "updated_at": "2018-01-09T10:26:14-06:00", - "expires_at": null, - "balance_in_cents": 0, - "current_period_ends_at": "2023-01-05T17:15:00-06:00", - "next_assessment_at": "2023-01-05T17:15:00-06:00", - "canceled_at": null, - "cancellation_message": null, - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "automatic", - "snap_day": null, - "cancellation_method": null, - "current_period_started_at": "2018-01-05T17:15:49-06:00", - "previous_state": "active", - "signup_payment_id": 219829722, - "signup_revenue": "100.00", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": 10009991, - "product_price_in_cents": 10000, - "product_version_number": 1, - "payment_type": "credit_card", - "referral_code": "8y7jqr", - "coupon_use_count": null, - "coupon_uses_allowed": null, - "reason_code": null, - "automatically_resume_at": "2019-01-20T00:00:00-06:00", - "coupon_codes": [], - "customer": { - "id": 19948683, - "first_name": "Vanessa", - "last_name": "Test", - "organization": "", - "email": "vanessa@example.com", - "created_at": "2018-01-05T17:15:49-06:00", - "updated_at": "2018-01-05T17:15:51-06:00", - "reference": null, - "address": "123 Anywhere Ln", - "address_2": "", - "city": "Boston", - "state": "MA", - "zip": "02120", - "country": "US", - "phone": "555-555-1212", - "portal_invite_last_sent_at": "2018-01-05T17:15:51-06:00", - "portal_invite_last_accepted_at": null, - "verified": null, - "portal_customer_created_at": "2018-01-05T17:15:51-06:00", - "cc_emails": null, - "tax_exempt": false - }, - "product": { - "id": 4535643, - "name": "Annual Product", - "handle": "annual-product", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2017-08-25T10:25:31-05:00", - "updated_at": "2017-08-25T10:25:31-05:00", - "price_in_cents": 10000, - "interval": 12, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": true, - "return_params": "", - "taxable": false, - "update_return_url": "", - "tax_code": "", - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": "", - "product_family": { - "id": 1025627, - "name": "Acme Products", - "description": "", - "handle": "acme-products", - "accounting_code": null - }, - "public_signup_pages": [] - }, - "credit_card": { - "id": 13826563, - "first_name": "Bomb 3", - "last_name": "Test", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2028, - "customer_id": 19948683, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "123 Anywhere Lane", - "billing_city": "Boston", - "billing_state": "Ma", - "billing_zip": "02120", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": "", - "payment_type": "credit_card" - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Reactivate Subscription - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 20359140, + "state": "on_hold", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2018-01-05T17:15:50-06:00", + "created_at": "2018-01-05T17:15:49-06:00", + "updated_at": "2018-01-09T10:26:14-06:00", + "expires_at": null, + "balance_in_cents": 0, + "current_period_ends_at": "2023-01-05T17:15:00-06:00", + "next_assessment_at": "2023-01-05T17:15:00-06:00", + "canceled_at": null, + "cancellation_message": null, + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "automatic", + "snap_day": null, + "cancellation_method": null, + "current_period_started_at": "2018-01-05T17:15:49-06:00", + "previous_state": "active", + "signup_payment_id": 219829722, + "signup_revenue": "100.00", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": 10009991, + "product_price_in_cents": 10000, + "product_version_number": 1, + "payment_type": "credit_card", + "referral_code": "8y7jqr", + "coupon_use_count": null, + "coupon_uses_allowed": null, + "reason_code": null, + "automatically_resume_at": "2019-01-20T00:00:00-06:00", + "coupon_codes": [], + "customer": { + "id": 19948683, + "first_name": "Vanessa", + "last_name": "Test", + "organization": "", + "email": "vanessa@example.com", + "created_at": "2018-01-05T17:15:49-06:00", + "updated_at": "2018-01-05T17:15:51-06:00", + "reference": null, + "address": "123 Anywhere Ln", + "address_2": "", + "city": "Boston", + "state": "MA", + "zip": "02120", + "country": "US", + "phone": "555-555-1212", + "portal_invite_last_sent_at": "2018-01-05T17:15:51-06:00", + "portal_invite_last_accepted_at": null, + "verified": null, + "portal_customer_created_at": "2018-01-05T17:15:51-06:00", + "cc_emails": null, + "tax_exempt": false + }, + "product": { + "id": 4535643, + "name": "Annual Product", + "handle": "annual-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2017-08-25T10:25:31-05:00", + "updated_at": "2017-08-25T10:25:31-05:00", + "price_in_cents": 10000, + "interval": 12, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": true, + "return_params": "", + "taxable": false, + "update_return_url": "", + "tax_code": "", + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": "", + "product_family": { + "id": 1025627, + "name": "Acme Products", + "description": "", + "handle": "acme-products", + "accounting_code": null + }, + "public_signup_pages": [] + }, + "credit_card": { + "id": 13826563, + "first_name": "Bomb 3", + "last_name": "Test", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2028, + "customer_id": 19948683, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": "123 Anywhere Lane", + "billing_city": "Boston", + "billing_state": "Ma", + "billing_zip": "02120", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": "", + "payment_type": "credit_card" + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Reactivate Subscription + Chargify offers the ability to reactivate a previously canceled subscription. For details on how the reactivation works, and how to reactivate subscriptions through the application, see [reactivation](https://chargify.zendesk.com/hc/en-us/articles/4407898737691). **Please note: The term @@ -1071,31 +1071,31 @@ PUT request sent to: + The subscription will transition to active + The next billing date should not have changed -+ Any product-related charges should have been collected - -```go -ReactivateSubscription( - ctx context.Context, - subscriptionId int, ++ Any product-related charges should have been collected + +```go +ReactivateSubscription( + ctx context.Context, + subscriptionId int, body *models.ReactivateSubscriptionRequest) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.ReactivateSubscriptionRequest`](../../doc/models/reactivate-subscription-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.ReactivateSubscriptionRequest`](../../doc/models/reactivate-subscription-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -1103,13 +1103,15 @@ bodyCalendarBilling := models.ReactivationBilling{ ReactivationCharge: models.ToPointer(models.ReactivationCharge("prorated")), } +bodyResume := models.ReactivateSubscriptionRequestResumeContainer.FromBoolean(true) + body := models.ReactivateSubscriptionRequest{ IncludeTrial: models.ToPointer(true), PreserveBalance: models.ToPointer(true), CouponCode: models.ToPointer("10OFF"), UseCreditsAndPrepayments: models.ToPointer(true), - Resume: models.ToPointer(interface{}("[key1, val1][key2, val2]")), CalendarBilling: models.ToPointer(bodyCalendarBilling), + Resume: models.ToPointer(bodyResume), } apiResponse, err := subscriptionStatusController.ReactivateSubscription(ctx, subscriptionId, &body) @@ -1119,157 +1121,157 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 18220670, - "state": "active", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2017-06-27T13:45:15-05:00", - "created_at": "2017-06-27T13:45:13-05:00", - "updated_at": "2017-06-30T09:26:50-05:00", - "expires_at": null, - "balance_in_cents": 10000, - "current_period_ends_at": "2017-06-30T12:00:00-05:00", - "next_assessment_at": "2017-06-30T12:00:00-05:00", - "canceled_at": null, - "cancellation_message": null, - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "automatic", - "snap_day": "end", - "cancellation_method": null, - "current_period_started_at": "2017-06-27T13:45:13-05:00", - "previous_state": "active", - "signup_payment_id": 191819284, - "signup_revenue": "0.00", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": 0, - "product_price_in_cents": 0, - "product_version_number": 1, - "payment_type": null, - "referral_code": "d3pw7f", - "coupon_use_count": null, - "coupon_uses_allowed": null, - "reason_code": null, - "automatically_resume_at": null, - "current_billing_amount_in_cents": 10000, - "customer": { - "id": 17780587, - "first_name": "Catie", - "last_name": "Test", - "organization": "Acme, Inc.", - "email": "catie@example.com", - "created_at": "2017-06-27T13:01:05-05:00", - "updated_at": "2017-06-30T09:23:10-05:00", - "reference": "123ABC", - "address": "123 Anywhere Street", - "address_2": "Apartment #10", - "city": "Los Angeles", - "state": "CA", - "zip": "90210", - "country": "US", - "phone": "555-555-5555", - "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", - "portal_invite_last_accepted_at": null, - "verified": true, - "portal_customer_created_at": "2017-06-27T13:01:08-05:00", - "cc_emails": "support@example.com", - "tax_exempt": true, - "vat_number": "012345678" - }, - "product": { - "id": 4470347, - "name": "Zero Dollar Product", - "handle": "zero-dollar-product", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2017-03-23T10:54:12-05:00", - "updated_at": "2017-04-20T15:18:46-05:00", - "price_in_cents": 0, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": false, - "return_params": "", - "taxable": false, - "update_return_url": "", - "tax_code": "", - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": "", - "product_family": { - "id": 997233, - "name": "Acme Products", - "description": "", - "handle": "acme-products", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 316810, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" - } - ] - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Initiate Delayed Cancellation - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 18220670, + "state": "active", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2017-06-27T13:45:15-05:00", + "created_at": "2017-06-27T13:45:13-05:00", + "updated_at": "2017-06-30T09:26:50-05:00", + "expires_at": null, + "balance_in_cents": 10000, + "current_period_ends_at": "2017-06-30T12:00:00-05:00", + "next_assessment_at": "2017-06-30T12:00:00-05:00", + "canceled_at": null, + "cancellation_message": null, + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "automatic", + "snap_day": "end", + "cancellation_method": null, + "current_period_started_at": "2017-06-27T13:45:13-05:00", + "previous_state": "active", + "signup_payment_id": 191819284, + "signup_revenue": "0.00", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": 0, + "product_price_in_cents": 0, + "product_version_number": 1, + "payment_type": null, + "referral_code": "d3pw7f", + "coupon_use_count": null, + "coupon_uses_allowed": null, + "reason_code": null, + "automatically_resume_at": null, + "current_billing_amount_in_cents": 10000, + "customer": { + "id": 17780587, + "first_name": "Catie", + "last_name": "Test", + "organization": "Acme, Inc.", + "email": "catie@example.com", + "created_at": "2017-06-27T13:01:05-05:00", + "updated_at": "2017-06-30T09:23:10-05:00", + "reference": "123ABC", + "address": "123 Anywhere Street", + "address_2": "Apartment #10", + "city": "Los Angeles", + "state": "CA", + "zip": "90210", + "country": "US", + "phone": "555-555-5555", + "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", + "portal_invite_last_accepted_at": null, + "verified": true, + "portal_customer_created_at": "2017-06-27T13:01:08-05:00", + "cc_emails": "support@example.com", + "tax_exempt": true, + "vat_number": "012345678" + }, + "product": { + "id": 4470347, + "name": "Zero Dollar Product", + "handle": "zero-dollar-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2017-03-23T10:54:12-05:00", + "updated_at": "2017-04-20T15:18:46-05:00", + "price_in_cents": 0, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": false, + "return_params": "", + "taxable": false, + "update_return_url": "", + "tax_code": "", + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": "", + "product_family": { + "id": 997233, + "name": "Acme Products", + "description": "", + "handle": "acme-products", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 316810, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" + } + ] + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Initiate Delayed Cancellation + Chargify offers the ability to cancel a subscription at the end of the current billing period. This period is set by its current product. Requesting to cancel the subscription at the end of the period sets the `cancel_at_end_of_period` flag to true. -Note that you cannot set `cancel_at_end_of_period` at subscription creation, or if the subscription is past due. - -```go -InitiateDelayedCancellation( - ctx context.Context, - subscriptionId int, +Note that you cannot set `cancel_at_end_of_period` at subscription creation, or if the subscription is past due. + +```go +InitiateDelayedCancellation( + ctx context.Context, + subscriptionId int, body *models.CancellationRequest) ( models.ApiResponse[models.DelayedCancellationResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.CancellationRequest`](../../doc/models/cancellation-request.md) | Body, Optional | - | - -## Response Type - -[`models.DelayedCancellationResponse`](../../doc/models/delayed-cancellation-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.CancellationRequest`](../../doc/models/cancellation-request.md) | Body, Optional | - | + +## Response Type + +[`models.DelayedCancellationResponse`](../../doc/models/delayed-cancellation-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -1280,43 +1282,43 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Cancel Delayed Cancellation - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Cancel Delayed Cancellation + Removing the delayed cancellation on a subscription will ensure that it doesn't get canceled at the end of the period that it is in. The request will reset the `cancel_at_end_of_period` flag to `false`. -This endpoint is idempotent. If the subscription was not set to cancel in the future, removing the delayed cancellation has no effect and the call will be successful. - -```go -CancelDelayedCancellation( - ctx context.Context, +This endpoint is idempotent. If the subscription was not set to cancel in the future, removing the delayed cancellation has no effect and the call will be successful. + +```go +CancelDelayedCancellation( + ctx context.Context, subscriptionId int) ( models.ApiResponse[models.DelayedCancellationResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -[`models.DelayedCancellationResponse`](../../doc/models/delayed-cancellation-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +[`models.DelayedCancellationResponse`](../../doc/models/delayed-cancellation-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -1327,49 +1329,49 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "message": "This subscription will no longer be canceled" -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | - - -# Cancel Dunning - -If a subscription is currently in dunning, the subscription will be set to active and the active Dunner will be resolved. - -```go -CancelDunning( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +{ + "message": "This subscription will no longer be canceled" +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | + + +# Cancel Dunning + +If a subscription is currently in dunning, the subscription will be set to active and the active Dunner will be resolved. + +```go +CancelDunning( + ctx context.Context, subscriptionId int) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -1380,12 +1382,12 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Preview Renewal - +} +``` + + +# Preview Renewal + The Chargify API allows you to preview a renewal by posting to the renewals endpoint. Renewal Preview is an object representing a subscription’s next assessment. You can retrieve it to see a snapshot of how much your customer will be charged on their next renewal. The "Next Billing" amount and "Next Billing" date are already represented in the UI on each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). @@ -1407,49 +1409,59 @@ Optionally, **you may provide your own custom quantities** for any component to ## Subscription Side Effects -You can request a `POST` to obtain this data from the endpoint without any side effects. Plain and simple, this will preview data, not log any changes against a subscription. - -```go -PreviewRenewal( - ctx context.Context, - subscriptionId int, +You can request a `POST` to obtain this data from the endpoint without any side effects. Plain and simple, this will preview data, not log any changes against a subscription. + +```go +PreviewRenewal( + ctx context.Context, + subscriptionId int, body *models.RenewalPreviewRequest) ( models.ApiResponse[models.RenewalPreviewResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.RenewalPreviewRequest`](../../doc/models/renewal-preview-request.md) | Body, Optional | - | - -## Response Type - -[`models.RenewalPreviewResponse`](../../doc/models/renewal-preview-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.RenewalPreviewRequest`](../../doc/models/renewal-preview-request.md) | Body, Optional | - | + +## Response Type + +[`models.RenewalPreviewResponse`](../../doc/models/renewal-preview-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 +bodyComponents0ComponentId := models.RenewalPreviewComponentComponentIdContainer.FromNumber(10708) + bodyComponents0 := models.RenewalPreviewComponent{ - ComponentId: models.ToPointer(interface{}("[key1, val1][key2, val2]")), Quantity: models.ToPointer(10000), + ComponentId: models.ToPointer(bodyComponents0ComponentId), } +bodyComponents1ComponentId := models.RenewalPreviewComponentComponentIdContainer.FromString("handle:small-instance-hours") + +bodyComponents1PricePointId := models.RenewalPreviewComponentPricePointIdContainer.FromNumber(8712) + bodyComponents1 := models.RenewalPreviewComponent{ - ComponentId: models.ToPointer(interface{}("[key1, val1][key2, val2]")), Quantity: models.ToPointer(10000), - PricePointId: models.ToPointer(interface{}("[key1, val1][key2, val2]")), + ComponentId: models.ToPointer(bodyComponents1ComponentId), + PricePointId: models.ToPointer(bodyComponents1PricePointId), } +bodyComponents2ComponentId := models.RenewalPreviewComponentComponentIdContainer.FromString("handle:large-instance-hours") + +bodyComponents2PricePointId := models.RenewalPreviewComponentPricePointIdContainer.FromString("handle:startup-pricing") + bodyComponents2 := models.RenewalPreviewComponent{ - ComponentId: models.ToPointer(interface{}("[key1, val1][key2, val2]")), Quantity: models.ToPointer(100), - PricePointId: models.ToPointer(interface{}("[key1, val1][key2, val2]")), + ComponentId: models.ToPointer(bodyComponents2ComponentId), + PricePointId: models.ToPointer(bodyComponents2PricePointId), } bodyComponents := []models.RenewalPreviewComponent{bodyComponents0, bodyComponents1, bodyComponents2} @@ -1464,57 +1476,57 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "renewal_preview": { - "next_assessment_at": "2017-03-13T12:50:55-04:00", - "subtotal_in_cents": 6000, - "total_tax_in_cents": 0, - "total_discount_in_cents": 0, - "total_in_cents": 6000, - "existing_balance_in_cents": 0, - "total_amount_due_in_cents": 6000, - "uncalculated_taxes": false, - "line_items": [ - { - "transaction_type": "charge", - "kind": "baseline", - "amount_in_cents": 5000, - "memo": "Gold Product (03/13/2017 - 04/13/2017)", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "product_id": 1, - "product_handle": "gold-product", - "product_name": "Gold Product", - "period_range_start": "01/10/2024", - "period_range_end": "02/10/2024" - }, - { - "transaction_type": "charge", - "kind": "quantity_based_component", - "amount_in_cents": 1000, - "memo": "Quantity Component: 10 Quantity Components", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "component_id": 104, - "component_handle": "quantity-component", - "component_name": "Quantity Component", - "period_range_start": "01/10/2024", - "period_range_end": "02/10/2024" - } - ] - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "renewal_preview": { + "next_assessment_at": "2017-03-13T12:50:55-04:00", + "subtotal_in_cents": 6000, + "total_tax_in_cents": 0, + "total_discount_in_cents": 0, + "total_in_cents": 6000, + "existing_balance_in_cents": 0, + "total_amount_due_in_cents": 6000, + "uncalculated_taxes": false, + "line_items": [ + { + "transaction_type": "charge", + "kind": "baseline", + "amount_in_cents": 5000, + "memo": "Gold Product (03/13/2017 - 04/13/2017)", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "product_id": 1, + "product_handle": "gold-product", + "product_name": "Gold Product", + "period_range_start": "01/10/2024", + "period_range_end": "02/10/2024" + }, + { + "transaction_type": "charge", + "kind": "quantity_based_component", + "amount_in_cents": 1000, + "memo": "Quantity Component: 10 Quantity Components", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "component_id": 104, + "component_handle": "quantity-component", + "component_name": "Quantity Component", + "period_range_start": "01/10/2024", + "period_range_end": "02/10/2024" + } + ] + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/controllers/subscriptions.md b/doc/controllers/subscriptions.md index 7c45e047..44238095 100644 --- a/doc/controllers/subscriptions.md +++ b/doc/controllers/subscriptions.md @@ -1,15 +1,15 @@ -# Subscriptions - -```go -subscriptionsController := client.SubscriptionsController() -``` - -## Class Name - -`SubscriptionsController` - -## Methods - +# Subscriptions + +```go +subscriptionsController := client.SubscriptionsController() +``` + +## Class Name + +`SubscriptionsController` + +## Methods + * [Create Subscription](../../doc/controllers/subscriptions.md#create-subscription) * [List Subscriptions](../../doc/controllers/subscriptions.md#list-subscriptions) * [Update Subscription](../../doc/controllers/subscriptions.md#update-subscription) @@ -21,11 +21,11 @@ subscriptionsController := client.SubscriptionsController() * [Preview Subscription](../../doc/controllers/subscriptions.md#preview-subscription) * [Apply Coupons to Subscription](../../doc/controllers/subscriptions.md#apply-coupons-to-subscription) * [Remove Coupon From Subscription](../../doc/controllers/subscriptions.md#remove-coupon-from-subscription) -* [Activate Subscription](../../doc/controllers/subscriptions.md#activate-subscription) - - -# Create Subscription - +* [Activate Subscription](../../doc/controllers/subscriptions.md#activate-subscription) + + +# Create Subscription + Full documentation on how subscriptions operate within Chargify can be located under the following topics: + [Subscriptions Reference](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577172749-Subscription-Introduction) @@ -635,29 +635,29 @@ Each of them is required. "ip_address": "1.2.3.4" } } -``` - -```go -CreateSubscription( - ctx context.Context, +``` + +```go +CreateSubscription( + ctx context.Context, body *models.CreateSubscriptionRequest) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() bodySubscriptionCustomerAttributes := models.CustomerAttributes{ @@ -675,19 +675,23 @@ bodySubscriptionCustomerAttributes := models.CustomerAttributes{ Phone: models.ToPointer("(617) 111 - 0000"), } +bodySubscriptionCreditCardAttributesExpirationMonth := models.PaymentProfileAttributesExpirationMonthContainer.FromString("1") + +bodySubscriptionCreditCardAttributesExpirationYear := models.PaymentProfileAttributesExpirationYearContainer.FromString("2021") + bodySubscriptionCreditCardAttributes := models.PaymentProfileAttributes{ FirstName: models.ToPointer("Joe"), LastName: models.ToPointer("Smith"), FullNumber: models.ToPointer("4111111111111111"), CardType: models.ToPointer(models.CardType("visa")), - ExpirationMonth: models.ToPointer(interface{}("[key1, val1][key2, val2]")), - ExpirationYear: models.ToPointer(interface{}("[key1, val1][key2, val2]")), BillingAddress: models.ToPointer("123 Mass Ave."), BillingAddress2: models.NewOptional(models.ToPointer("billing_address_22")), BillingCity: models.ToPointer("Boston"), BillingState: models.ToPointer("MA"), BillingCountry: models.ToPointer("US"), BillingZip: models.ToPointer("02120"), + ExpirationMonth: models.ToPointer(bodySubscriptionCreditCardAttributesExpirationMonth), + ExpirationYear: models.ToPointer(bodySubscriptionCreditCardAttributesExpirationYear), } bodySubscription := models.CreateSubscription{ @@ -707,157 +711,157 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 15236915, - "state": "active", - "balance_in_cents": 0, - "total_revenue_in_cents": 14000, - "product_price_in_cents": 1000, - "product_version_number": 7, - "current_period_ends_at": "2016-11-15T14:48:10-05:00", - "next_assessment_at": "2016-11-15T14:48:10-05:00", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2016-11-14T14:48:12-05:00", - "expires_at": null, - "created_at": "2016-11-14T14:48:10-05:00", - "updated_at": "2016-11-14T15:24:41-05:00", - "cancellation_message": null, - "cancellation_method": "merchant_api", - "cancel_at_end_of_period": null, - "canceled_at": null, - "current_period_started_at": "2016-11-14T14:48:10-05:00", - "previous_state": "active", - "signup_payment_id": 162269766, - "signup_revenue": "260.00", - "delayed_cancel_at": null, - "coupon_code": "5SNN6HFK3GBH", - "payment_collection_method": "automatic", - "snap_day": null, - "reason_code": null, - "receives_invoice_emails": false, - "customer": { - "first_name": "Curtis", - "last_name": "Test", - "email": "curtis@example.com", - "cc_emails": "jeff@example.com", - "organization": "", - "reference": null, - "id": 14714298, - "created_at": "2016-11-14T14:48:10-05:00", - "updated_at": "2016-11-14T14:48:13-05:00", - "address": "123 Anywhere Street", - "address_2": "", - "city": "Boulder", - "state": "CO", - "zip": "80302", - "country": "US", - "phone": "", - "verified": false, - "portal_customer_created_at": "2016-11-14T14:48:13-05:00", - "portal_invite_last_sent_at": "2016-11-14T14:48:13-05:00", - "portal_invite_last_accepted_at": null, - "tax_exempt": false, - "vat_number": "012345678" - }, - "product": { - "id": 3792003, - "name": "$10 Basic Plan", - "handle": "basic", - "description": "lorem ipsum", - "accounting_code": "basic", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "day", - "initial_charge_in_cents": null, - "expiration_interval": null, - "expiration_interval_unit": "never", - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "initial_charge_after_trial": false, - "return_params": "", - "request_credit_card": false, - "require_credit_card": false, - "created_at": "2016-03-24T13:38:39-04:00", - "updated_at": "2016-11-03T13:03:05-04:00", - "archived_at": null, - "update_return_url": "", - "update_return_params": "", - "product_family": { - "id": 527890, - "name": "Acme Projects", - "handle": "billing-plans", - "accounting_code": null, - "description": "" - }, - "public_signup_pages": [ - { - "id": 281054, - "url": "https://general-goods.chargify.com/subscribe/kqvmfrbgd89q/basic" - }, - { - "id": 281240, - "url": "https://general-goods.chargify.com/subscribe/dkffht5dxfd8/basic" - }, - { - "id": 282694, - "url": "https://general-goods.chargify.com/subscribe/jwffwgdd95s8/basic" - } - ], - "taxable": false, - "version_number": 7, - "product_price_point_name": "Default" - }, - "credit_card": { - "id": 10191713, - "payment_type": "credit_card", - "first_name": "Curtis", - "last_name": "Test", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2026, - "billing_address": "123 Anywhere Street", - "billing_address_2": "", - "billing_city": "Boulder", - "billing_state": null, - "billing_country": "", - "billing_zip": "80302", - "current_vault": "bogus", - "vault_token": "1", - "customer_vault_token": null, - "customer_id": 14714298 - }, - "payment_type": "credit_card", - "referral_code": "w7kjc9", - "next_product_id": null, - "coupon_use_count": 1, - "coupon_uses_allowed": 1, - "next_product_handle": null, - "stored_credential_transaction_id": 125566112256688, - "dunning_communication_delay_enabled": true, - "dunning_communication_delay_time_zone": "Eastern Time (US & Canada)" - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Subscriptions - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 15236915, + "state": "active", + "balance_in_cents": 0, + "total_revenue_in_cents": 14000, + "product_price_in_cents": 1000, + "product_version_number": 7, + "current_period_ends_at": "2016-11-15T14:48:10-05:00", + "next_assessment_at": "2016-11-15T14:48:10-05:00", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2016-11-14T14:48:12-05:00", + "expires_at": null, + "created_at": "2016-11-14T14:48:10-05:00", + "updated_at": "2016-11-14T15:24:41-05:00", + "cancellation_message": null, + "cancellation_method": "merchant_api", + "cancel_at_end_of_period": null, + "canceled_at": null, + "current_period_started_at": "2016-11-14T14:48:10-05:00", + "previous_state": "active", + "signup_payment_id": 162269766, + "signup_revenue": "260.00", + "delayed_cancel_at": null, + "coupon_code": "5SNN6HFK3GBH", + "payment_collection_method": "automatic", + "snap_day": null, + "reason_code": null, + "receives_invoice_emails": false, + "customer": { + "first_name": "Curtis", + "last_name": "Test", + "email": "curtis@example.com", + "cc_emails": "jeff@example.com", + "organization": "", + "reference": null, + "id": 14714298, + "created_at": "2016-11-14T14:48:10-05:00", + "updated_at": "2016-11-14T14:48:13-05:00", + "address": "123 Anywhere Street", + "address_2": "", + "city": "Boulder", + "state": "CO", + "zip": "80302", + "country": "US", + "phone": "", + "verified": false, + "portal_customer_created_at": "2016-11-14T14:48:13-05:00", + "portal_invite_last_sent_at": "2016-11-14T14:48:13-05:00", + "portal_invite_last_accepted_at": null, + "tax_exempt": false, + "vat_number": "012345678" + }, + "product": { + "id": 3792003, + "name": "$10 Basic Plan", + "handle": "basic", + "description": "lorem ipsum", + "accounting_code": "basic", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "day", + "initial_charge_in_cents": null, + "expiration_interval": null, + "expiration_interval_unit": "never", + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "initial_charge_after_trial": false, + "return_params": "", + "request_credit_card": false, + "require_credit_card": false, + "created_at": "2016-03-24T13:38:39-04:00", + "updated_at": "2016-11-03T13:03:05-04:00", + "archived_at": null, + "update_return_url": "", + "update_return_params": "", + "product_family": { + "id": 527890, + "name": "Acme Projects", + "handle": "billing-plans", + "accounting_code": null, + "description": "" + }, + "public_signup_pages": [ + { + "id": 281054, + "url": "https://general-goods.chargify.com/subscribe/kqvmfrbgd89q/basic" + }, + { + "id": 281240, + "url": "https://general-goods.chargify.com/subscribe/dkffht5dxfd8/basic" + }, + { + "id": 282694, + "url": "https://general-goods.chargify.com/subscribe/jwffwgdd95s8/basic" + } + ], + "taxable": false, + "version_number": 7, + "product_price_point_name": "Default" + }, + "credit_card": { + "id": 10191713, + "payment_type": "credit_card", + "first_name": "Curtis", + "last_name": "Test", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2026, + "billing_address": "123 Anywhere Street", + "billing_address_2": "", + "billing_city": "Boulder", + "billing_state": null, + "billing_country": "", + "billing_zip": "80302", + "current_vault": "bogus", + "vault_token": "1", + "customer_vault_token": null, + "customer_id": 14714298 + }, + "payment_type": "credit_card", + "referral_code": "w7kjc9", + "next_product_id": null, + "coupon_use_count": 1, + "coupon_uses_allowed": 1, + "next_product_handle": null, + "stored_credential_transaction_id": 125566112256688, + "dunning_communication_delay_enabled": true, + "dunning_communication_delay_time_zone": "Eastern Time (US & Canada)" + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Subscriptions + This method will return an array of subscriptions from a Site. Pay close attention to query string filters and pagination in order to control responses from the server. ## Search for a subscription @@ -866,76 +870,84 @@ Use the query strings below to search for a subscription using the criteria avai ## Self-Service Page token -Self-Service Page token for the subscriptions is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. - -```go -ListSubscriptions( - ctx context.Context,input ListSubscriptionsInput) ( +Self-Service Page token for the subscriptions is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. + +```go +ListSubscriptions( + ctx context.Context, + input ListSubscriptionsInput) ( models.ApiResponse[[]models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `state` | [`*models.SubscriptionStateFilter`](../../doc/models/subscription-state-filter.md) | Query, Optional | The current state of the subscription | -| `product` | `*int` | Query, Optional | The product id of the subscription. (Note that the product handle cannot be used.) | -| `productPricePointId` | `*int` | Query, Optional | The ID of the product price point. If supplied, product is required | -| `coupon` | `*int` | Query, Optional | The numeric id of the coupon currently applied to the subscription. (This can be found in the URL when editing a coupon. Note that the coupon code cannot be used.) | -| `dateField` | [`*models.SubscriptionDateField`](../../doc/models/subscription-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Allowed Values: , current_period_ends_at, current_period_starts_at, created_at, activated_at, canceled_at, expires_at, trial_started_at, trial_ended_at, updated_at | -| `startDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `start_date=2022-07-01`. | -| `endDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `end_date=2022-08-01`. | -| `startDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `start_datetime=2022-07-01 09:00:05`. | -| `endDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `end_datetime=2022-08-01 10:00:05`. | -| `metadata` | `map[string]string` | Query, Optional | The value of the metadata field specified in the parameter. Use in query `metadata[my-field]=value&metadata[other-field]=another_value`. | -| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | -| `sort` | [`*models.SubscriptionSort`](../../doc/models/subscription-sort.md) | Query, Optional | The attribute by which to sort | -| `include` | [`[]models.SubscriptionListInclude`](../../doc/models/subscription-list-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include[]=self_service_page_token`. | - -## Response Type - -[`[]models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `state` | [`*models.SubscriptionStateFilter`](../../doc/models/subscription-state-filter.md) | Query, Optional | The current state of the subscription | +| `product` | `*int` | Query, Optional | The product id of the subscription. (Note that the product handle cannot be used.) | +| `productPricePointId` | `*int` | Query, Optional | The ID of the product price point. If supplied, product is required | +| `coupon` | `*int` | Query, Optional | The numeric id of the coupon currently applied to the subscription. (This can be found in the URL when editing a coupon. Note that the coupon code cannot be used.) | +| `dateField` | [`*models.SubscriptionDateField`](../../doc/models/subscription-date-field.md) | Query, Optional | The type of filter you'd like to apply to your search. Allowed Values: , current_period_ends_at, current_period_starts_at, created_at, activated_at, canceled_at, expires_at, trial_started_at, trial_ended_at, updated_at | +| `startDate` | `*time.Time` | Query, Optional | The start date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `start_date=2022-07-01`. | +| `endDate` | `*time.Time` | Query, Optional | The end date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `end_date=2022-08-01`. | +| `startDatetime` | `*time.Time` | Query, Optional | The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `start_datetime=2022-07-01 09:00:05`. | +| `endDatetime` | `*time.Time` | Query, Optional | The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `end_datetime=2022-08-01 10:00:05`. | +| `metadata` | `map[string]string` | Query, Optional | The value of the metadata field specified in the parameter. Use in query `metadata[my-field]=value&metadata[other-field]=another_value`. | +| `direction` | [`*models.SortingDirection`](../../doc/models/sorting-direction.md) | Query, Optional | Controls the order in which results are returned.
Use in query `direction=asc`. | +| `sort` | [`*models.SubscriptionSort`](../../doc/models/subscription-sort.md) | Query, Optional | The attribute by which to sort | +| `include` | [`[]models.SubscriptionListInclude`](../../doc/models/subscription-list-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include[]=self_service_page_token`. | + +## Response Type + +[`[]models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -startDate, err := time.Parse(time.RFC3339, "2022-07-01") + +collectedInputStartDate, err := time.Parse(time.RFC3339, "2022-07-01") if err != nil { log.Fatalln(err) } -endDate, err := time.Parse(time.RFC3339, "2022-08-01") +collectedInputEndDate, err := time.Parse(time.RFC3339, "2022-08-01") if err != nil { log.Fatalln(err) } -startDatetime, err := time.Parse(time.RFC3339, "2022-07-01 09:00:05") +collectedInputStartDatetime, err := time.Parse(time.RFC3339, "2022-07-01 09:00:05") if err != nil { log.Fatalln(err) } -endDatetime, err := time.Parse(time.RFC3339, "2022-08-01 10:00:05") +collectedInputEndDatetime, err := time.Parse(time.RFC3339, "2022-08-01 10:00:05") if err != nil { log.Fatalln(err) } -sort := models.SubscriptionSort("signup_date")Liquid error: Value cannot be null. (Parameter 'key') +collectedInput := advancedbilling.ListSubscriptionsInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), + Sort: models.ToPointer(models.SubscriptionSort("signup_date")), +Liquid error: Value cannot be null. (Parameter 'key') StartDate: models.ToPointer(collectedInputStartDate), + EndDate: models.ToPointer(collectedInputEndDate), + StartDatetime: models.ToPointer(collectedInputStartDatetime), + EndDatetime: models.ToPointer(collectedInputEndDatetime), +} -apiResponse, err := subscriptionsController.ListSubscriptions(ctx, &page, &perPage, nil, nil, nil, nil, nil, &startDate, &endDate, &startDatetime, &endDatetime, nil, nil, &sort, Liquid error: Value cannot be null. (Parameter 'key')) +apiResponse, err := subscriptionsController.ListSubscriptions(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Update Subscription - +} +``` + + +# Update Subscription + The subscription endpoint allows you to instantly update one or many attributes about a subscription in a single call. ## Update Subscription Payment Method @@ -976,31 +988,31 @@ The server response will not return data under the key/value pair of `next_billi For a subscription using Calendar Billing, setting the next billing date is a bit different. Send the `snap_day` attribute to change the calendar billing date for **a subscription using a product eligible for calendar billing**. -Note: If you change the product associated with a subscription that contains a `snap_date` and immediately `READ/GET` the subscription data, it will still contain evidence of the existing `snap_date`. This is due to the fact that a product change is instantanous and only affects the product associated with a subscription. After the `next_billing` date arrives, the `snap_day` associated with the subscription will return to `null.` Another way of looking at this is that you willl have to wait for the next billing cycle to arrive before the `snap_date` will reset to `null`. - -```go -UpdateSubscription( - ctx context.Context, - subscriptionId int, +Note: If you change the product associated with a subscription that contains a `snap_date` and immediately `READ/GET` the subscription data, it will still contain evidence of the existing `snap_date`. This is due to the fact that a product change is instantanous and only affects the product associated with a subscription. After the `next_billing` date arrives, the `snap_day` associated with the subscription will return to `null.` Another way of looking at this is that you willl have to wait for the next billing cycle to arrive before the `snap_date` will reset to `null`. + +```go +UpdateSubscription( + ctx context.Context, + subscriptionId int, body *models.UpdateSubscriptionRequest) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.UpdateSubscriptionRequest`](../../doc/models/update-subscription-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.UpdateSubscriptionRequest`](../../doc/models/update-subscription-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -1030,157 +1042,157 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 18220670, - "state": "active", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2017-06-27T13:45:15-05:00", - "created_at": "2017-06-27T13:45:13-05:00", - "updated_at": "2017-06-30T09:26:50-05:00", - "expires_at": null, - "balance_in_cents": 10000, - "current_period_ends_at": "2017-06-30T12:00:00-05:00", - "next_assessment_at": "2017-06-30T12:00:00-05:00", - "canceled_at": null, - "cancellation_message": null, - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "automatic", - "snap_day": "end", - "cancellation_method": null, - "current_period_started_at": "2017-06-27T13:45:13-05:00", - "previous_state": "active", - "signup_payment_id": 191819284, - "signup_revenue": "0.00", - "delayed_cancel_at": null, - "coupon_code": null, - "total_revenue_in_cents": 0, - "product_price_in_cents": 0, - "product_version_number": 1, - "payment_type": null, - "referral_code": "d3pw7f", - "coupon_use_count": null, - "coupon_uses_allowed": null, - "reason_code": null, - "automatically_resume_at": null, - "current_billing_amount_in_cents": 10000, - "receives_invoice_emails": false, - "customer": { - "id": 17780587, - "first_name": "Catie", - "last_name": "Test", - "organization": "Acme, Inc.", - "email": "catie@example.com", - "created_at": "2017-06-27T13:01:05-05:00", - "updated_at": "2017-06-30T09:23:10-05:00", - "reference": "123ABC", - "address": "123 Anywhere Street", - "address_2": "Apartment #10", - "city": "Los Angeles", - "state": "CA", - "zip": "90210", - "country": "US", - "phone": "555-555-5555", - "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", - "portal_invite_last_accepted_at": null, - "verified": true, - "portal_customer_created_at": "2017-06-27T13:01:08-05:00", - "cc_emails": "support@example.com", - "tax_exempt": true - }, - "product": { - "id": 4470347, - "name": "Zero Dollar Product", - "handle": "zero-dollar-product", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2017-03-23T10:54:12-05:00", - "updated_at": "2017-04-20T15:18:46-05:00", - "price_in_cents": 0, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": null, - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": false, - "return_params": "", - "taxable": false, - "update_return_url": "", - "tax_code": "", - "initial_charge_after_trial": false, - "version_number": 1, - "update_return_params": "", - "product_family": { - "id": 997233, - "name": "Acme Products", - "description": "", - "handle": "acme-products", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 316810, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" - } - ] - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# Read Subscription - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 18220670, + "state": "active", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2017-06-27T13:45:15-05:00", + "created_at": "2017-06-27T13:45:13-05:00", + "updated_at": "2017-06-30T09:26:50-05:00", + "expires_at": null, + "balance_in_cents": 10000, + "current_period_ends_at": "2017-06-30T12:00:00-05:00", + "next_assessment_at": "2017-06-30T12:00:00-05:00", + "canceled_at": null, + "cancellation_message": null, + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "automatic", + "snap_day": "end", + "cancellation_method": null, + "current_period_started_at": "2017-06-27T13:45:13-05:00", + "previous_state": "active", + "signup_payment_id": 191819284, + "signup_revenue": "0.00", + "delayed_cancel_at": null, + "coupon_code": null, + "total_revenue_in_cents": 0, + "product_price_in_cents": 0, + "product_version_number": 1, + "payment_type": null, + "referral_code": "d3pw7f", + "coupon_use_count": null, + "coupon_uses_allowed": null, + "reason_code": null, + "automatically_resume_at": null, + "current_billing_amount_in_cents": 10000, + "receives_invoice_emails": false, + "customer": { + "id": 17780587, + "first_name": "Catie", + "last_name": "Test", + "organization": "Acme, Inc.", + "email": "catie@example.com", + "created_at": "2017-06-27T13:01:05-05:00", + "updated_at": "2017-06-30T09:23:10-05:00", + "reference": "123ABC", + "address": "123 Anywhere Street", + "address_2": "Apartment #10", + "city": "Los Angeles", + "state": "CA", + "zip": "90210", + "country": "US", + "phone": "555-555-5555", + "portal_invite_last_sent_at": "2017-06-27T13:45:16-05:00", + "portal_invite_last_accepted_at": null, + "verified": true, + "portal_customer_created_at": "2017-06-27T13:01:08-05:00", + "cc_emails": "support@example.com", + "tax_exempt": true + }, + "product": { + "id": 4470347, + "name": "Zero Dollar Product", + "handle": "zero-dollar-product", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2017-03-23T10:54:12-05:00", + "updated_at": "2017-04-20T15:18:46-05:00", + "price_in_cents": 0, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": null, + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": false, + "return_params": "", + "taxable": false, + "update_return_url": "", + "tax_code": "", + "initial_charge_after_trial": false, + "version_number": 1, + "update_return_params": "", + "product_family": { + "id": 997233, + "name": "Acme Products", + "description": "", + "handle": "acme-products", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 316810, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargify.com/subscribe/69x825m78v3d/zero-dollar-product" + } + ] + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# Read Subscription + Use this endpoint to find subscription details. ## Self-Service Page token -Self-Service Page token for the subscription is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. - -```go -ReadSubscription( - ctx context.Context, - subscriptionId int, +Self-Service Page token for the subscription is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. + +```go +ReadSubscription( + ctx context.Context, + subscriptionId int, include []models.SubscriptionInclude) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `include` | [`[]models.SubscriptionInclude`](../../doc/models/subscription-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include[]=coupons&include[]=self_service_page_token`. | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `include` | [`[]models.SubscriptionInclude`](../../doc/models/subscription-include.md) | Query, Optional | Allows including additional data in the response. Use in query: `include[]=coupons&include[]=self_service_page_token`. | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222Liquid error: Value cannot be null. (Parameter 'key') @@ -1191,151 +1203,151 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 15236915, - "state": "active", - "balance_in_cents": 0, - "total_revenue_in_cents": 14000, - "product_price_in_cents": 1000, - "product_version_number": 7, - "current_period_ends_at": "2016-11-15T14:48:10-05:00", - "next_assessment_at": "2016-11-15T14:48:10-05:00", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2016-11-14T14:48:12-05:00", - "expires_at": null, - "created_at": "2016-11-14T14:48:10-05:00", - "updated_at": "2016-11-14T15:24:41-05:00", - "cancellation_message": null, - "cancellation_method": null, - "cancel_at_end_of_period": null, - "canceled_at": null, - "current_period_started_at": "2016-11-14T14:48:10-05:00", - "previous_state": "active", - "signup_payment_id": 162269766, - "signup_revenue": "260.00", - "delayed_cancel_at": null, - "coupon_code": "5SNN6HFK3GBH", - "payment_collection_method": "automatic", - "snap_day": null, - "reason_code": null, - "receives_invoice_emails": false, - "net_terms": 0, - "customer": { - "first_name": "Curtis", - "last_name": "Test", - "email": "curtis@example.com", - "cc_emails": "jeff@example.com", - "organization": "", - "reference": null, - "id": 14714298, - "created_at": "2016-11-14T14:48:10-05:00", - "updated_at": "2016-11-14T14:48:13-05:00", - "address": "123 Anywhere Street", - "address_2": "", - "city": "Boulder", - "state": "CO", - "zip": "80302", - "country": "US", - "phone": "", - "verified": false, - "portal_customer_created_at": "2016-11-14T14:48:13-05:00", - "portal_invite_last_sent_at": "2016-11-14T14:48:13-05:00", - "portal_invite_last_accepted_at": null, - "tax_exempt": false, - "vat_number": "012345678" - }, - "product": { - "id": 3792003, - "name": "$10 Basic Plan", - "handle": "basic", - "description": "lorem ipsum", - "accounting_code": "basic", - "price_in_cents": 1000, - "interval": 1, - "interval_unit": "day", - "initial_charge_in_cents": null, - "expiration_interval": null, - "expiration_interval_unit": "never", - "trial_price_in_cents": null, - "trial_interval": null, - "trial_interval_unit": "month", - "initial_charge_after_trial": false, - "return_params": "", - "request_credit_card": false, - "require_credit_card": false, - "created_at": "2016-03-24T13:38:39-04:00", - "updated_at": "2016-11-03T13:03:05-04:00", - "archived_at": null, - "update_return_url": "", - "update_return_params": "", - "product_family": { - "id": 527890, - "name": "Acme Projects", - "handle": "billing-plans", - "accounting_code": null, - "description": "" - }, - "public_signup_pages": [ - { - "id": 281054, - "url": "https://general-goods.chargify.com/subscribe/kqvmfrbgd89q/basic" - }, - { - "id": 281240, - "url": "https://general-goods.chargify.com/subscribe/dkffht5dxfd8/basic" - }, - { - "id": 282694, - "url": "https://general-goods.chargify.com/subscribe/jwffwgdd95s8/basic" - } - ], - "taxable": false, - "version_number": 7, - "product_price_point_name": "Default" - }, - "credit_card": { - "id": 10191713, - "payment_type": "credit_card", - "first_name": "Curtis", - "last_name": "Test", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2026, - "billing_address": "123 Anywhere Street", - "billing_address_2": "", - "billing_city": "Boulder", - "billing_state": null, - "billing_country": "", - "billing_zip": "80302", - "current_vault": "bogus", - "vault_token": "1", - "customer_vault_token": null, - "customer_id": 14714298 - }, - "payment_type": "credit_card", - "referral_code": "w7kjc9", - "next_product_id": null, - "coupon_use_count": 1, - "coupon_uses_allowed": 1, - "stored_credential_transaction_id": 166411599220288, - "on_hold_at": null, - "scheduled_cancellation_at": "2016-11-14T14:48:13-05:00" - } -} -``` - - -# Override Subscription - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 15236915, + "state": "active", + "balance_in_cents": 0, + "total_revenue_in_cents": 14000, + "product_price_in_cents": 1000, + "product_version_number": 7, + "current_period_ends_at": "2016-11-15T14:48:10-05:00", + "next_assessment_at": "2016-11-15T14:48:10-05:00", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2016-11-14T14:48:12-05:00", + "expires_at": null, + "created_at": "2016-11-14T14:48:10-05:00", + "updated_at": "2016-11-14T15:24:41-05:00", + "cancellation_message": null, + "cancellation_method": null, + "cancel_at_end_of_period": null, + "canceled_at": null, + "current_period_started_at": "2016-11-14T14:48:10-05:00", + "previous_state": "active", + "signup_payment_id": 162269766, + "signup_revenue": "260.00", + "delayed_cancel_at": null, + "coupon_code": "5SNN6HFK3GBH", + "payment_collection_method": "automatic", + "snap_day": null, + "reason_code": null, + "receives_invoice_emails": false, + "net_terms": 0, + "customer": { + "first_name": "Curtis", + "last_name": "Test", + "email": "curtis@example.com", + "cc_emails": "jeff@example.com", + "organization": "", + "reference": null, + "id": 14714298, + "created_at": "2016-11-14T14:48:10-05:00", + "updated_at": "2016-11-14T14:48:13-05:00", + "address": "123 Anywhere Street", + "address_2": "", + "city": "Boulder", + "state": "CO", + "zip": "80302", + "country": "US", + "phone": "", + "verified": false, + "portal_customer_created_at": "2016-11-14T14:48:13-05:00", + "portal_invite_last_sent_at": "2016-11-14T14:48:13-05:00", + "portal_invite_last_accepted_at": null, + "tax_exempt": false, + "vat_number": "012345678" + }, + "product": { + "id": 3792003, + "name": "$10 Basic Plan", + "handle": "basic", + "description": "lorem ipsum", + "accounting_code": "basic", + "price_in_cents": 1000, + "interval": 1, + "interval_unit": "day", + "initial_charge_in_cents": null, + "expiration_interval": null, + "expiration_interval_unit": "never", + "trial_price_in_cents": null, + "trial_interval": null, + "trial_interval_unit": "month", + "initial_charge_after_trial": false, + "return_params": "", + "request_credit_card": false, + "require_credit_card": false, + "created_at": "2016-03-24T13:38:39-04:00", + "updated_at": "2016-11-03T13:03:05-04:00", + "archived_at": null, + "update_return_url": "", + "update_return_params": "", + "product_family": { + "id": 527890, + "name": "Acme Projects", + "handle": "billing-plans", + "accounting_code": null, + "description": "" + }, + "public_signup_pages": [ + { + "id": 281054, + "url": "https://general-goods.chargify.com/subscribe/kqvmfrbgd89q/basic" + }, + { + "id": 281240, + "url": "https://general-goods.chargify.com/subscribe/dkffht5dxfd8/basic" + }, + { + "id": 282694, + "url": "https://general-goods.chargify.com/subscribe/jwffwgdd95s8/basic" + } + ], + "taxable": false, + "version_number": 7, + "product_price_point_name": "Default" + }, + "credit_card": { + "id": 10191713, + "payment_type": "credit_card", + "first_name": "Curtis", + "last_name": "Test", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2026, + "billing_address": "123 Anywhere Street", + "billing_address_2": "", + "billing_city": "Boulder", + "billing_state": null, + "billing_country": "", + "billing_zip": "80302", + "current_vault": "bogus", + "vault_token": "1", + "customer_vault_token": null, + "customer_id": 14714298 + }, + "payment_type": "credit_card", + "referral_code": "w7kjc9", + "next_product_id": null, + "coupon_use_count": 1, + "coupon_uses_allowed": 1, + "stored_credential_transaction_id": 166411599220288, + "on_hold_at": null, + "scheduled_cancellation_at": "2016-11-14T14:48:13-05:00" + } +} +``` + + +# Override Subscription + This API endpoint allows you to set certain subscription fields that are usually managed for you automatically. Some of the fields can be set via the normal Subscriptions Update API, but others can only be set using this endpoint. This endpoint is provided for cases where you need to “align” Chargify data with data that happened in your system, perhaps before you started using Chargify. For example, you may choose to import your historical subscription data, and would like the activation and cancellation dates in Chargify to match your existing historical dates. Chargify does not backfill historical events (i.e. from the Events API), but some static data can be changed via this API. @@ -1354,31 +1366,31 @@ When passing `current_period_starts_at` some validations are made: 2. The value passed must be a valid date/time. We recommend using the iso 8601 format. 3. The value passed must be before the current date/time. -If unpermitted parameters are sent, a 400 HTTP response is sent along with a string giving the reason for the problem. - -```go -OverrideSubscription( - ctx context.Context, - subscriptionId int, +If unpermitted parameters are sent, a 400 HTTP response is sent along with a string giving the reason for the problem. + +```go +OverrideSubscription( + ctx context.Context, + subscriptionId int, body *models.OverrideSubscriptionRequest) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.OverrideSubscriptionRequest`](../../doc/models/override-subscription-request.md) | Body, Optional | Only these fields are available to be set. | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.OverrideSubscriptionRequest`](../../doc/models/override-subscription-request.md) | Body, Optional | Only these fields are available to be set. | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -1410,41 +1422,41 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | - - -# Find Subscription - -Use this endpoint to find a subscription by its reference. - -```go -FindSubscription( - ctx context.Context, +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SingleErrorResponseException`](../../doc/models/single-error-response-exception.md) | + + +# Find Subscription + +Use this endpoint to find a subscription by its reference. + +```go +FindSubscription( + ctx context.Context, reference *string) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `reference` | `*string` | Query, Optional | Subscription reference | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `reference` | `*string` | Query, Optional | Subscription reference | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() apiResponse, err := subscriptionsController.FindSubscription(ctx, nil) @@ -1454,12 +1466,12 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - - -# Purge Subscription - +} +``` + + +# Purge Subscription + For sites in test mode, you may purge individual subscriptions. Provide the subscription ID in the url. To confirm, supply the customer ID in the query string `ack` parameter. You may also delete the customer record and/or payment profiles by passing `cascade` parameters. For example, to delete just the customer record, the query params would be: `?ack={customer_id}&cascade[]=customer` @@ -1468,33 +1480,33 @@ If you need to remove subscriptions from a live site, please contact support to ### Delete customer and payment profile -The query params will be: `?ack={customer_id}&cascade[]=customer&cascade[]=payment_profile` - -```go -PurgeSubscription( - ctx context.Context, - subscriptionId int, - ack int, +The query params will be: `?ack={customer_id}&cascade[]=customer&cascade[]=payment_profile` + +```go +PurgeSubscription( + ctx context.Context, + subscriptionId int, + ack int, cascade []models.SubscriptionPurgeType) ( http.Response, - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `ack` | `int` | Query, Required | id of the customer. | -| `cascade` | [`[]models.SubscriptionPurgeType`](../../doc/models/subscription-purge-type.md) | Query, Optional | Options are "customer" or "payment_profile".
Use in query: `cascade[]=customer&cascade[]=payment_profile`. | - -## Response Type - -`` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `ack` | `int` | Query, Required | id of the customer. | +| `cascade` | [`[]models.SubscriptionPurgeType`](../../doc/models/subscription-purge-type.md) | Query, Optional | Options are "customer" or "payment_profile".
Use in query: `cascade[]=customer&cascade[]=payment_profile`. | + +## Response Type + +`` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 ack := 252Liquid error: Value cannot be null. (Parameter 'key') @@ -1504,37 +1516,37 @@ if err != nil { log.Fatalln(err) } else { fmt.Println(resp.StatusCode) -} -``` - - -# Update Prepaid Subscription Configuration - -Use this endpoint to update a subscription's prepaid configuration. - -```go -UpdatePrepaidSubscriptionConfiguration( - ctx context.Context, - subscriptionId int, +} +``` + + +# Update Prepaid Subscription Configuration + +Use this endpoint to update a subscription's prepaid configuration. + +```go +UpdatePrepaidSubscriptionConfiguration( + ctx context.Context, + subscriptionId int, body *models.UpsertPrepaidConfigurationRequest) ( models.ApiResponse[models.PrepaidConfigurationResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.UpsertPrepaidConfigurationRequest`](../../doc/models/upsert-prepaid-configuration-request.md) | Body, Optional | - | - -## Response Type - -[`models.PrepaidConfigurationResponse`](../../doc/models/prepaid-configuration-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.UpsertPrepaidConfigurationRequest`](../../doc/models/upsert-prepaid-configuration-request.md) | Body, Optional | - | + +## Response Type + +[`models.PrepaidConfigurationResponse`](../../doc/models/prepaid-configuration-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -1556,26 +1568,26 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "prepaid_configuration": { - "id": 55, - "initial_funding_amount_in_cents": 2500, - "auto_replenish": true, - "replenish_to_amount_in_cents": 50000, - "replenish_threshold_amount_in_cents": 10000 - } -} -``` - - -# Preview Subscription - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "prepaid_configuration": { + "id": 55, + "initial_funding_amount_in_cents": 2500, + "auto_replenish": true, + "replenish_to_amount_in_cents": 50000, + "replenish_threshold_amount_in_cents": 10000 + } +} +``` + + +# Preview Subscription + The Chargify API allows you to preview a subscription by POSTing the same JSON or XML as for a subscription creation. The "Next Billing" amount and "Next Billing" date are represented in each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). @@ -1600,29 +1612,29 @@ You can pass shipping and billing addresses and still decide not to calculate ta ## Non-taxable Subscriptions -If you'd like to calculate subscriptions that do not include tax, please feel free to leave off the billing information. - -```go -PreviewSubscription( - ctx context.Context, +If you'd like to calculate subscriptions that do not include tax, please feel free to leave off the billing information. + +```go +PreviewSubscription( + ctx context.Context, body *models.CreateSubscriptionRequest) ( models.ApiResponse[models.SubscriptionPreviewResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionPreviewResponse`](../../doc/models/subscription-preview-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.CreateSubscriptionRequest`](../../doc/models/create-subscription-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionPreviewResponse`](../../doc/models/subscription-preview-response.md) + +## Example Usage + +```go ctx := context.Background() bodySubscription := models.CreateSubscription{ @@ -1640,165 +1652,165 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription_preview": { - "current_billing_manifest": { - "line_items": [ - { - "transaction_type": "charge", - "kind": "baseline", - "amount_in_cents": 5000, - "memo": "Gold Product (08/21/2018 - 09/21/2018)", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "product_id": 1, - "product_handle": "gold-product", - "product_name": "Gold Product", - "period_range_start": "13 Oct 2023", - "period_range_end": "13 Nov 2023" - }, - { - "transaction_type": "charge", - "kind": "component", - "amount_in_cents": 28000, - "memo": "Component name: 14 Unit names", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "component_id": 462149, - "component_handle": "handle", - "component_name": "Component name" - }, - { - "transaction_type": "charge", - "kind": "component", - "amount_in_cents": 2000, - "memo": "Fractional Metered Components: 20.0 Fractional Metereds", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "component_id": 426665, - "component_handle": "handle", - "component_name": "Fractional Metered Components" - }, - { - "transaction_type": "charge", - "kind": "component", - "amount_in_cents": 0, - "memo": "On/Off Component", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "component_id": 426670, - "component_handle": "handle", - "component_name": "On/Off Component" - }, - { - "transaction_type": "adjustment", - "kind": "coupon", - "amount_in_cents": 0, - "memo": "Coupon: 1DOLLAR - You only get $1.00 off", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0 - } - ], - "total_in_cents": 35000, - "total_discount_in_cents": 0, - "total_tax_in_cents": 0, - "subtotal_in_cents": 35000, - "start_date": "2018-08-21T21:25:21Z", - "end_date": "2018-09-21T21:25:21Z", - "period_type": "recurring", - "existing_balance_in_cents": 0 - }, - "next_billing_manifest": { - "line_items": [ - { - "transaction_type": "charge", - "kind": "baseline", - "amount_in_cents": 5000, - "memo": "Gold Product (09/21/2018 - 10/21/2018)", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "product_id": 1, - "product_handle": "gold-product", - "product_name": "Gold Product" - }, - { - "transaction_type": "charge", - "kind": "component", - "amount_in_cents": 28000, - "memo": "Component name: 14 Unit names", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "component_id": 462149, - "component_handle": "handle", - "component_name": "Component name" - }, - { - "transaction_type": "charge", - "kind": "component", - "amount_in_cents": 0, - "memo": "On/Off Component", - "discount_amount_in_cents": 0, - "taxable_amount_in_cents": 0, - "component_id": 426670, - "component_handle": "handle", - "component_name": "On/Off Component" - } - ], - "total_in_cents": 33000, - "total_discount_in_cents": 0, - "total_tax_in_cents": 0, - "subtotal_in_cents": 33000, - "start_date": "2018-09-21T21:25:21Z", - "end_date": "2018-10-21T21:25:21Z", - "period_type": "recurring", - "existing_balance_in_cents": 0 - } - } -} -``` - - -# Apply Coupons to Subscription - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription_preview": { + "current_billing_manifest": { + "line_items": [ + { + "transaction_type": "charge", + "kind": "baseline", + "amount_in_cents": 5000, + "memo": "Gold Product (08/21/2018 - 09/21/2018)", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "product_id": 1, + "product_handle": "gold-product", + "product_name": "Gold Product", + "period_range_start": "13 Oct 2023", + "period_range_end": "13 Nov 2023" + }, + { + "transaction_type": "charge", + "kind": "component", + "amount_in_cents": 28000, + "memo": "Component name: 14 Unit names", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "component_id": 462149, + "component_handle": "handle", + "component_name": "Component name" + }, + { + "transaction_type": "charge", + "kind": "component", + "amount_in_cents": 2000, + "memo": "Fractional Metered Components: 20.0 Fractional Metereds", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "component_id": 426665, + "component_handle": "handle", + "component_name": "Fractional Metered Components" + }, + { + "transaction_type": "charge", + "kind": "component", + "amount_in_cents": 0, + "memo": "On/Off Component", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "component_id": 426670, + "component_handle": "handle", + "component_name": "On/Off Component" + }, + { + "transaction_type": "adjustment", + "kind": "coupon", + "amount_in_cents": 0, + "memo": "Coupon: 1DOLLAR - You only get $1.00 off", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0 + } + ], + "total_in_cents": 35000, + "total_discount_in_cents": 0, + "total_tax_in_cents": 0, + "subtotal_in_cents": 35000, + "start_date": "2018-08-21T21:25:21Z", + "end_date": "2018-09-21T21:25:21Z", + "period_type": "recurring", + "existing_balance_in_cents": 0 + }, + "next_billing_manifest": { + "line_items": [ + { + "transaction_type": "charge", + "kind": "baseline", + "amount_in_cents": 5000, + "memo": "Gold Product (09/21/2018 - 10/21/2018)", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "product_id": 1, + "product_handle": "gold-product", + "product_name": "Gold Product" + }, + { + "transaction_type": "charge", + "kind": "component", + "amount_in_cents": 28000, + "memo": "Component name: 14 Unit names", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "component_id": 462149, + "component_handle": "handle", + "component_name": "Component name" + }, + { + "transaction_type": "charge", + "kind": "component", + "amount_in_cents": 0, + "memo": "On/Off Component", + "discount_amount_in_cents": 0, + "taxable_amount_in_cents": 0, + "component_id": 426670, + "component_handle": "handle", + "component_name": "On/Off Component" + } + ], + "total_in_cents": 33000, + "total_discount_in_cents": 0, + "total_tax_in_cents": 0, + "subtotal_in_cents": 33000, + "start_date": "2018-09-21T21:25:21Z", + "end_date": "2018-10-21T21:25:21Z", + "period_type": "recurring", + "existing_balance_in_cents": 0 + } + } +} +``` + + +# Apply Coupons to Subscription + An existing subscription can accommodate multiple discounts/coupon codes. This is only applicable if each coupon is stackable. For more information on stackable coupons, we recommend reviewing our [coupon documentation.](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#stackable-coupons) ## Query Parameters vs Request Body Parameters Passing in a coupon code as a query parameter will add the code to the subscription, completely replacing all existing coupon codes on the subscription. -For this reason, using this query parameter on this endpoint has been deprecated in favor of using the request body parameters as described below. When passing in request body parameters, the list of coupon codes will simply be added to any existing list of codes on the subscription. - -```go -ApplyCouponsToSubscription( - ctx context.Context, - subscriptionId int, - code *string, +For this reason, using this query parameter on this endpoint has been deprecated in favor of using the request body parameters as described below. When passing in request body parameters, the list of coupon codes will simply be added to any existing list of codes on the subscription. + +```go +ApplyCouponsToSubscription( + ctx context.Context, + subscriptionId int, + code *string, body *models.AddCouponsRequest) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `code` | `*string` | Query, Optional | A code for the coupon that would be applied to a subscription | -| `body` | [`*models.AddCouponsRequest`](../../doc/models/add-coupons-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `code` | `*string` | Query, Optional | A code for the coupon that would be applied to a subscription | +| `body` | [`*models.AddCouponsRequest`](../../doc/models/add-coupons-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -1813,195 +1825,195 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "subscription": { - "id": 21607180, - "state": "active", - "trial_started_at": null, - "trial_ended_at": null, - "activated_at": "2018-04-20T14:20:57-05:00", - "created_at": "2018-04-20T14:20:57-05:00", - "updated_at": "2018-05-11T13:53:44-05:00", - "expires_at": null, - "balance_in_cents": 49000, - "current_period_ends_at": "2018-05-12T11:33:03-05:00", - "next_assessment_at": "2018-05-12T11:33:03-05:00", - "canceled_at": null, - "cancellation_message": null, - "next_product_id": null, - "cancel_at_end_of_period": false, - "payment_collection_method": "remittance", - "snap_day": null, - "cancellation_method": null, - "current_period_started_at": "2018-05-11T11:33:03-05:00", - "previous_state": "active", - "signup_payment_id": 237154761, - "signup_revenue": "0.00", - "delayed_cancel_at": null, - "coupon_code": "COUPONA", - "total_revenue_in_cents": 52762, - "product_price_in_cents": 100000, - "product_version_number": 2, - "payment_type": "credit_card", - "referral_code": "x45nc8", - "coupon_use_count": 0, - "coupon_uses_allowed": 1, - "reason_code": null, - "automatically_resume_at": null, - "coupon_codes": [ - "COUPONA", - "COUPONB" - ], - "customer": { - "id": 21259051, - "first_name": "K", - "last_name": "C", - "organization": "", - "email": "example@chargify.com", - "created_at": "2018-04-20T14:20:57-05:00", - "updated_at": "2018-04-23T15:29:28-05:00", - "reference": null, - "address": "", - "address_2": "", - "city": "", - "state": "", - "zip": "", - "country": "", - "phone": "", - "portal_invite_last_sent_at": "2018-04-20T14:20:59-05:00", - "portal_invite_last_accepted_at": null, - "verified": false, - "portal_customer_created_at": "2018-04-20T14:20:59-05:00", - "cc_emails": "", - "tax_exempt": false - }, - "product": { - "id": 4581816, - "name": "Basic", - "handle": "basic", - "description": "", - "accounting_code": "", - "request_credit_card": true, - "expiration_interval": null, - "expiration_interval_unit": "never", - "created_at": "2017-11-02T15:00:11-05:00", - "updated_at": "2018-04-10T09:02:59-05:00", - "price_in_cents": 100000, - "interval": 1, - "interval_unit": "month", - "initial_charge_in_cents": 100000, - "trial_price_in_cents": 1000, - "trial_interval": 10, - "trial_interval_unit": "month", - "archived_at": null, - "require_credit_card": true, - "return_params": "", - "taxable": false, - "update_return_url": "", - "tax_code": "", - "initial_charge_after_trial": false, - "version_number": 2, - "update_return_params": "", - "product_family": { - "id": 1025627, - "name": "My Product Family", - "description": "", - "handle": "acme-products", - "accounting_code": null - }, - "public_signup_pages": [ - { - "id": 333589, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargifypay.com/subscribe/hbwtd98j3hk2/basic" - }, - { - "id": 335926, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargifypay.com/subscribe/g366zy67c7rm/basic" - }, - { - "id": 345555, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargifypay.com/subscribe/txqyyqk7d8rz/basic" - }, - { - "id": 345556, - "return_url": "", - "return_params": "", - "url": "https://general-goods.chargifypay.com/subscribe/2zss3qpf4249/basic" - } - ] - }, - "credit_card": { - "id": 14839830, - "first_name": "John", - "last_name": "Doe", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2028, - "customer_id": 21259051, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": null, - "billing_city": null, - "billing_state": null, - "billing_zip": "99999", - "billing_country": null, - "customer_vault_token": null, - "billing_address_2": null, - "payment_type": "credit_card" - } - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionAddCouponErrorException`](../../doc/models/subscription-add-coupon-error-exception.md) | - - -# Remove Coupon From Subscription - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "subscription": { + "id": 21607180, + "state": "active", + "trial_started_at": null, + "trial_ended_at": null, + "activated_at": "2018-04-20T14:20:57-05:00", + "created_at": "2018-04-20T14:20:57-05:00", + "updated_at": "2018-05-11T13:53:44-05:00", + "expires_at": null, + "balance_in_cents": 49000, + "current_period_ends_at": "2018-05-12T11:33:03-05:00", + "next_assessment_at": "2018-05-12T11:33:03-05:00", + "canceled_at": null, + "cancellation_message": null, + "next_product_id": null, + "cancel_at_end_of_period": false, + "payment_collection_method": "remittance", + "snap_day": null, + "cancellation_method": null, + "current_period_started_at": "2018-05-11T11:33:03-05:00", + "previous_state": "active", + "signup_payment_id": 237154761, + "signup_revenue": "0.00", + "delayed_cancel_at": null, + "coupon_code": "COUPONA", + "total_revenue_in_cents": 52762, + "product_price_in_cents": 100000, + "product_version_number": 2, + "payment_type": "credit_card", + "referral_code": "x45nc8", + "coupon_use_count": 0, + "coupon_uses_allowed": 1, + "reason_code": null, + "automatically_resume_at": null, + "coupon_codes": [ + "COUPONA", + "COUPONB" + ], + "customer": { + "id": 21259051, + "first_name": "K", + "last_name": "C", + "organization": "", + "email": "example@chargify.com", + "created_at": "2018-04-20T14:20:57-05:00", + "updated_at": "2018-04-23T15:29:28-05:00", + "reference": null, + "address": "", + "address_2": "", + "city": "", + "state": "", + "zip": "", + "country": "", + "phone": "", + "portal_invite_last_sent_at": "2018-04-20T14:20:59-05:00", + "portal_invite_last_accepted_at": null, + "verified": false, + "portal_customer_created_at": "2018-04-20T14:20:59-05:00", + "cc_emails": "", + "tax_exempt": false + }, + "product": { + "id": 4581816, + "name": "Basic", + "handle": "basic", + "description": "", + "accounting_code": "", + "request_credit_card": true, + "expiration_interval": null, + "expiration_interval_unit": "never", + "created_at": "2017-11-02T15:00:11-05:00", + "updated_at": "2018-04-10T09:02:59-05:00", + "price_in_cents": 100000, + "interval": 1, + "interval_unit": "month", + "initial_charge_in_cents": 100000, + "trial_price_in_cents": 1000, + "trial_interval": 10, + "trial_interval_unit": "month", + "archived_at": null, + "require_credit_card": true, + "return_params": "", + "taxable": false, + "update_return_url": "", + "tax_code": "", + "initial_charge_after_trial": false, + "version_number": 2, + "update_return_params": "", + "product_family": { + "id": 1025627, + "name": "My Product Family", + "description": "", + "handle": "acme-products", + "accounting_code": null + }, + "public_signup_pages": [ + { + "id": 333589, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargifypay.com/subscribe/hbwtd98j3hk2/basic" + }, + { + "id": 335926, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargifypay.com/subscribe/g366zy67c7rm/basic" + }, + { + "id": 345555, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargifypay.com/subscribe/txqyyqk7d8rz/basic" + }, + { + "id": 345556, + "return_url": "", + "return_params": "", + "url": "https://general-goods.chargifypay.com/subscribe/2zss3qpf4249/basic" + } + ] + }, + "credit_card": { + "id": 14839830, + "first_name": "John", + "last_name": "Doe", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2028, + "customer_id": 21259051, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": null, + "billing_city": null, + "billing_state": null, + "billing_zip": "99999", + "billing_country": null, + "customer_vault_token": null, + "billing_address_2": null, + "payment_type": "credit_card" + } + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionAddCouponErrorException`](../../doc/models/subscription-add-coupon-error-exception.md) | + + +# Remove Coupon From Subscription + Use this endpoint to remove a coupon from an existing subscription. -For more information on the expected behaviour of removing a coupon from a subscription, please see our documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407896488987#removing-a-coupon) - -```go -RemoveCouponFromSubscription( - ctx context.Context, - subscriptionId int, +For more information on the expected behaviour of removing a coupon from a subscription, please see our documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407896488987#removing-a-coupon) + +```go +RemoveCouponFromSubscription( + ctx context.Context, + subscriptionId int, couponCode *string) ( models.ApiResponse[string], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `couponCode` | `*string` | Query, Optional | The coupon code | - -## Response Type - -`string` - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `couponCode` | `*string` | Query, Optional | The coupon code | + +## Response Type + +`string` + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -2012,24 +2024,24 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response - -``` -"Coupon successfully removed" -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionRemoveCouponErrorsException`](../../doc/models/subscription-remove-coupon-errors-exception.md) | - - -# Activate Subscription - +} +``` + +## Example Response + +``` +"Coupon successfully removed" +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`SubscriptionRemoveCouponErrorsException`](../../doc/models/subscription-remove-coupon-errors-exception.md) | + + +# Activate Subscription + Chargify offers the ability to activate awaiting signup and trialing subscriptions. This feature is only available on the Relationship Invoicing architecture. Subscriptions in a group may not be activated immediately. For details on how the activation works, and how to activate subscriptions through the application, see [activation](#). @@ -2072,31 +2084,31 @@ The default activation failure behavior can be configured per activation attempt ### Activate Trialing subscription You can read more about the behavior of trialing subscriptions [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404494617357#trialing-subscriptions-0-0). -When the `revert_on_failure` parameter is set to `true`, the subscription's state will remain as Trialing, we will void the invoice from activation and return any prepayments and credits applied to the invoice back to the subscription. - -```go -ActivateSubscription( - ctx context.Context, - subscriptionId int, +When the `revert_on_failure` parameter is set to `true`, the subscription's state will remain as Trialing, we will void the invoice from activation and return any prepayments and credits applied to the invoice back to the subscription. + +```go +ActivateSubscription( + ctx context.Context, + subscriptionId int, body *models.ActivateSubscriptionRequest) ( models.ApiResponse[models.SubscriptionResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | -| `body` | [`*models.ActivateSubscriptionRequest`](../../doc/models/activate-subscription-request.md) | Body, Optional | - | - -## Response Type - -[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `subscriptionId` | `int` | Template, Required | The Chargify id of the subscription | +| `body` | [`*models.ActivateSubscriptionRequest`](../../doc/models/activate-subscription-request.md) | Body, Optional | - | + +## Response Type + +[`models.SubscriptionResponse`](../../doc/models/subscription-response.md) + +## Example Usage + +```go ctx := context.Background() subscriptionId := 222 @@ -2107,12 +2119,12 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 400 | Bad Request | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 400 | Bad Request | [`ErrorArrayMapResponseException`](../../doc/models/error-array-map-response-exception.md) | + diff --git a/doc/controllers/webhooks.md b/doc/controllers/webhooks.md index c63258ef..ac38f5ee 100644 --- a/doc/controllers/webhooks.md +++ b/doc/controllers/webhooks.md @@ -1,25 +1,25 @@ -# Webhooks - -```go -webhooksController := client.WebhooksController() -``` - -## Class Name - -`WebhooksController` - -## Methods - +# Webhooks + +```go +webhooksController := client.WebhooksController() +``` + +## Class Name + +`WebhooksController` + +## Methods + * [List Webhooks](../../doc/controllers/webhooks.md#list-webhooks) * [Enable Webhooks](../../doc/controllers/webhooks.md#enable-webhooks) * [Replay Webhooks](../../doc/controllers/webhooks.md#replay-webhooks) * [Create Endpoint](../../doc/controllers/webhooks.md#create-endpoint) * [List Endpoints](../../doc/controllers/webhooks.md#list-endpoints) -* [Update Endpoint](../../doc/controllers/webhooks.md#update-endpoint) - - -# List Webhooks - +* [Update Endpoint](../../doc/controllers/webhooks.md#update-endpoint) + + +# List Webhooks + ## Webhooks Intro The Webhooks API allows you to view a list of all webhooks and to selectively resend individual or groups of webhooks. Webhooks will be sent on endpoints specified by you. Endpoints can be added via API or Web UI. There is also an option to enable / disable webhooks via API request. @@ -33,113 +33,117 @@ We recommend that you review Chargify's webhook documentation located in our hel ## List Webhooks for a Site -This method allows you to fetch data about webhooks. You can pass query parameters if you want to filter webhooks. - -```go -ListWebhooks( - ctx context.Context,input ListWebhooksInput) ( +This method allows you to fetch data about webhooks. You can pass query parameters if you want to filter webhooks. + +```go +ListWebhooks( + ctx context.Context, + input ListWebhooksInput) ( models.ApiResponse[[]models.WebhookResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `status` | [`*models.WebhookStatus`](../../doc/models/webhook-status.md) | Query, Optional | Webhooks with matching status would be returned. | -| `sinceDate` | `*string` | Query, Optional | Format YYYY-MM-DD. Returns Webhooks with the created_at date greater than or equal to the one specified. | -| `untilDate` | `*string` | Query, Optional | Format YYYY-MM-DD. Returns Webhooks with the created_at date less than or equal to the one specified. | -| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | -| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | -| `order` | [`*models.WebhookOrder`](../../doc/models/webhook-order.md) | Query, Optional | The order in which the Webhooks are returned. | -| `subscription` | `*int` | Query, Optional | The Chargify id of a subscription you'd like to filter for | - -## Response Type - -[`[]models.WebhookResponse`](../../doc/models/webhook-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `status` | [`*models.WebhookStatus`](../../doc/models/webhook-status.md) | Query, Optional | Webhooks with matching status would be returned. | +| `sinceDate` | `*string` | Query, Optional | Format YYYY-MM-DD. Returns Webhooks with the created_at date greater than or equal to the one specified. | +| `untilDate` | `*string` | Query, Optional | Format YYYY-MM-DD. Returns Webhooks with the created_at date less than or equal to the one specified. | +| `page` | `*int` | Query, Optional | Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned.
Use in query `page=1`. | +| `perPage` | `*int` | Query, Optional | This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200.
Use in query `per_page=200`. | +| `order` | [`*models.WebhookOrder`](../../doc/models/webhook-order.md) | Query, Optional | The order in which the Webhooks are returned. | +| `subscription` | `*int` | Query, Optional | The Chargify id of a subscription you'd like to filter for | + +## Response Type + +[`[]models.WebhookResponse`](../../doc/models/webhook-response.md) + +## Example Usage + +```go ctx := context.Background() -page := 2 -perPage := 50 -apiResponse, err := webhooksController.ListWebhooks(ctx, nil, nil, nil, &page, &perPage, nil, nil) +collectedInput := advancedbilling.ListWebhooksInput{ + Page: models.ToPointer(2), + PerPage: models.ToPointer(50), +} + +apiResponse, err := webhooksController.ListWebhooks(ctx, collectedInput) if err != nil { log.Fatalln(err) } else { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "webhook": { - "event": "statement_settled", - "id": 141765032, - "created_at": "2016-11-08T16:22:26-05:00", - "last_error": "404 Resource Not Found (retry 5 of 5)", - "last_error_at": "2016-11-08T16:43:54-05:00", - "accepted_at": null, - "last_sent_at": "2016-11-08T16:43:54-05:00", - "last_sent_url": "http://requestb.in/11u45x71", - "successful": false, - "body": "id=141765032&event=statement_settled&payload[site][id]=31615&payload[site][subdomain]=general-goods&payload[subscription][id]=15100141&payload[subscription][state]=active&payload[subscription][balance_in_cents]=0&payload[customer][id]=14585695&payload[customer][first_name]=Pookie&payload[customer][last_name]=Test&payload[customer][reference]=&payload[customer][organization]=&payload[customer][address]=&payload[customer][address_2]=&payload[customer][city]=&payload[customer][state]=&payload[customer][zip]=&payload[customer][country]=&payload[customer][email]=pookie999%40example.com&payload[customer][phone]=&payload[statement][closed_at]=2016-11-08%2016%3A22%3A20%20-0500&payload[statement][created_at]=2016-11-08%2016%3A22%3A18%20-0500&payload[statement][id]=80168049&payload[statement][opened_at]=2016-11-07%2016%3A22%3A15%20-0500&payload[statement][settled_at]=2016-11-08%2016%3A22%3A20%20-0500&payload[statement][subscription_id]=15100141&payload[statement][updated_at]=2016-11-08%2016%3A22%3A20%20-0500&payload[statement][starting_balance_in_cents]=0&payload[statement][ending_balance_in_cents]=0&payload[statement][total_in_cents]=6400&payload[statement][memo]=We%20thank%20you%20for%20your%20continued%20business!&payload[statement][events][0][id]=346956565&payload[statement][events][0][key]=renewal_success&payload[statement][events][0][message]=Successful%20renewal%20for%20Pookie%20Test's%20subscription%20to%20%2410%20Basic%20Plan&payload[statement][events][1][id]=346956579&payload[statement][events][1][key]=payment_success&payload[statement][events][1][message]=Successful%20payment%20of%20%2464.00%20for%20Pookie%20Test's%20subscription%20to%20%2410%20Basic%20Plan&payload[statement][events][2][id]=347299359&payload[statement][events][2][key]=renewal_success&payload[statement][events][2][message]=Successful%20renewal%20for%20Pookie%20Test's%20subscription%20to%20%2410%20Basic%20Plan&payload[statement][transactions][0][id]=161537343&payload[statement][transactions][0][subscription_id]=15100141&payload[statement][transactions][0][type]=Charge&payload[statement][transactions][0][kind]=baseline&payload[statement][transactions][0][transaction_type]=charge&payload[statement][transactions][0][success]=true&payload[statement][transactions][0][amount_in_cents]=1000&payload[statement][transactions][0][memo]=%2410%20Basic%20Plan%20(11%2F08%2F2016%20-%2011%2F09%2F2016)&payload[statement][transactions][0][created_at]=2016-11-08%2016%3A22%3A18%20-0500&payload[statement][transactions][0][starting_balance_in_cents]=0&payload[statement][transactions][0][ending_balance_in_cents]=1000&payload[statement][transactions][0][gateway_used]=&payload[statement][transactions][0][gateway_transaction_id]=&payload[statement][transactions][0][gateway_order_id]=&payload[statement][transactions][0][payment_id]=161537369&payload[statement][transactions][0][product_id]=3792003&payload[statement][transactions][0][tax_id]=&payload[statement][transactions][0][component_id]=&payload[statement][transactions][0][statement_id]=80168049&payload[statement][transactions][0][customer_id]=14585695&payload[statement][transactions][0][original_amount_in_cents]=&payload[statement][transactions][0][discount_amount_in_cents]=&payload[statement][transactions][0][taxable_amount_in_cents]=&payload[statement][transactions][1][id]=161537344&payload[statement][transactions][1][subscription_id]=15100141&payload[statement][transactions][1][type]=Charge&payload[statement][transactions][1][kind]=quantity_based_component&payload[statement][transactions][1][transaction_type]=charge&payload[statement][transactions][1][success]=true&payload[statement][transactions][1][amount_in_cents]=5400&payload[statement][transactions][1][memo]=Timesheet%20Users%3A%2018%20Timesheet%20Users&payload[statement][transactions][1][created_at]=2016-11-08%2016%3A22%3A18%20-0500&payload[statement][transactions][1][starting_balance_in_cents]=1000&payload[statement][transactions][1][ending_balance_in_cents]=6400&payload[statement][transactions][1][gateway_used]=&payload[statement][transactions][1][gateway_transaction_id]=&payload[statement][transactions][1][gateway_order_id]=&payload[statement][transactions][1][payment_id]=161537369&payload[statement][transactions][1][product_id]=3792003&payload[statement][transactions][1][tax_id]=&payload[statement][transactions][1][component_id]=277221&payload[statement][transactions][1][statement_id]=80168049&payload[statement][transactions][1][customer_id]=14585695&payload[statement][transactions][1][original_amount_in_cents]=&payload[statement][transactions][1][discount_amount_in_cents]=&payload[statement][transactions][1][taxable_amount_in_cents]=&payload[statement][transactions][2][id]=161537369&payload[statement][transactions][2][subscription_id]=15100141&payload[statement][transactions][2][type]=Payment&payload[statement][transactions][2][kind]=&payload[statement][transactions][2][transaction_type]=payment&payload[statement][transactions][2][success]=true&payload[statement][transactions][2][amount_in_cents]=6400&payload[statement][transactions][2][memo]=Pookie%20Test%20-%20%2410%20Basic%20Plan%3A%20Renewal%20payment&payload[statement][transactions][2][created_at]=2016-11-08%2016%3A22%3A20%20-0500&payload[statement][transactions][2][starting_balance_in_cents]=6400&payload[statement][transactions][2][ending_balance_in_cents]=0&payload[statement][transactions][2][gateway_used]=bogus&payload[statement][transactions][2][gateway_transaction_id]=53433&payload[statement][transactions][2][gateway_order_id]=&payload[statement][transactions][2][payment_id]=&payload[statement][transactions][2][product_id]=3792003&payload[statement][transactions][2][tax_id]=&payload[statement][transactions][2][component_id]=&payload[statement][transactions][2][statement_id]=80168049&payload[statement][transactions][2][customer_id]=14585695&payload[statement][transactions][2][card_number]=XXXX-XXXX-XXXX-1&payload[statement][transactions][2][card_expiration]=10%2F2020&payload[statement][transactions][2][card_type]=bogus&payload[statement][transactions][2][refunded_amount_in_cents]=0&payload[product][id]=3792003&payload[product][name]=%2410%20Basic%20Plan&payload[product_family][id]=527890&payload[product_family][name]=Acme%20Projects&payload[payment_profile][id]=10102821&payload[payment_profile][first_name]=Pookie&payload[payment_profile][last_name]=Test&payload[payment_profile][billing_address]=&payload[payment_profile][billing_address_2]=&payload[payment_profile][billing_city]=&payload[payment_profile][billing_country]=&payload[payment_profile][billing_state]=&payload[payment_profile][billing_zip]=&payload[event_id]=347299384", - "signature": "7c606ec4628ce75ec46e284097ce163a", - "signature_hmac_sha_256": "40f25e83dd324508bb2149e3e525821922fb210535ebfbfa81e7ab951996b41d" - } - }, - { - "webhook": { - "event": "payment_success", - "id": 141765008, - "created_at": "2016-11-08T16:22:25-05:00", - "last_error": "404 Resource Not Found (retry 5 of 5)", - "last_error_at": "2016-11-08T16:43:54-05:00", - "accepted_at": null, - "last_sent_at": "2016-11-08T16:43:54-05:00", - "last_sent_url": "http://requestb.in/11u45x71", - "successful": false, - "body": "id=141765008&event=payment_success&payload[site][id]=31615&payload[site][subdomain]=general-goods&payload[subscription][id]=15100141&payload[subscription][state]=active&payload[subscription][trial_started_at]=&payload[subscription][trial_ended_at]=&payload[subscription][activated_at]=2016-11-04%2017%3A06%3A43%20-0400&payload[subscription][created_at]=2016-11-04%2017%3A06%3A42%20-0400&payload[subscription][updated_at]=2016-11-08%2016%3A22%3A22%20-0500&payload[subscription][expires_at]=&payload[subscription][balance_in_cents]=0&payload[subscription][current_period_ends_at]=2016-11-09%2016%3A06%3A42%20-0500&payload[subscription][next_assessment_at]=2016-11-09%2016%3A06%3A42%20-0500&payload[subscription][canceled_at]=&payload[subscription][cancellation_message]=&payload[subscription][next_product_id]=&payload[subscription][cancel_at_end_of_period]=false&payload[subscription][payment_collection_method]=automatic&payload[subscription][snap_day]=&payload[subscription][cancellation_method]=&payload[subscription][current_period_started_at]=2016-11-08%2016%3A06%3A42%20-0500&payload[subscription][previous_state]=active&payload[subscription][signup_payment_id]=161034048&payload[subscription][signup_revenue]=64.00&payload[subscription][delayed_cancel_at]=&payload[subscription][coupon_code]=&payload[subscription][total_revenue_in_cents]=32000&payload[subscription][product_price_in_cents]=1000&payload[subscription][product_version_number]=7&payload[subscription][payment_type]=credit_card&payload[subscription][referral_code]=pggn84&payload[subscription][coupon_use_count]=&payload[subscription][coupon_uses_allowed]=&payload[subscription][customer][id]=14585695&payload[subscription][customer][first_name]=Test&payload[subscription][customer][last_name]=Test&payload[subscription][customer][organization]=&payload[subscription][customer][email]=pookie999%40example.com&payload[subscription][customer][created_at]=2016-11-04%2017%3A06%3A42%20-0400&payload[subscription][customer][updated_at]=2016-11-04%2017%3A06%3A45%20-0400&payload[subscription][customer][reference]=&payload[subscription][customer][address]=&payload[subscription][customer][address_2]=&payload[subscription][customer][city]=&payload[subscription][customer][state]=&payload[subscription][customer][zip]=&payload[subscription][customer][country]=&payload[subscription][customer][phone]=&payload[subscription][customer][portal_invite_last_sent_at]=2016-11-04%2017%3A06%3A45%20-0400&payload[subscription][customer][portal_invite_last_accepted_at]=&payload[subscription][customer][verified]=false&payload[subscription][customer][portal_customer_created_at]=2016-11-04%2017%3A06%3A45%20-0400&payload[subscription][customer][cc_emails]=&payload[subscription][product][id]=3792003&payload[subscription][product][name]=%2410%20Basic%20Plan&payload[subscription][product][handle]=basic&payload[subscription][product][description]=lorem%20ipsum&payload[subscription][product][accounting_code]=basic&payload[subscription][product][request_credit_card]=false&payload[subscription][product][expiration_interval]=&payload[subscription][product][expiration_interval_unit]=never&payload[subscription][product][created_at]=2016-03-24%2013%3A38%3A39%20-0400&payload[subscription][product][updated_at]=2016-11-03%2013%3A03%3A05%20-0400&payload[subscription][product][price_in_cents]=1000&payload[subscription][product][interval]=1&payload[subscription][product][interval_unit]=day&payload[subscription][product][initial_charge_in_cents]=&payload[subscription][product][trial_price_in_cents]=&payload[subscription][product][trial_interval]=&payload[subscription][product][trial_interval_unit]=month&payload[subscription][product][archived_at]=&payload[subscription][product][require_credit_card]=false&payload[subscription][product][return_params]=&payload[subscription][product][taxable]=false&payload[subscription][product][update_return_url]=&payload[subscription][product][initial_charge_after_trial]=false&payload[subscription][product][version_number]=7&payload[subscription][product][update_return_params]=&payload[subscription][product][product_family][id]=527890&payload[subscription][product][product_family][name]=Acme%20Projects&payload[subscription][product][product_family][description]=&payload[subscription][product][product_family][handle]=billing-plans&payload[subscription][product][product_family][accounting_code]=&payload[subscription][product][public_signup_pages][id]=281054&payload[subscription][product][public_signup_pages][return_url]=http%3A%2F%2Fwww.example.com%3Fsuccessfulsignup&payload[subscription][product][public_signup_pages][return_params]=&payload[subscription][product][public_signup_pages][url]=https%3A%2F%2Fgeneral-goods.chargify.com%2Fsubscribe%2Fkqvmfrbgd89q%2Fbasic&payload[subscription][product][public_signup_pages][id]=281240&payload[subscription][product][public_signup_pages][return_url]=&payload[subscription][product][public_signup_pages][return_params]=&payload[subscription][product][public_signup_pages][url]=https%3A%2F%2Fgeneral-goods.chargify.com%2Fsubscribe%2Fdkffht5dxfd8%2Fbasic&payload[subscription][product][public_signup_pages][id]=282694&payload[subscription][product][public_signup_pages][return_url]=&payload[subscription][product][public_signup_pages][return_params]=&payload[subscription][product][public_signup_pages][url]=https%3A%2F%2Fgeneral-goods.chargify.com%2Fsubscribe%2Fjwffwgdd95s8%2Fbasic&payload[subscription][credit_card][id]=10102821&payload[subscription][credit_card][first_name]=Pookie&payload[subscription][credit_card][last_name]=Test&payload[subscription][credit_card][masked_card_number]=XXXX-XXXX-XXXX-1&payload[subscription][credit_card][card_type]=bogus&payload[subscription][credit_card][expiration_month]=10&payload[subscription][credit_card][expiration_year]=2020&payload[subscription][credit_card][customer_id]=14585695&payload[subscription][credit_card][current_vault]=bogus&payload[subscription][credit_card][vault_token]=1&payload[subscription][credit_card][billing_address]=&payload[subscription][credit_card][billing_city]=&payload[subscription][credit_card][billing_state]=&payload[subscription][credit_card][billing_zip]=&payload[subscription][credit_card][billing_country]=&payload[subscription][credit_card][customer_vault_token]=&payload[subscription][credit_card][billing_address_2]=&payload[subscription][credit_card][payment_type]=credit_card&payload[subscription][credit_card][site_gateway_setting_id]=&payload[subscription][credit_card][gateway_handle]=&payload[transaction][id]=161537369&payload[transaction][subscription_id]=15100141&payload[transaction][type]=Payment&payload[transaction][kind]=&payload[transaction][transaction_type]=payment&payload[transaction][success]=true&payload[transaction][amount_in_cents]=6400&payload[transaction][memo]=Pookie%20Test%20-%20%2410%20Basic%20Plan%3A%20Renewal%20payment&payload[transaction][created_at]=2016-11-08%2016%3A22%3A20%20-0500&payload[transaction][starting_balance_in_cents]=6400&payload[transaction][ending_balance_in_cents]=0&payload[transaction][gateway_used]=bogus&payload[transaction][gateway_transaction_id]=53433&payload[transaction][gateway_response_code]=&payload[transaction][gateway_order_id]=&payload[transaction][payment_id]=&payload[transaction][product_id]=3792003&payload[transaction][tax_id]=&payload[transaction][component_id]=&payload[transaction][statement_id]=80168049&payload[transaction][customer_id]=14585695&payload[transaction][card_number]=XXXX-XXXX-XXXX-1&payload[transaction][card_expiration]=10%2F2020&payload[transaction][card_type]=bogus&payload[transaction][refunded_amount_in_cents]=0&payload[transaction][invoice_id]=&payload[event_id]=347299364", - "signature": "fbcf2f6be579f9658cff90c4373e0ca2", - "signature_hmac_sha_256": "db96654f5456c5460062feb944ac8bb1418f9d181ae04a8ed982fe9ffdca8de1" - } - } -] -``` - - -# Enable Webhooks - -This method allows you to enable webhooks via API for your site - -```go -EnableWebhooks( - ctx context.Context, +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "webhook": { + "event": "statement_settled", + "id": 141765032, + "created_at": "2016-11-08T16:22:26-05:00", + "last_error": "404 Resource Not Found (retry 5 of 5)", + "last_error_at": "2016-11-08T16:43:54-05:00", + "accepted_at": null, + "last_sent_at": "2016-11-08T16:43:54-05:00", + "last_sent_url": "http://requestb.in/11u45x71", + "successful": false, + "body": "id=141765032&event=statement_settled&payload[site][id]=31615&payload[site][subdomain]=general-goods&payload[subscription][id]=15100141&payload[subscription][state]=active&payload[subscription][balance_in_cents]=0&payload[customer][id]=14585695&payload[customer][first_name]=Pookie&payload[customer][last_name]=Test&payload[customer][reference]=&payload[customer][organization]=&payload[customer][address]=&payload[customer][address_2]=&payload[customer][city]=&payload[customer][state]=&payload[customer][zip]=&payload[customer][country]=&payload[customer][email]=pookie999%40example.com&payload[customer][phone]=&payload[statement][closed_at]=2016-11-08%2016%3A22%3A20%20-0500&payload[statement][created_at]=2016-11-08%2016%3A22%3A18%20-0500&payload[statement][id]=80168049&payload[statement][opened_at]=2016-11-07%2016%3A22%3A15%20-0500&payload[statement][settled_at]=2016-11-08%2016%3A22%3A20%20-0500&payload[statement][subscription_id]=15100141&payload[statement][updated_at]=2016-11-08%2016%3A22%3A20%20-0500&payload[statement][starting_balance_in_cents]=0&payload[statement][ending_balance_in_cents]=0&payload[statement][total_in_cents]=6400&payload[statement][memo]=We%20thank%20you%20for%20your%20continued%20business!&payload[statement][events][0][id]=346956565&payload[statement][events][0][key]=renewal_success&payload[statement][events][0][message]=Successful%20renewal%20for%20Pookie%20Test's%20subscription%20to%20%2410%20Basic%20Plan&payload[statement][events][1][id]=346956579&payload[statement][events][1][key]=payment_success&payload[statement][events][1][message]=Successful%20payment%20of%20%2464.00%20for%20Pookie%20Test's%20subscription%20to%20%2410%20Basic%20Plan&payload[statement][events][2][id]=347299359&payload[statement][events][2][key]=renewal_success&payload[statement][events][2][message]=Successful%20renewal%20for%20Pookie%20Test's%20subscription%20to%20%2410%20Basic%20Plan&payload[statement][transactions][0][id]=161537343&payload[statement][transactions][0][subscription_id]=15100141&payload[statement][transactions][0][type]=Charge&payload[statement][transactions][0][kind]=baseline&payload[statement][transactions][0][transaction_type]=charge&payload[statement][transactions][0][success]=true&payload[statement][transactions][0][amount_in_cents]=1000&payload[statement][transactions][0][memo]=%2410%20Basic%20Plan%20(11%2F08%2F2016%20-%2011%2F09%2F2016)&payload[statement][transactions][0][created_at]=2016-11-08%2016%3A22%3A18%20-0500&payload[statement][transactions][0][starting_balance_in_cents]=0&payload[statement][transactions][0][ending_balance_in_cents]=1000&payload[statement][transactions][0][gateway_used]=&payload[statement][transactions][0][gateway_transaction_id]=&payload[statement][transactions][0][gateway_order_id]=&payload[statement][transactions][0][payment_id]=161537369&payload[statement][transactions][0][product_id]=3792003&payload[statement][transactions][0][tax_id]=&payload[statement][transactions][0][component_id]=&payload[statement][transactions][0][statement_id]=80168049&payload[statement][transactions][0][customer_id]=14585695&payload[statement][transactions][0][original_amount_in_cents]=&payload[statement][transactions][0][discount_amount_in_cents]=&payload[statement][transactions][0][taxable_amount_in_cents]=&payload[statement][transactions][1][id]=161537344&payload[statement][transactions][1][subscription_id]=15100141&payload[statement][transactions][1][type]=Charge&payload[statement][transactions][1][kind]=quantity_based_component&payload[statement][transactions][1][transaction_type]=charge&payload[statement][transactions][1][success]=true&payload[statement][transactions][1][amount_in_cents]=5400&payload[statement][transactions][1][memo]=Timesheet%20Users%3A%2018%20Timesheet%20Users&payload[statement][transactions][1][created_at]=2016-11-08%2016%3A22%3A18%20-0500&payload[statement][transactions][1][starting_balance_in_cents]=1000&payload[statement][transactions][1][ending_balance_in_cents]=6400&payload[statement][transactions][1][gateway_used]=&payload[statement][transactions][1][gateway_transaction_id]=&payload[statement][transactions][1][gateway_order_id]=&payload[statement][transactions][1][payment_id]=161537369&payload[statement][transactions][1][product_id]=3792003&payload[statement][transactions][1][tax_id]=&payload[statement][transactions][1][component_id]=277221&payload[statement][transactions][1][statement_id]=80168049&payload[statement][transactions][1][customer_id]=14585695&payload[statement][transactions][1][original_amount_in_cents]=&payload[statement][transactions][1][discount_amount_in_cents]=&payload[statement][transactions][1][taxable_amount_in_cents]=&payload[statement][transactions][2][id]=161537369&payload[statement][transactions][2][subscription_id]=15100141&payload[statement][transactions][2][type]=Payment&payload[statement][transactions][2][kind]=&payload[statement][transactions][2][transaction_type]=payment&payload[statement][transactions][2][success]=true&payload[statement][transactions][2][amount_in_cents]=6400&payload[statement][transactions][2][memo]=Pookie%20Test%20-%20%2410%20Basic%20Plan%3A%20Renewal%20payment&payload[statement][transactions][2][created_at]=2016-11-08%2016%3A22%3A20%20-0500&payload[statement][transactions][2][starting_balance_in_cents]=6400&payload[statement][transactions][2][ending_balance_in_cents]=0&payload[statement][transactions][2][gateway_used]=bogus&payload[statement][transactions][2][gateway_transaction_id]=53433&payload[statement][transactions][2][gateway_order_id]=&payload[statement][transactions][2][payment_id]=&payload[statement][transactions][2][product_id]=3792003&payload[statement][transactions][2][tax_id]=&payload[statement][transactions][2][component_id]=&payload[statement][transactions][2][statement_id]=80168049&payload[statement][transactions][2][customer_id]=14585695&payload[statement][transactions][2][card_number]=XXXX-XXXX-XXXX-1&payload[statement][transactions][2][card_expiration]=10%2F2020&payload[statement][transactions][2][card_type]=bogus&payload[statement][transactions][2][refunded_amount_in_cents]=0&payload[product][id]=3792003&payload[product][name]=%2410%20Basic%20Plan&payload[product_family][id]=527890&payload[product_family][name]=Acme%20Projects&payload[payment_profile][id]=10102821&payload[payment_profile][first_name]=Pookie&payload[payment_profile][last_name]=Test&payload[payment_profile][billing_address]=&payload[payment_profile][billing_address_2]=&payload[payment_profile][billing_city]=&payload[payment_profile][billing_country]=&payload[payment_profile][billing_state]=&payload[payment_profile][billing_zip]=&payload[event_id]=347299384", + "signature": "7c606ec4628ce75ec46e284097ce163a", + "signature_hmac_sha_256": "40f25e83dd324508bb2149e3e525821922fb210535ebfbfa81e7ab951996b41d" + } + }, + { + "webhook": { + "event": "payment_success", + "id": 141765008, + "created_at": "2016-11-08T16:22:25-05:00", + "last_error": "404 Resource Not Found (retry 5 of 5)", + "last_error_at": "2016-11-08T16:43:54-05:00", + "accepted_at": null, + "last_sent_at": "2016-11-08T16:43:54-05:00", + "last_sent_url": "http://requestb.in/11u45x71", + "successful": false, + "body": "id=141765008&event=payment_success&payload[site][id]=31615&payload[site][subdomain]=general-goods&payload[subscription][id]=15100141&payload[subscription][state]=active&payload[subscription][trial_started_at]=&payload[subscription][trial_ended_at]=&payload[subscription][activated_at]=2016-11-04%2017%3A06%3A43%20-0400&payload[subscription][created_at]=2016-11-04%2017%3A06%3A42%20-0400&payload[subscription][updated_at]=2016-11-08%2016%3A22%3A22%20-0500&payload[subscription][expires_at]=&payload[subscription][balance_in_cents]=0&payload[subscription][current_period_ends_at]=2016-11-09%2016%3A06%3A42%20-0500&payload[subscription][next_assessment_at]=2016-11-09%2016%3A06%3A42%20-0500&payload[subscription][canceled_at]=&payload[subscription][cancellation_message]=&payload[subscription][next_product_id]=&payload[subscription][cancel_at_end_of_period]=false&payload[subscription][payment_collection_method]=automatic&payload[subscription][snap_day]=&payload[subscription][cancellation_method]=&payload[subscription][current_period_started_at]=2016-11-08%2016%3A06%3A42%20-0500&payload[subscription][previous_state]=active&payload[subscription][signup_payment_id]=161034048&payload[subscription][signup_revenue]=64.00&payload[subscription][delayed_cancel_at]=&payload[subscription][coupon_code]=&payload[subscription][total_revenue_in_cents]=32000&payload[subscription][product_price_in_cents]=1000&payload[subscription][product_version_number]=7&payload[subscription][payment_type]=credit_card&payload[subscription][referral_code]=pggn84&payload[subscription][coupon_use_count]=&payload[subscription][coupon_uses_allowed]=&payload[subscription][customer][id]=14585695&payload[subscription][customer][first_name]=Test&payload[subscription][customer][last_name]=Test&payload[subscription][customer][organization]=&payload[subscription][customer][email]=pookie999%40example.com&payload[subscription][customer][created_at]=2016-11-04%2017%3A06%3A42%20-0400&payload[subscription][customer][updated_at]=2016-11-04%2017%3A06%3A45%20-0400&payload[subscription][customer][reference]=&payload[subscription][customer][address]=&payload[subscription][customer][address_2]=&payload[subscription][customer][city]=&payload[subscription][customer][state]=&payload[subscription][customer][zip]=&payload[subscription][customer][country]=&payload[subscription][customer][phone]=&payload[subscription][customer][portal_invite_last_sent_at]=2016-11-04%2017%3A06%3A45%20-0400&payload[subscription][customer][portal_invite_last_accepted_at]=&payload[subscription][customer][verified]=false&payload[subscription][customer][portal_customer_created_at]=2016-11-04%2017%3A06%3A45%20-0400&payload[subscription][customer][cc_emails]=&payload[subscription][product][id]=3792003&payload[subscription][product][name]=%2410%20Basic%20Plan&payload[subscription][product][handle]=basic&payload[subscription][product][description]=lorem%20ipsum&payload[subscription][product][accounting_code]=basic&payload[subscription][product][request_credit_card]=false&payload[subscription][product][expiration_interval]=&payload[subscription][product][expiration_interval_unit]=never&payload[subscription][product][created_at]=2016-03-24%2013%3A38%3A39%20-0400&payload[subscription][product][updated_at]=2016-11-03%2013%3A03%3A05%20-0400&payload[subscription][product][price_in_cents]=1000&payload[subscription][product][interval]=1&payload[subscription][product][interval_unit]=day&payload[subscription][product][initial_charge_in_cents]=&payload[subscription][product][trial_price_in_cents]=&payload[subscription][product][trial_interval]=&payload[subscription][product][trial_interval_unit]=month&payload[subscription][product][archived_at]=&payload[subscription][product][require_credit_card]=false&payload[subscription][product][return_params]=&payload[subscription][product][taxable]=false&payload[subscription][product][update_return_url]=&payload[subscription][product][initial_charge_after_trial]=false&payload[subscription][product][version_number]=7&payload[subscription][product][update_return_params]=&payload[subscription][product][product_family][id]=527890&payload[subscription][product][product_family][name]=Acme%20Projects&payload[subscription][product][product_family][description]=&payload[subscription][product][product_family][handle]=billing-plans&payload[subscription][product][product_family][accounting_code]=&payload[subscription][product][public_signup_pages][id]=281054&payload[subscription][product][public_signup_pages][return_url]=http%3A%2F%2Fwww.example.com%3Fsuccessfulsignup&payload[subscription][product][public_signup_pages][return_params]=&payload[subscription][product][public_signup_pages][url]=https%3A%2F%2Fgeneral-goods.chargify.com%2Fsubscribe%2Fkqvmfrbgd89q%2Fbasic&payload[subscription][product][public_signup_pages][id]=281240&payload[subscription][product][public_signup_pages][return_url]=&payload[subscription][product][public_signup_pages][return_params]=&payload[subscription][product][public_signup_pages][url]=https%3A%2F%2Fgeneral-goods.chargify.com%2Fsubscribe%2Fdkffht5dxfd8%2Fbasic&payload[subscription][product][public_signup_pages][id]=282694&payload[subscription][product][public_signup_pages][return_url]=&payload[subscription][product][public_signup_pages][return_params]=&payload[subscription][product][public_signup_pages][url]=https%3A%2F%2Fgeneral-goods.chargify.com%2Fsubscribe%2Fjwffwgdd95s8%2Fbasic&payload[subscription][credit_card][id]=10102821&payload[subscription][credit_card][first_name]=Pookie&payload[subscription][credit_card][last_name]=Test&payload[subscription][credit_card][masked_card_number]=XXXX-XXXX-XXXX-1&payload[subscription][credit_card][card_type]=bogus&payload[subscription][credit_card][expiration_month]=10&payload[subscription][credit_card][expiration_year]=2020&payload[subscription][credit_card][customer_id]=14585695&payload[subscription][credit_card][current_vault]=bogus&payload[subscription][credit_card][vault_token]=1&payload[subscription][credit_card][billing_address]=&payload[subscription][credit_card][billing_city]=&payload[subscription][credit_card][billing_state]=&payload[subscription][credit_card][billing_zip]=&payload[subscription][credit_card][billing_country]=&payload[subscription][credit_card][customer_vault_token]=&payload[subscription][credit_card][billing_address_2]=&payload[subscription][credit_card][payment_type]=credit_card&payload[subscription][credit_card][site_gateway_setting_id]=&payload[subscription][credit_card][gateway_handle]=&payload[transaction][id]=161537369&payload[transaction][subscription_id]=15100141&payload[transaction][type]=Payment&payload[transaction][kind]=&payload[transaction][transaction_type]=payment&payload[transaction][success]=true&payload[transaction][amount_in_cents]=6400&payload[transaction][memo]=Pookie%20Test%20-%20%2410%20Basic%20Plan%3A%20Renewal%20payment&payload[transaction][created_at]=2016-11-08%2016%3A22%3A20%20-0500&payload[transaction][starting_balance_in_cents]=6400&payload[transaction][ending_balance_in_cents]=0&payload[transaction][gateway_used]=bogus&payload[transaction][gateway_transaction_id]=53433&payload[transaction][gateway_response_code]=&payload[transaction][gateway_order_id]=&payload[transaction][payment_id]=&payload[transaction][product_id]=3792003&payload[transaction][tax_id]=&payload[transaction][component_id]=&payload[transaction][statement_id]=80168049&payload[transaction][customer_id]=14585695&payload[transaction][card_number]=XXXX-XXXX-XXXX-1&payload[transaction][card_expiration]=10%2F2020&payload[transaction][card_type]=bogus&payload[transaction][refunded_amount_in_cents]=0&payload[transaction][invoice_id]=&payload[event_id]=347299364", + "signature": "fbcf2f6be579f9658cff90c4373e0ca2", + "signature_hmac_sha_256": "db96654f5456c5460062feb944ac8bb1418f9d181ae04a8ed982fe9ffdca8de1" + } + } +] +``` + + +# Enable Webhooks + +This method allows you to enable webhooks via API for your site + +```go +EnableWebhooks( + ctx context.Context, body *models.EnableWebhooksRequest) ( models.ApiResponse[models.EnableWebhooksResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.EnableWebhooksRequest`](../../doc/models/enable-webhooks-request.md) | Body, Optional | - | - -## Response Type - -[`models.EnableWebhooksResponse`](../../doc/models/enable-webhooks-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.EnableWebhooksRequest`](../../doc/models/enable-webhooks-request.md) | Body, Optional | - | + +## Response Type + +[`models.EnableWebhooksResponse`](../../doc/models/enable-webhooks-response.md) + +## Example Usage + +```go ctx := context.Background() body := models.EnableWebhooksRequest{ @@ -153,45 +157,45 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "webhooks_enabled": true -} -``` - - -# Replay Webhooks - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "webhooks_enabled": true +} +``` + + +# Replay Webhooks + Posting to the replay endpoint does not immediately resend the webhooks. They are added to a queue and will be sent as soon as possible, depending on available system resources. -You may submit an array of up to 1000 webhook IDs to replay in the request. - -```go -ReplayWebhooks( - ctx context.Context, +You may submit an array of up to 1000 webhook IDs to replay in the request. + +```go +ReplayWebhooks( + ctx context.Context, body *models.ReplayWebhooksRequest) ( models.ApiResponse[models.ReplayWebhooksResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.ReplayWebhooksRequest`](../../doc/models/replay-webhooks-request.md) | Body, Optional | - | - -## Response Type - -[`models.ReplayWebhooksResponse`](../../doc/models/replay-webhooks-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.ReplayWebhooksRequest`](../../doc/models/replay-webhooks-request.md) | Body, Optional | - | + +## Response Type + +[`models.ReplayWebhooksResponse`](../../doc/models/replay-webhooks-response.md) + +## Example Usage + +```go ctx := context.Background() body := models.ReplayWebhooksRequest{ @@ -205,46 +209,46 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "status": "ok" -} -``` - - -# Create Endpoint - +} +``` + +## Example Response *(as JSON)* + +```json +{ + "status": "ok" +} +``` + + +# Create Endpoint + The Chargify API allows you to create an endpoint and assign a list of webhooks subscriptions (events) to it. You can check available events here. -[Event keys](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405357509645-Webhooks-Reference#example-payloads) - -```go -CreateEndpoint( - ctx context.Context, +[Event keys](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405357509645-Webhooks-Reference#example-payloads) + +```go +CreateEndpoint( + ctx context.Context, body *models.CreateOrUpdateEndpointRequest) ( models.ApiResponse[models.EndpointResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `body` | [`*models.CreateOrUpdateEndpointRequest`](../../doc/models/create-or-update-endpoint-request.md) | Body, Optional | Used to Create or Update Endpoint | - -## Response Type - -[`models.EndpointResponse`](../../doc/models/endpoint-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `body` | [`*models.CreateOrUpdateEndpointRequest`](../../doc/models/create-or-update-endpoint-request.md) | Body, Optional | Used to Create or Update Endpoint | + +## Response Type + +[`models.EndpointResponse`](../../doc/models/endpoint-response.md) + +## Example Usage + +```go ctx := context.Background() bodyEndpoint := models.CreateOrUpdateEndpoint{ @@ -263,51 +267,51 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -{ - "endpoint": { - "id": 1, - "url": "https://your.site/webhooks", - "site_id": 1, - "status": "enabled", - "webhook_subscriptions": [ - "payment_success", - "payment_failure" - ] - } -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - - -# List Endpoints - -This method returns created endpoints for site. - -```go -ListEndpoints( +} +``` + +## Example Response *(as JSON)* + +```json +{ + "endpoint": { + "id": 1, + "url": "https://your.site/webhooks", + "site_id": 1, + "status": "enabled", + "webhook_subscriptions": [ + "payment_success", + "payment_failure" + ] + } +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + + +# List Endpoints + +This method returns created endpoints for site. + +```go +ListEndpoints( ctx context.Context) ( models.ApiResponse[[]models.Endpoint], - error) -``` - -## Response Type - -[`[]models.Endpoint`](../../doc/models/endpoint.md) - -## Example Usage - -```go + error) +``` + +## Response Type + +[`[]models.Endpoint`](../../doc/models/endpoint.md) + +## Example Usage + +```go ctx := context.Background() apiResponse, err := webhooksController.ListEndpoints(ctx) if err != nil { @@ -316,40 +320,40 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Example Response *(as JSON)* - -```json -[ - { - "id": 11, - "url": "https://foobar.com/webhooks", - "site_id": 1, - "status": "enabled", - "webhook_subscriptions": [ - "payment_success", - "payment_failure" - ] - }, - { - "id": 12, - "url": "https:/example.com/webhooks", - "site_id": 1, - "status": "enabled", - "webhook_subscriptions": [ - "payment_success", - "payment_failure", - "refund_failure" - ] - } -] -``` - - -# Update Endpoint - +} +``` + +## Example Response *(as JSON)* + +```json +[ + { + "id": 11, + "url": "https://foobar.com/webhooks", + "site_id": 1, + "status": "enabled", + "webhook_subscriptions": [ + "payment_success", + "payment_failure" + ] + }, + { + "id": 12, + "url": "https:/example.com/webhooks", + "site_id": 1, + "status": "enabled", + "webhook_subscriptions": [ + "payment_success", + "payment_failure", + "refund_failure" + ] + } +] +``` + + +# Update Endpoint + You can update an Endpoint via the API with a PUT request to the resource endpoint. You can change the `url` of your endpoint which consumes webhooks or list of `webhook_subscriptions`. @@ -358,31 +362,31 @@ Check available [Event keys](https://maxio-chargify.zendesk.com/hc/en-us/article Always send a complete list of events which you want subscribe/watch. Sending an PUT request for existing endpoint with empty list of `webhook_subscriptions` will end with unsubscribe from all events. -If you want unsubscribe from specific event, just send a list of `webhook_subscriptions` without the specific event key. - -```go -UpdateEndpoint( - ctx context.Context, - endpointId int, +If you want unsubscribe from specific event, just send a list of `webhook_subscriptions` without the specific event key. + +```go +UpdateEndpoint( + ctx context.Context, + endpointId int, body *models.CreateOrUpdateEndpointRequest) ( models.ApiResponse[models.EndpointResponse], - error) -``` - -## Parameters - -| Parameter | Type | Tags | Description | -| --- | --- | --- | --- | -| `endpointId` | `int` | Template, Required | The Chargify id for the endpoint that should be updated | -| `body` | [`*models.CreateOrUpdateEndpointRequest`](../../doc/models/create-or-update-endpoint-request.md) | Body, Optional | Used to Create or Update Endpoint | - -## Response Type - -[`models.EndpointResponse`](../../doc/models/endpoint-response.md) - -## Example Usage - -```go + error) +``` + +## Parameters + +| Parameter | Type | Tags | Description | +| --- | --- | --- | --- | +| `endpointId` | `int` | Template, Required | The Chargify id for the endpoint that should be updated | +| `body` | [`*models.CreateOrUpdateEndpointRequest`](../../doc/models/create-or-update-endpoint-request.md) | Body, Optional | Used to Create or Update Endpoint | + +## Response Type + +[`models.EndpointResponse`](../../doc/models/endpoint-response.md) + +## Example Usage + +```go ctx := context.Background() endpointId := 42 @@ -402,13 +406,13 @@ if err != nil { // Printing the result and response fmt.Println(apiResponse.Data) fmt.Println(apiResponse.Response.StatusCode) -} -``` - -## Errors - -| HTTP Status Code | Error Description | Exception Class | -| --- | --- | --- | -| 404 | Not Found | `ApiError` | -| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | - +} +``` + +## Errors + +| HTTP Status Code | Error Description | Exception Class | +| --- | --- | --- | +| 404 | Not Found | `ApiError` | +| 422 | Unprocessable Entity (WebDAV) | [`ErrorListResponseException`](../../doc/models/error-list-response-exception.md) | + diff --git a/doc/http-configuration.md b/doc/http-configuration.md index 2a1c5bac..cec2beb8 100644 --- a/doc/http-configuration.md +++ b/doc/http-configuration.md @@ -1,23 +1,23 @@ - -# HttpConfiguration - -The following parameters are configurable for the HttpConfiguration: - -## Properties - -| Name | Type | Description | -| --- | --- | --- | -| `timeout` | `float64` | Timeout in milliseconds.
*Default*: `30` | -| `transport` | `http.RoundTripper` | Establishes network connection and caches them for reuse.
*Default*: `http.DefaultTransport` | -| `retryConfiguration` | [`advancedbilling.RetryConfiguration`](retry-configuration.md) | Configurations to retry requests.
*Default*: `DefaultRetryConfiguration()` | - -The httpConfiguration can be initialized as follows: - + +# HttpConfiguration + +The following parameters are configurable for the HttpConfiguration: + +## Properties + +| Name | Type | Description | +| --- | --- | --- | +| `timeout` | `float64` | Timeout in milliseconds.
*Default*: `30` | +| `transport` | `http.RoundTripper` | Establishes network connection and caches them for reuse.
*Default*: `http.DefaultTransport` | +| `retryConfiguration` | [`advancedbilling.RetryConfiguration`](retry-configuration.md) | Configurations to retry requests.
*Default*: `DefaultRetryConfiguration()` | + +The httpConfiguration can be initialized as follows: + ```go httpConfiguration := CreateHttpConfiguration( advancedbilling.WithTimeout(30), advancedbilling.WithTransport(http.DefaultTransport), advancedbilling.WithRetryConfiguration(DefaultRetryConfiguration()), ) -``` - +``` + diff --git a/doc/models/account-balance.md b/doc/models/account-balance.md index 40830491..99d195b7 100644 --- a/doc/models/account-balance.md +++ b/doc/models/account-balance.md @@ -1,21 +1,25 @@ - -# Account Balance - -## Structure - -`AccountBalance` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `BalanceInCents` | `*int64` | Optional | The balance in cents. | - -## Example (as JSON) - -```json -{ - "balance_in_cents": 16 -} -``` - + +# Account Balance + +## Structure + +`AccountBalance` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `BalanceInCents` | `*int64` | Optional | The balance in cents. | +| `AutomaticBalanceInCents` | `models.Optional[int64]` | Optional | The automatic balance in cents. | +| `RemittanceBalanceInCents` | `models.Optional[int64]` | Optional | The remittance balance in cents. | + +## Example (as JSON) + +```json +{ + "balance_in_cents": 16, + "automatic_balance_in_cents": 226, + "remittance_balance_in_cents": 62 +} +``` + diff --git a/doc/models/account-balances.md b/doc/models/account-balances.md index 3febc339..a30ab2e0 100644 --- a/doc/models/account-balances.md +++ b/doc/models/account-balances.md @@ -1,35 +1,49 @@ - -# Account Balances - -## Structure - -`AccountBalances` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `OpenInvoices` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | The balance, in cents, of the sum of the subscription's open, payable invoices. | -| `PendingDiscounts` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | The balance, in cents, of the subscription's Pending Discount account. | -| `ServiceCredits` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | The balance, in cents, of the subscription's Service Credit account. | -| `Prepayments` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | The balance, in cents, of the subscription's Prepayment account. | - -## Example (as JSON) - -```json -{ - "open_invoices": { - "balance_in_cents": 40 - }, - "pending_discounts": { - "balance_in_cents": 88 - }, - "service_credits": { - "balance_in_cents": 84 - }, - "prepayments": { - "balance_in_cents": 192 - } -} -``` - + +# Account Balances + +## Structure + +`AccountBalances` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `OpenInvoices` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | The balance, in cents, of the sum of the subscription's open, payable invoices. | +| `PendingInvoices` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | The balance, in cents, of the sum of the subscription's pending, payable invoices. | +| `PendingDiscounts` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | The balance, in cents, of the subscription's Pending Discount account. | +| `ServiceCredits` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | The balance, in cents, of the subscription's Service Credit account. | +| `Prepayments` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | The balance, in cents, of the subscription's Prepayment account. | + +## Example (as JSON) + +```json +{ + "open_invoices": { + "balance_in_cents": 40, + "automatic_balance_in_cents": 202, + "remittance_balance_in_cents": 170 + }, + "pending_invoices": { + "balance_in_cents": 0, + "automatic_balance_in_cents": 242, + "remittance_balance_in_cents": 46 + }, + "pending_discounts": { + "balance_in_cents": 88, + "automatic_balance_in_cents": 154, + "remittance_balance_in_cents": 134 + }, + "service_credits": { + "balance_in_cents": 84, + "automatic_balance_in_cents": 70, + "remittance_balance_in_cents": 38 + }, + "prepayments": { + "balance_in_cents": 192, + "automatic_balance_in_cents": 178, + "remittance_balance_in_cents": 146 + } +} +``` + diff --git a/doc/models/ach-agreement.md b/doc/models/ach-agreement.md index 7b29d88b..59f2b799 100644 --- a/doc/models/ach-agreement.md +++ b/doc/models/ach-agreement.md @@ -1,29 +1,29 @@ - -# ACH Agreement - -(Optional) If passed, the proof of the authorized ACH agreement terms will be persisted. - -## Structure - -`ACHAgreement` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `AgreementTerms` | `*string` | Optional | (Required when providing ACH agreement params) The ACH authorization agreement terms. | -| `AuthorizerFirstName` | `*string` | Optional | (Required when providing ACH agreement params) The first name of the person authorizing the ACH agreement. | -| `AuthorizerLastName` | `*string` | Optional | (Required when providing ACH agreement params) The last name of the person authorizing the ACH agreement. | -| `IpAddress` | `*string` | Optional | (Required when providing ACH agreement params) The IP address of the person authorizing the ACH agreement. | - -## Example (as JSON) - -```json -{ - "agreement_terms": "agreement_terms4", - "authorizer_first_name": "authorizer_first_name2", - "authorizer_last_name": "authorizer_last_name2", - "ip_address": "ip_address2" -} -``` - + +# ACH Agreement + +(Optional) If passed, the proof of the authorized ACH agreement terms will be persisted. + +## Structure + +`ACHAgreement` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `AgreementTerms` | `*string` | Optional | (Required when providing ACH agreement params) The ACH authorization agreement terms. | +| `AuthorizerFirstName` | `*string` | Optional | (Required when providing ACH agreement params) The first name of the person authorizing the ACH agreement. | +| `AuthorizerLastName` | `*string` | Optional | (Required when providing ACH agreement params) The last name of the person authorizing the ACH agreement. | +| `IpAddress` | `*string` | Optional | (Required when providing ACH agreement params) The IP address of the person authorizing the ACH agreement. | + +## Example (as JSON) + +```json +{ + "agreement_terms": "agreement_terms4", + "authorizer_first_name": "authorizer_first_name2", + "authorizer_last_name": "authorizer_last_name2", + "ip_address": "ip_address2" +} +``` + diff --git a/doc/models/activate-subscription-request.md b/doc/models/activate-subscription-request.md index 2bb74dbe..aa15466e 100644 --- a/doc/models/activate-subscription-request.md +++ b/doc/models/activate-subscription-request.md @@ -1,21 +1,21 @@ - -# Activate Subscription Request - -## Structure - -`ActivateSubscriptionRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `RevertOnFailure` | `Optional[bool]` | Optional | You may choose how to handle the activation failure. `true` means do not change the subscription’s state and billing period. `false` means to continue through with the activation and enter an end of life state. If this parameter is omitted or `null` is passed it will default to value set in the site settings (default: `true`) | - -## Example (as JSON) - -```json -{ - "revert_on_failure": false -} -``` - + +# Activate Subscription Request + +## Structure + +`ActivateSubscriptionRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `RevertOnFailure` | `models.Optional[bool]` | Optional | You may choose how to handle the activation failure. `true` means do not change the subscription’s state and billing period. `false` means to continue through with the activation and enter an end of life state. If this parameter is omitted or `null` is passed it will default to value set in the site settings (default: `true`) | + +## Example (as JSON) + +```json +{ + "revert_on_failure": false +} +``` + diff --git a/doc/models/add-coupons-request.md b/doc/models/add-coupons-request.md index ccc59332..e63e4a78 100644 --- a/doc/models/add-coupons-request.md +++ b/doc/models/add-coupons-request.md @@ -1,24 +1,24 @@ - -# Add Coupons Request - -## Structure - -`AddCouponsRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Codes` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "codes": [ - "codes0", - "codes1" - ] -} -``` - + +# Add Coupons Request + +## Structure + +`AddCouponsRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Codes` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "codes": [ + "codes0", + "codes1" + ] +} +``` + diff --git a/doc/models/add-subscription-to-a-group.md b/doc/models/add-subscription-to-a-group.md index 7c632805..cfc41655 100644 --- a/doc/models/add-subscription-to-a-group.md +++ b/doc/models/add-subscription-to-a-group.md @@ -1,24 +1,31 @@ - -# Add Subscription to a Group - -## Structure - -`AddSubscriptionToAGroup` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Group` | `*interface{}` | Optional | - | - -## Example (as JSON) - -```json -{ - "group": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Add Subscription to a Group + +## Structure + +`AddSubscriptionToAGroup` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Group` | [`*models.AddSubscriptionToAGroupGroup`](../../doc/models/containers/add-subscription-to-a-group-group.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "group": { + "target": { + "type": "parent", + "id": 236 + }, + "billing": { + "accrue": false, + "align_date": false, + "prorate": false + } + } +} +``` + diff --git a/doc/models/address-change.md b/doc/models/address-change.md index 45a27cd9..94c23f99 100644 --- a/doc/models/address-change.md +++ b/doc/models/address-change.md @@ -1,35 +1,35 @@ - -# Address Change - -## Structure - -`AddressChange` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Before` | [`models.InvoiceAddress`](../../doc/models/invoice-address.md) | Required | - | -| `After` | [`models.InvoiceAddress`](../../doc/models/invoice-address.md) | Required | - | - -## Example (as JSON) - -```json -{ - "before": { - "street": "street0", - "line2": "line24", - "city": "city0", - "state": "state6", - "zip": "zip4" - }, - "after": { - "street": "street2", - "line2": "line26", - "city": "city8", - "state": "state2", - "zip": "zip4" - } -} -``` - + +# Address Change + +## Structure + +`AddressChange` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Before` | [`models.InvoiceAddress`](../../doc/models/invoice-address.md) | Required | - | +| `After` | [`models.InvoiceAddress`](../../doc/models/invoice-address.md) | Required | - | + +## Example (as JSON) + +```json +{ + "before": { + "street": "street0", + "line2": "line24", + "city": "city0", + "state": "state6", + "zip": "zip4" + }, + "after": { + "street": "street2", + "line2": "line26", + "city": "city8", + "state": "state2", + "zip": "zip4" + } +} +``` + diff --git a/doc/models/agreement-acceptance.md b/doc/models/agreement-acceptance.md index b3752aa2..f7826189 100644 --- a/doc/models/agreement-acceptance.md +++ b/doc/models/agreement-acceptance.md @@ -1,32 +1,32 @@ - -# Agreement Acceptance - -Required when creating a subscription with Maxio Payments. - -## Structure - -`AgreementAcceptance` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `IpAddress` | `*string` | Optional | Required when providing agreement acceptance params. | -| `TermsUrl` | `*string` | Optional | Required when creating a subscription with Maxio Payments. Either terms_url or provacy_policy_url required when providing agreement_acceptance params. | -| `PrivacyPolicyUrl` | `*string` | Optional | - | -| `ReturnRefundPolicyUrl` | `*string` | Optional | - | -| `DeliveryPolicyUrl` | `*string` | Optional | - | -| `SecureCheckoutPolicyUrl` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "ip_address": "ip_address2", - "terms_url": "terms_url0", - "privacy_policy_url": "privacy_policy_url0", - "return_refund_policy_url": "return_refund_policy_url4", - "delivery_policy_url": "delivery_policy_url8" -} -``` - + +# Agreement Acceptance + +Required when creating a subscription with Maxio Payments. + +## Structure + +`AgreementAcceptance` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `IpAddress` | `*string` | Optional | Required when providing agreement acceptance params. | +| `TermsUrl` | `*string` | Optional | Required when creating a subscription with Maxio Payments. Either terms_url or provacy_policy_url required when providing agreement_acceptance params. | +| `PrivacyPolicyUrl` | `*string` | Optional | - | +| `ReturnRefundPolicyUrl` | `*string` | Optional | - | +| `DeliveryPolicyUrl` | `*string` | Optional | - | +| `SecureCheckoutPolicyUrl` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "ip_address": "ip_address2", + "terms_url": "terms_url0", + "privacy_policy_url": "privacy_policy_url0", + "return_refund_policy_url": "return_refund_policy_url4", + "delivery_policy_url": "delivery_policy_url8" +} +``` + diff --git a/doc/models/allocate-components.md b/doc/models/allocate-components.md index f2184255..cc25f84d 100644 --- a/doc/models/allocate-components.md +++ b/doc/models/allocate-components.md @@ -1,49 +1,49 @@ - -# Allocate Components - -## Structure - -`AllocateComponents` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ProrationUpgradeScheme` | `*string` | Optional | - | -| `ProrationDowngradeScheme` | `*string` | Optional | - | -| `Allocations` | [`[]models.CreateAllocation`](../../doc/models/create-allocation.md) | Optional | - | -| `AccrueCharge` | `*bool` | Optional | - | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `PaymentCollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | (Optional) If not passed, the allocation(s) will use the payment collection method on the subscription | -| `InitiateDunning` | `*bool` | Optional | If true, if the immediate component payment fails, initiate dunning for the subscription.
Otherwise, leave the charges on the subscription to pay for at renewal. | - -## Example (as JSON) - -```json -{ - "proration_upgrade_scheme": "proration_upgrade_scheme2", - "proration_downgrade_scheme": "proration_downgrade_scheme0", - "allocations": [ - { - "quantity": 26.48, - "component_id": 242, - "memo": "memo6", - "proration_downgrade_scheme": "proration_downgrade_scheme0", - "proration_upgrade_scheme": "proration_upgrade_scheme2", - "accrue_charge": false - }, - { - "quantity": 26.48, - "component_id": 242, - "memo": "memo6", - "proration_downgrade_scheme": "proration_downgrade_scheme0", - "proration_upgrade_scheme": "proration_upgrade_scheme2", - "accrue_charge": false - } - ], - "accrue_charge": false, - "upgrade_charge": "full" -} -``` - + +# Allocate Components + +## Structure + +`AllocateComponents` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProrationUpgradeScheme` | `*string` | Optional | - | +| `ProrationDowngradeScheme` | `*string` | Optional | - | +| `Allocations` | [`[]models.CreateAllocation`](../../doc/models/create-allocation.md) | Optional | - | +| `AccrueCharge` | `*bool` | Optional | - | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `PaymentCollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | (Optional) If not passed, the allocation(s) will use the payment collection method on the subscription | +| `InitiateDunning` | `*bool` | Optional | If true, if the immediate component payment fails, initiate dunning for the subscription.
Otherwise, leave the charges on the subscription to pay for at renewal. | + +## Example (as JSON) + +```json +{ + "proration_upgrade_scheme": "proration_upgrade_scheme2", + "proration_downgrade_scheme": "proration_downgrade_scheme0", + "allocations": [ + { + "quantity": 26.48, + "component_id": 242, + "memo": "memo6", + "proration_downgrade_scheme": "proration_downgrade_scheme0", + "proration_upgrade_scheme": "proration_upgrade_scheme2", + "accrue_charge": false + }, + { + "quantity": 26.48, + "component_id": 242, + "memo": "memo6", + "proration_downgrade_scheme": "proration_downgrade_scheme0", + "proration_upgrade_scheme": "proration_upgrade_scheme2", + "accrue_charge": false + } + ], + "accrue_charge": false, + "upgrade_charge": "full" +} +``` + diff --git a/doc/models/allocation-expiration-date.md b/doc/models/allocation-expiration-date.md index 3e30517d..653f8566 100644 --- a/doc/models/allocation-expiration-date.md +++ b/doc/models/allocation-expiration-date.md @@ -1,21 +1,21 @@ - -# Allocation Expiration Date - -## Structure - -`AllocationExpirationDate` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ExpiresAt` | `*time.Time` | Optional | - | - -## Example (as JSON) - -```json -{ - "expires_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Allocation Expiration Date + +## Structure + +`AllocationExpirationDate` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ExpiresAt` | `*time.Time` | Optional | - | + +## Example (as JSON) + +```json +{ + "expires_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/allocation-preview-direction.md b/doc/models/allocation-preview-direction.md index 57ca4e0b..2e124430 100644 --- a/doc/models/allocation-preview-direction.md +++ b/doc/models/allocation-preview-direction.md @@ -1,14 +1,14 @@ - -# Allocation Preview Direction - -## Enumeration - -`AllocationPreviewDirection` - -## Fields - -| Name | -| --- | -| `UPGRADE` | -| `DOWNGRADE` | - + +# Allocation Preview Direction + +## Enumeration + +`AllocationPreviewDirection` + +## Fields + +| Name | +| --- | +| `UPGRADE` | +| `DOWNGRADE` | + diff --git a/doc/models/allocation-preview-item.md b/doc/models/allocation-preview-item.md index 15828fba..651c7e8d 100644 --- a/doc/models/allocation-preview-item.md +++ b/doc/models/allocation-preview-item.md @@ -1,48 +1,42 @@ - -# Allocation Preview Item - -## Structure - -`AllocationPreviewItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ComponentId` | `*int` | Optional | - | -| `SubscriptionId` | `*int` | Optional | - | -| `Quantity` | `*interface{}` | Optional | - | -| `PreviousQuantity` | `*interface{}` | Optional | - | -| `Memo` | `Optional[string]` | Optional | - | -| `Timestamp` | `Optional[string]` | Optional | - | -| `ProrationUpgradeScheme` | `*string` | Optional | - | -| `ProrationDowngradeScheme` | `*string` | Optional | - | -| `AccrueCharge` | `*bool` | Optional | - | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `PricePointId` | `*int` | Optional | - | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | -| `PreviousPricePointId` | `*int` | Optional | - | -| `PricePointHandle` | `*string` | Optional | - | -| `PricePointName` | `*string` | Optional | - | -| `ComponentHandle` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "component_id": 54, - "subscription_id": 54, - "quantity": { - "key1": "val1", - "key2": "val2" - }, - "previous_quantity": { - "key1": "val1", - "key2": "val2" - }, - "memo": "memo6" -} -``` - + +# Allocation Preview Item + +## Structure + +`AllocationPreviewItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ComponentId` | `*int` | Optional | - | +| `SubscriptionId` | `*int` | Optional | - | +| `Quantity` | [`*models.AllocationPreviewItemQuantity`](../../doc/models/containers/allocation-preview-item-quantity.md) | Optional | This is a container for one-of cases. | +| `PreviousQuantity` | [`*models.AllocationPreviewItemPreviousQuantity`](../../doc/models/containers/allocation-preview-item-previous-quantity.md) | Optional | This is a container for one-of cases. | +| `Memo` | `models.Optional[string]` | Optional | - | +| `Timestamp` | `models.Optional[string]` | Optional | - | +| `ProrationUpgradeScheme` | `*string` | Optional | - | +| `ProrationDowngradeScheme` | `*string` | Optional | - | +| `AccrueCharge` | `*bool` | Optional | - | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `PricePointId` | `*int` | Optional | - | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | +| `PreviousPricePointId` | `*int` | Optional | - | +| `PricePointHandle` | `*string` | Optional | - | +| `PricePointName` | `*string` | Optional | - | +| `ComponentHandle` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "component_id": 54, + "subscription_id": 54, + "quantity": 78, + "previous_quantity": 192, + "memo": "memo6" +} +``` + diff --git a/doc/models/allocation-preview-line-item-kind.md b/doc/models/allocation-preview-line-item-kind.md index 608e758a..da6c7110 100644 --- a/doc/models/allocation-preview-line-item-kind.md +++ b/doc/models/allocation-preview-line-item-kind.md @@ -1,18 +1,18 @@ - -# Allocation Preview Line Item Kind - -A handle for the line item kind for allocation preview - -## Enumeration - -`AllocationPreviewLineItemKind` - -## Fields - -| Name | -| --- | -| `QUANTITYBASEDCOMPONENT` | -| `ONOFFCOMPONENT` | -| `COUPON` | -| `TAX` | - + +# Allocation Preview Line Item Kind + +A handle for the line item kind for allocation preview + +## Enumeration + +`AllocationPreviewLineItemKind` + +## Fields + +| Name | +| --- | +| `QUANTITYBASEDCOMPONENT` | +| `ONOFFCOMPONENT` | +| `COUPON` | +| `TAX` | + diff --git a/doc/models/allocation-preview-line-item.md b/doc/models/allocation-preview-line-item.md index cee46163..2f210c9e 100644 --- a/doc/models/allocation-preview-line-item.md +++ b/doc/models/allocation-preview-line-item.md @@ -1,33 +1,33 @@ - -# Allocation Preview Line Item - -## Structure - -`AllocationPreviewLineItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TransactionType` | [`*models.LineItemTransactionType`](../../doc/models/line-item-transaction-type.md) | Optional | A handle for the line item transaction type | -| `Kind` | [`*models.AllocationPreviewLineItemKind`](../../doc/models/allocation-preview-line-item-kind.md) | Optional | A handle for the line item kind for allocation preview | -| `AmountInCents` | `*int64` | Optional | - | -| `Memo` | `*string` | Optional | - | -| `DiscountAmountInCents` | `*int64` | Optional | - | -| `TaxableAmountInCents` | `*int64` | Optional | - | -| `ComponentId` | `*int` | Optional | - | -| `ComponentHandle` | `*string` | Optional | - | -| `Direction` | [`*models.AllocationPreviewDirection`](../../doc/models/allocation-preview-direction.md) | Optional | Visible when using Fine-grained Component Control | - -## Example (as JSON) - -```json -{ - "transaction_type": "credit", - "kind": "quantity_based_component", - "amount_in_cents": 24, - "memo": "memo6", - "discount_amount_in_cents": 172 -} -``` - + +# Allocation Preview Line Item + +## Structure + +`AllocationPreviewLineItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TransactionType` | [`*models.LineItemTransactionType`](../../doc/models/line-item-transaction-type.md) | Optional | A handle for the line item transaction type | +| `Kind` | [`*models.AllocationPreviewLineItemKind`](../../doc/models/allocation-preview-line-item-kind.md) | Optional | A handle for the line item kind for allocation preview | +| `AmountInCents` | `*int64` | Optional | - | +| `Memo` | `*string` | Optional | - | +| `DiscountAmountInCents` | `*int64` | Optional | - | +| `TaxableAmountInCents` | `*int64` | Optional | - | +| `ComponentId` | `*int` | Optional | - | +| `ComponentHandle` | `*string` | Optional | - | +| `Direction` | [`*models.AllocationPreviewDirection`](../../doc/models/allocation-preview-direction.md) | Optional | Visible when using Fine-grained Component Control | + +## Example (as JSON) + +```json +{ + "transaction_type": "credit", + "kind": "quantity_based_component", + "amount_in_cents": 24, + "memo": "memo6", + "discount_amount_in_cents": 172 +} +``` + diff --git a/doc/models/allocation-preview-response.md b/doc/models/allocation-preview-response.md index bb8639cb..56391ed7 100644 --- a/doc/models/allocation-preview-response.md +++ b/doc/models/allocation-preview-response.md @@ -1,27 +1,27 @@ - -# Allocation Preview Response - -## Structure - -`AllocationPreviewResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `AllocationPreview` | [`models.AllocationPreview`](../../doc/models/allocation-preview.md) | Required | - | - -## Example (as JSON) - -```json -{ - "allocation_preview": { - "start_date": "2016-03-13T12:52:32.123Z", - "end_date": "2016-03-13T12:52:32.123Z", - "subtotal_in_cents": 240, - "total_tax_in_cents": 108, - "total_discount_in_cents": 142 - } -} -``` - + +# Allocation Preview Response + +## Structure + +`AllocationPreviewResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `AllocationPreview` | [`models.AllocationPreview`](../../doc/models/allocation-preview.md) | Required | - | + +## Example (as JSON) + +```json +{ + "allocation_preview": { + "start_date": "2016-03-13T12:52:32.123Z", + "end_date": "2016-03-13T12:52:32.123Z", + "subtotal_in_cents": 240, + "total_tax_in_cents": 108, + "total_discount_in_cents": 142 + } +} +``` + diff --git a/doc/models/allocation-preview.md b/doc/models/allocation-preview.md index b2d15be5..fbe9d2e2 100644 --- a/doc/models/allocation-preview.md +++ b/doc/models/allocation-preview.md @@ -1,37 +1,37 @@ - -# Allocation Preview - -## Structure - -`AllocationPreview` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `StartDate` | `*time.Time` | Optional | - | -| `EndDate` | `*time.Time` | Optional | - | -| `SubtotalInCents` | `*int64` | Optional | - | -| `TotalTaxInCents` | `*int64` | Optional | - | -| `TotalDiscountInCents` | `*int64` | Optional | - | -| `TotalInCents` | `*int64` | Optional | - | -| `Direction` | [`*models.AllocationPreviewDirection`](../../doc/models/allocation-preview-direction.md) | Optional | - | -| `ProrationScheme` | `*string` | Optional | - | -| `LineItems` | [`[]models.AllocationPreviewLineItem`](../../doc/models/allocation-preview-line-item.md) | Optional | - | -| `AccrueCharge` | `*bool` | Optional | - | -| `Allocations` | [`[]models.AllocationPreviewItem`](../../doc/models/allocation-preview-item.md) | Optional | - | -| `PeriodType` | `*string` | Optional | - | -| `ExistingBalanceInCents` | `*int64` | Optional | An integer representing the amount of the subscription's current balance | - -## Example (as JSON) - -```json -{ - "start_date": "2016-03-13T12:52:32.123Z", - "end_date": "2016-03-13T12:52:32.123Z", - "subtotal_in_cents": 4, - "total_tax_in_cents": 128, - "total_discount_in_cents": 122 -} -``` - + +# Allocation Preview + +## Structure + +`AllocationPreview` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `StartDate` | `*time.Time` | Optional | - | +| `EndDate` | `*time.Time` | Optional | - | +| `SubtotalInCents` | `*int64` | Optional | - | +| `TotalTaxInCents` | `*int64` | Optional | - | +| `TotalDiscountInCents` | `*int64` | Optional | - | +| `TotalInCents` | `*int64` | Optional | - | +| `Direction` | [`*models.AllocationPreviewDirection`](../../doc/models/allocation-preview-direction.md) | Optional | - | +| `ProrationScheme` | `*string` | Optional | - | +| `LineItems` | [`[]models.AllocationPreviewLineItem`](../../doc/models/allocation-preview-line-item.md) | Optional | - | +| `AccrueCharge` | `*bool` | Optional | - | +| `Allocations` | [`[]models.AllocationPreviewItem`](../../doc/models/allocation-preview-item.md) | Optional | - | +| `PeriodType` | `*string` | Optional | - | +| `ExistingBalanceInCents` | `*int64` | Optional | An integer representing the amount of the subscription's current balance | + +## Example (as JSON) + +```json +{ + "start_date": "2016-03-13T12:52:32.123Z", + "end_date": "2016-03-13T12:52:32.123Z", + "subtotal_in_cents": 4, + "total_tax_in_cents": 128, + "total_discount_in_cents": 122 +} +``` + diff --git a/doc/models/allocation-response.md b/doc/models/allocation-response.md index 4cffa68a..ca958920 100644 --- a/doc/models/allocation-response.md +++ b/doc/models/allocation-response.md @@ -1,30 +1,27 @@ - -# Allocation Response - -## Structure - -`AllocationResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Allocation` | [`*models.Allocation`](../../doc/models/allocation.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "allocation": { - "allocation_id": 238, - "component_id": 8, - "component_handle": "component_handle8", - "subscription_id": 8, - "quantity": { - "key1": "val1", - "key2": "val2" - } - } -} -``` - + +# Allocation Response + +## Structure + +`AllocationResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Allocation` | [`*models.Allocation`](../../doc/models/allocation.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "allocation": { + "allocation_id": 238, + "component_id": 8, + "component_handle": "component_handle8", + "subscription_id": 8, + "quantity": 32 + } +} +``` + diff --git a/doc/models/allocation-settings.md b/doc/models/allocation-settings.md index 4b00ed81..f9f6d2c3 100644 --- a/doc/models/allocation-settings.md +++ b/doc/models/allocation-settings.md @@ -1,25 +1,25 @@ - -# Allocation Settings - -## Structure - -`AllocationSettings` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `AccrueCharge` | `*string` | Optional | Either "true" or "false". | - -## Example (as JSON) - -```json -{ - "upgrade_charge": "none", - "downgrade_credit": "prorated", - "accrue_charge": "accrue_charge0" -} -``` - + +# Allocation Settings + +## Structure + +`AllocationSettings` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `AccrueCharge` | `*string` | Optional | Either "true" or "false". | + +## Example (as JSON) + +```json +{ + "upgrade_charge": "none", + "downgrade_credit": "prorated", + "accrue_charge": "accrue_charge0" +} +``` + diff --git a/doc/models/allocation.md b/doc/models/allocation.md index 6c16a982..08bb93d7 100644 --- a/doc/models/allocation.md +++ b/doc/models/allocation.md @@ -1,52 +1,49 @@ - -# Allocation - -## Structure - -`Allocation` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `AllocationId` | `*int` | Optional | The allocation unique id | -| `ComponentId` | `*int` | Optional | The integer component ID for the allocation. This references a component that you have created in your Product setup | -| `ComponentHandle` | `Optional[string]` | Optional | The handle of the component. This references a component that you have created in your Product setup | -| `SubscriptionId` | `*int` | Optional | The integer subscription ID for the allocation. This references a unique subscription in your Site | -| `Quantity` | `*interface{}` | Optional | The allocated quantity set in to effect by the allocation. String for components supporting fractional quantities | -| `PreviousQuantity` | `*interface{}` | Optional | The allocated quantity that was in effect before this allocation was created. String for components supporting fractional quantities | -| `Memo` | `Optional[string]` | Optional | The memo passed when the allocation was created | -| `Timestamp` | `*time.Time` | Optional | The time that the allocation was recorded, in format and UTC timezone, i.e. 2012-11-20T22:00:37Z | -| `CreatedAt` | `*time.Time` | Optional | Timestamp indicating when this allocation was created | -| `ProrationUpgradeScheme` | `*string` | Optional | The scheme used if the proration was an upgrade. This is only present when the allocation was created mid-period. | -| `ProrationDowngradeScheme` | `*string` | Optional | The scheme used if the proration was a downgrade. This is only present when the allocation was created mid-period. | -| `PricePointId` | `*int` | Optional | - | -| `PricePointName` | `*string` | Optional | - | -| `PricePointHandle` | `*string` | Optional | - | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | -| `PreviousPricePointId` | `*int` | Optional | - | -| `AccrueCharge` | `*bool` | Optional | If the change in cost is an upgrade, this determines if the charge should accrue to the next renewal or if capture should be attempted immediately. | -| `InitiateDunning` | `*bool` | Optional | If true, if the immediate component payment fails, initiate dunning for the subscription.
Otherwise, leave the charges on the subscription to pay for at renewal. | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `Payment` | [`Optional[models.PaymentForAllocation]`](../../doc/models/payment-for-allocation.md) | Optional | - | -| `ExpiresAt` | `*time.Time` | Optional | - | -| `UsedQuantity` | `*int64` | Optional | - | -| `ChargeId` | `*int64` | Optional | - | - -## Example (as JSON) - -```json -{ - "allocation_id": 102, - "component_id": 144, - "component_handle": "component_handle0", - "subscription_id": 144, - "quantity": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Allocation + +## Structure + +`Allocation` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `AllocationId` | `*int` | Optional | The allocation unique id | +| `ComponentId` | `*int` | Optional | The integer component ID for the allocation. This references a component that you have created in your Product setup | +| `ComponentHandle` | `models.Optional[string]` | Optional | The handle of the component. This references a component that you have created in your Product setup | +| `SubscriptionId` | `*int` | Optional | The integer subscription ID for the allocation. This references a unique subscription in your Site | +| `Quantity` | [`*models.AllocationQuantity`](../../doc/models/containers/allocation-quantity.md) | Optional | This is a container for one-of cases. | +| `PreviousQuantity` | [`*models.AllocationPreviousQuantity`](../../doc/models/containers/allocation-previous-quantity.md) | Optional | This is a container for one-of cases. | +| `Memo` | `models.Optional[string]` | Optional | The memo passed when the allocation was created | +| `Timestamp` | `*time.Time` | Optional | The time that the allocation was recorded, in format and UTC timezone, i.e. 2012-11-20T22:00:37Z | +| `CreatedAt` | `*time.Time` | Optional | Timestamp indicating when this allocation was created | +| `ProrationUpgradeScheme` | `*string` | Optional | The scheme used if the proration was an upgrade. This is only present when the allocation was created mid-period. | +| `ProrationDowngradeScheme` | `*string` | Optional | The scheme used if the proration was a downgrade. This is only present when the allocation was created mid-period. | +| `PricePointId` | `*int` | Optional | - | +| `PricePointName` | `*string` | Optional | - | +| `PricePointHandle` | `*string` | Optional | - | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | +| `PreviousPricePointId` | `*int` | Optional | - | +| `AccrueCharge` | `*bool` | Optional | If the change in cost is an upgrade, this determines if the charge should accrue to the next renewal or if capture should be attempted immediately. | +| `InitiateDunning` | `*bool` | Optional | If true, if the immediate component payment fails, initiate dunning for the subscription.
Otherwise, leave the charges on the subscription to pay for at renewal. | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `Payment` | [`models.Optional[models.AllocationPayment]`](../../doc/models/containers/allocation-payment.md) | Optional | This is a container for one-of cases. | +| `ExpiresAt` | `*time.Time` | Optional | - | +| `UsedQuantity` | `*int64` | Optional | - | +| `ChargeId` | `*int64` | Optional | - | + +## Example (as JSON) + +```json +{ + "allocation_id": 102, + "component_id": 144, + "component_handle": "component_handle0", + "subscription_id": 144, + "quantity": 168 +} +``` + diff --git a/doc/models/applied-credit-note-data.md b/doc/models/applied-credit-note-data.md index 5362fb18..e16b48f8 100644 --- a/doc/models/applied-credit-note-data.md +++ b/doc/models/applied-credit-note-data.md @@ -1,23 +1,23 @@ - -# Applied Credit Note Data - -## Structure - -`AppliedCreditNoteData` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | The UID of the credit note | -| `Number` | `*string` | Optional | The number of the credit note | - -## Example (as JSON) - -```json -{ - "uid": "uid2", - "number": "number0" -} -``` - + +# Applied Credit Note Data + +## Structure + +`AppliedCreditNoteData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | The UID of the credit note | +| `Number` | `*string` | Optional | The number of the credit note | + +## Example (as JSON) + +```json +{ + "uid": "uid2", + "number": "number0" +} +``` + diff --git a/doc/models/apply-credit-note-event-data.md b/doc/models/apply-credit-note-event-data.md new file mode 100644 index 00000000..04fd1b45 --- /dev/null +++ b/doc/models/apply-credit-note-event-data.md @@ -0,0 +1,50 @@ + +# Apply Credit Note Event Data + +Example schema for an `apply_credit_note` event + +## Structure + +`ApplyCreditNoteEventData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `string` | Required | Unique identifier for the credit note application. It is generated automatically by Chargify and has the prefix "cdt_" followed by alphanumeric characters. | +| `CreditNoteNumber` | `string` | Required | A unique, identifying string that appears on the credit note and in places it is referenced. | +| `CreditNoteUid` | `string` | Required | Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. | +| `OriginalAmount` | `string` | Required | The full, original amount of the credit note. | +| `AppliedAmount` | `string` | Required | The amount of the credit note applied to invoice. | +| `TransactionTime` | `*time.Time` | Optional | The time the credit note was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" | +| `Memo` | `*string` | Optional | The credit note memo. | +| `Role` | `*string` | Optional | The role of the credit note (e.g. 'general') | +| `ConsolidatedInvoice` | `*bool` | Optional | Shows whether it was applied to consolidated invoice or not | +| `AppliedCreditNotes` | [`[]models.AppliedCreditNoteData`](../../doc/models/applied-credit-note-data.md) | Optional | List of credit notes applied to children invoices (if consolidated invoice) | + +## Example (as JSON) + +```json +{ + "uid": "uid2", + "credit_note_number": "credit_note_number4", + "credit_note_uid": "credit_note_uid4", + "original_amount": "original_amount6", + "applied_amount": "applied_amount6", + "transaction_time": "2016-03-13T12:52:32.123Z", + "memo": "memo6", + "role": "role4", + "consolidated_invoice": false, + "applied_credit_notes": [ + { + "uid": "uid4", + "number": "number8" + }, + { + "uid": "uid4", + "number": "number8" + } + ] +} +``` + diff --git a/doc/models/apply-debit-note-event-data.md b/doc/models/apply-debit-note-event-data.md new file mode 100644 index 00000000..24cdbbd0 --- /dev/null +++ b/doc/models/apply-debit-note-event-data.md @@ -0,0 +1,29 @@ + +# Apply Debit Note Event Data + +Example schema for an `apply_debit_note` event + +## Structure + +`ApplyDebitNoteEventData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `DebitNoteNumber` | `string` | Required | A unique, identifying string that appears on the debit note and in places it is referenced. | +| `DebitNoteUid` | `string` | Required | Unique identifier for the debit note. It is generated automatically by Chargify and has the prefix "db_" followed by alphanumeric characters. | +| `OriginalAmount` | `string` | Required | The full, original amount of the debit note. | +| `AppliedAmount` | `string` | Required | The amount of the debit note applied to invoice. | + +## Example (as JSON) + +```json +{ + "debit_note_number": "debit_note_number0", + "debit_note_uid": "debit_note_uid6", + "original_amount": "original_amount4", + "applied_amount": "applied_amount8" +} +``` + diff --git a/doc/models/apply-payment-event-data.md b/doc/models/apply-payment-event-data.md new file mode 100644 index 00000000..ebda7c34 --- /dev/null +++ b/doc/models/apply-payment-event-data.md @@ -0,0 +1,43 @@ + +# Apply Payment Event Data + +Example schema for an `apply_payment` event + +## Structure + +`ApplyPaymentEventData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Memo` | `string` | Required | The payment memo | +| `OriginalAmount` | `string` | Required | The full, original amount of the payment transaction as a string in full units. Incoming payments can be split amongst several invoices, which will result in a `applied_amount` less than the `original_amount`. Example: A $100.99 payment, of which $40.11 is applied to this invoice, will have an `original_amount` of `"100.99"`. | +| `AppliedAmount` | `string` | Required | The amount of the payment applied to this invoice. Incoming payments can be split amongst several invoices, which will result in a `applied_amount` less than the `original_amount`. Example: A $100.99 payment, of which $40.11 is applied to this invoice, will have an `applied_amount` of `"40.11"`. | +| `TransactionTime` | `time.Time` | Required | The time the payment was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" | +| `PaymentMethod` | [`models.InvoiceEventPayment2`](../../doc/models/containers/invoice-event-payment-2.md) | Required | A nested data structure detailing the method of payment | +| `TransactionId` | `*int` | Optional | The Chargify id of the original payment | +| `ParentInvoiceNumber` | `models.Optional[int]` | Optional | - | +| `RemainingPrepaymentAmount` | `models.Optional[string]` | Optional | - | +| `Prepayment` | `*bool` | Optional | - | +| `External` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "memo": "memo8", + "original_amount": "original_amount8", + "applied_amount": "applied_amount4", + "transaction_time": "2016-03-13T12:52:32.123Z", + "payment_method": { + "type": "apple_pay" + }, + "transaction_id": 196, + "parent_invoice_number": 174, + "remaining_prepayment_amount": "remaining_prepayment_amount6", + "prepayment": false, + "external": false +} +``` + diff --git a/doc/models/attribute-error.md b/doc/models/attribute-error.md index 19b143d4..0f9510f4 100644 --- a/doc/models/attribute-error.md +++ b/doc/models/attribute-error.md @@ -1,24 +1,24 @@ - -# Attribute Error - -## Structure - -`AttributeError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Attribute` | `[]string` | Required | - | - -## Example (as JSON) - -```json -{ - "attribute": [ - "attribute6", - "attribute7" - ] -} -``` - + +# Attribute Error + +## Structure + +`AttributeError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Attribute` | `[]string` | Required | - | + +## Example (as JSON) + +```json +{ + "attribute": [ + "attribute6", + "attribute7" + ] +} +``` + diff --git a/doc/models/auto-invite.md b/doc/models/auto-invite.md index 639b1bf0..c467ad11 100644 --- a/doc/models/auto-invite.md +++ b/doc/models/auto-invite.md @@ -1,14 +1,14 @@ - -# Auto Invite - -## Enumeration - -`AutoInvite` - -## Fields - -| Name | Description | -| --- | --- | -| `NO` | Do not send the invitation email. | -| `YES` | Automatically send the invitation email. | - + +# Auto Invite + +## Enumeration + +`AutoInvite` + +## Fields + +| Name | Description | +| --- | --- | +| `NO` | Do not send the invitation email. | +| `YES` | Automatically send the invitation email. | + diff --git a/doc/models/auto-resume.md b/doc/models/auto-resume.md index c1ef8f4e..5a5b0449 100644 --- a/doc/models/auto-resume.md +++ b/doc/models/auto-resume.md @@ -1,21 +1,21 @@ - -# Auto Resume - -## Structure - -`AutoResume` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `AutomaticallyResumeAt` | `Optional[time.Time]` | Optional | - | - -## Example (as JSON) - -```json -{ - "automatically_resume_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Auto Resume + +## Structure + +`AutoResume` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `AutomaticallyResumeAt` | `models.Optional[time.Time]` | Optional | - | + +## Example (as JSON) + +```json +{ + "automatically_resume_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/bank-account-attributes.md b/doc/models/bank-account-attributes.md index ddd3423b..b8efc523 100644 --- a/doc/models/bank-account-attributes.md +++ b/doc/models/bank-account-attributes.md @@ -1,36 +1,36 @@ - -# Bank Account Attributes - -## Structure - -`BankAccountAttributes` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ChargifyToken` | `*string` | Optional | - | -| `BankName` | `*string` | Optional | (Required when creating a subscription with ACH or GoCardless) The name of the bank where the customer’s account resides | -| `BankRoutingNumber` | `*string` | Optional | (Required when creating a subscription with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API | -| `BankAccountNumber` | `*string` | Optional | (Required when creating a subscription with ACH. Required when creating a subscription with GoCardless and bank_iban is blank) The customerʼs bank account number | -| `BankAccountType` | [`*models.BankAccountType`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking | -| `BankBranchCode` | `*string` | Optional | (Optional when creating a subscription with GoCardless) Branch code. Alternatively, an IBAN can be provided | -| `BankIban` | `*string` | Optional | (Optional when creating a subscription with GoCardless). International Bank Account Number. Alternatively, local bank details can be provided | -| `BankAccountHolderType` | [`*models.BankAccountHolderType`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | -| `PaymentType` | [`*models.PaymentType`](../../doc/models/payment-type.md) | Optional | - | -| `CurrentVault` | [`*models.BankAccountVault`](../../doc/models/bank-account-vault.md) | Optional | The vault that stores the payment profile with the provided vault_token. | -| `VaultToken` | `*string` | Optional | - | -| `CustomerVaultToken` | `*string` | Optional | (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token | - -## Example (as JSON) - -```json -{ - "chargify_token": "chargify_token0", - "bank_name": "bank_name2", - "bank_routing_number": "bank_routing_number8", - "bank_account_number": "bank_account_number4", - "bank_account_type": "checking" -} -``` - + +# Bank Account Attributes + +## Structure + +`BankAccountAttributes` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ChargifyToken` | `*string` | Optional | - | +| `BankName` | `*string` | Optional | (Required when creating a subscription with ACH or GoCardless) The name of the bank where the customer’s account resides | +| `BankRoutingNumber` | `*string` | Optional | (Required when creating a subscription with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API | +| `BankAccountNumber` | `*string` | Optional | (Required when creating a subscription with ACH. Required when creating a subscription with GoCardless and bank_iban is blank) The customerʼs bank account number | +| `BankAccountType` | [`*models.BankAccountType`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking | +| `BankBranchCode` | `*string` | Optional | (Optional when creating a subscription with GoCardless) Branch code. Alternatively, an IBAN can be provided | +| `BankIban` | `*string` | Optional | (Optional when creating a subscription with GoCardless). International Bank Account Number. Alternatively, local bank details can be provided | +| `BankAccountHolderType` | [`*models.BankAccountHolderType`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | +| `PaymentType` | [`*models.PaymentType`](../../doc/models/payment-type.md) | Optional | - | +| `CurrentVault` | [`*models.BankAccountVault`](../../doc/models/bank-account-vault.md) | Optional | The vault that stores the payment profile with the provided vault_token. | +| `VaultToken` | `*string` | Optional | - | +| `CustomerVaultToken` | `*string` | Optional | (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token | + +## Example (as JSON) + +```json +{ + "chargify_token": "chargify_token0", + "bank_name": "bank_name2", + "bank_routing_number": "bank_routing_number8", + "bank_account_number": "bank_account_number4", + "bank_account_type": "checking" +} +``` + diff --git a/doc/models/bank-account-holder-type.md b/doc/models/bank-account-holder-type.md index ebb220db..129dc3bc 100644 --- a/doc/models/bank-account-holder-type.md +++ b/doc/models/bank-account-holder-type.md @@ -1,16 +1,16 @@ - -# Bank Account Holder Type - -Defaults to personal - -## Enumeration - -`BankAccountHolderType` - -## Fields - -| Name | -| --- | -| `PERSONAL` | -| `BUSINESS` | - + +# Bank Account Holder Type + +Defaults to personal + +## Enumeration + +`BankAccountHolderType` + +## Fields + +| Name | +| --- | +| `PERSONAL` | +| `BUSINESS` | + diff --git a/doc/models/bank-account-payment-profile.md b/doc/models/bank-account-payment-profile.md index d532f136..ed436ba6 100644 --- a/doc/models/bank-account-payment-profile.md +++ b/doc/models/bank-account-payment-profile.md @@ -1,49 +1,49 @@ - -# Bank Account Payment Profile - -## Structure - -`BankAccountPaymentProfile` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | The Chargify-assigned ID of the stored bank account. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer | -| `FirstName` | `*string` | Optional | The first name of the bank account holder | -| `LastName` | `*string` | Optional | The last name of the bank account holder | -| `CustomerId` | `*int` | Optional | The Chargify-assigned id for the customer record to which the bank account belongs | -| `CurrentVault` | [`*models.BankAccountVault`](../../doc/models/bank-account-vault.md) | Optional | The vault that stores the payment profile with the provided vault_token. | -| `VaultToken` | `*string` | Optional | The “token” provided by your vault storage for an already stored payment profile | -| `BillingAddress` | `Optional[string]` | Optional | The current billing street address for the bank account | -| `BillingCity` | `Optional[string]` | Optional | The current billing address city for the bank account | -| `BillingState` | `Optional[string]` | Optional | The current billing address state for the bank account | -| `BillingZip` | `Optional[string]` | Optional | The current billing address zip code for the bank account | -| `BillingCountry` | `Optional[string]` | Optional | The current billing address country for the bank account | -| `CustomerVaultToken` | `Optional[string]` | Optional | (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. | -| `BillingAddress2` | `Optional[string]` | Optional | The current billing street address, second line, for the bank account | -| `BankName` | `*string` | Optional | The bank where the account resides | -| `MaskedBankRoutingNumber` | `string` | Required | A string representation of the stored bank routing number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’). payment_type will be bank_account | -| `MaskedBankAccountNumber` | `string` | Required | A string representation of the stored bank account number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’) | -| `BankAccountType` | [`*models.BankAccountType`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking | -| `BankAccountHolderType` | [`*models.BankAccountHolderType`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | -| `PaymentType` | [`*models.PaymentType`](../../doc/models/payment-type.md) | Optional | - | -| `Verified` | `*bool` | Optional | denotes whether a bank account has been verified by providing the amounts of two small deposits made into the account
**Default**: `false` | -| `SiteGatewaySettingId` | `Optional[int]` | Optional | - | -| `GatewayHandle` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "masked_bank_routing_number": "masked_bank_routing_number8", - "masked_bank_account_number": "masked_bank_account_number8", - "verified": false, - "id": 188, - "first_name": "first_name6", - "last_name": "last_name4", - "customer_id": 226, - "current_vault": "authorizenet" -} -``` - + +# Bank Account Payment Profile + +## Structure + +`BankAccountPaymentProfile` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | The Chargify-assigned ID of the stored bank account. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer | +| `FirstName` | `*string` | Optional | The first name of the bank account holder | +| `LastName` | `*string` | Optional | The last name of the bank account holder | +| `CustomerId` | `*int` | Optional | The Chargify-assigned id for the customer record to which the bank account belongs | +| `CurrentVault` | [`*models.BankAccountVault`](../../doc/models/bank-account-vault.md) | Optional | The vault that stores the payment profile with the provided vault_token. | +| `VaultToken` | `*string` | Optional | The “token” provided by your vault storage for an already stored payment profile | +| `BillingAddress` | `models.Optional[string]` | Optional | The current billing street address for the bank account | +| `BillingCity` | `models.Optional[string]` | Optional | The current billing address city for the bank account | +| `BillingState` | `models.Optional[string]` | Optional | The current billing address state for the bank account | +| `BillingZip` | `models.Optional[string]` | Optional | The current billing address zip code for the bank account | +| `BillingCountry` | `models.Optional[string]` | Optional | The current billing address country for the bank account | +| `CustomerVaultToken` | `models.Optional[string]` | Optional | (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. | +| `BillingAddress2` | `models.Optional[string]` | Optional | The current billing street address, second line, for the bank account | +| `BankName` | `*string` | Optional | The bank where the account resides | +| `MaskedBankRoutingNumber` | `string` | Required | A string representation of the stored bank routing number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’). payment_type will be bank_account | +| `MaskedBankAccountNumber` | `string` | Required | A string representation of the stored bank account number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’) | +| `BankAccountType` | [`*models.BankAccountType`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking | +| `BankAccountHolderType` | [`*models.BankAccountHolderType`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | +| `PaymentType` | [`*models.PaymentType`](../../doc/models/payment-type.md) | Optional | - | +| `Verified` | `*bool` | Optional | denotes whether a bank account has been verified by providing the amounts of two small deposits made into the account
**Default**: `false` | +| `SiteGatewaySettingId` | `models.Optional[int]` | Optional | - | +| `GatewayHandle` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "masked_bank_routing_number": "masked_bank_routing_number8", + "masked_bank_account_number": "masked_bank_account_number8", + "verified": false, + "id": 188, + "first_name": "first_name6", + "last_name": "last_name4", + "customer_id": 226, + "current_vault": "authorizenet" +} +``` + diff --git a/doc/models/bank-account-response.md b/doc/models/bank-account-response.md index 965d2818..b92b9774 100644 --- a/doc/models/bank-account-response.md +++ b/doc/models/bank-account-response.md @@ -1,30 +1,30 @@ - -# Bank Account Response - -## Structure - -`BankAccountResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PaymentProfile` | [`models.BankAccountPaymentProfile`](../../doc/models/bank-account-payment-profile.md) | Required | - | - -## Example (as JSON) - -```json -{ - "payment_profile": { - "masked_bank_routing_number": "masked_bank_routing_number0", - "masked_bank_account_number": "masked_bank_account_number6", - "verified": false, - "id": 44, - "first_name": "first_name4", - "last_name": "last_name2", - "customer_id": 82, - "current_vault": "gocardless" - } -} -``` - + +# Bank Account Response + +## Structure + +`BankAccountResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PaymentProfile` | [`models.BankAccountPaymentProfile`](../../doc/models/bank-account-payment-profile.md) | Required | - | + +## Example (as JSON) + +```json +{ + "payment_profile": { + "masked_bank_routing_number": "masked_bank_routing_number0", + "masked_bank_account_number": "masked_bank_account_number6", + "verified": false, + "id": 44, + "first_name": "first_name4", + "last_name": "last_name2", + "customer_id": 82, + "current_vault": "gocardless" + } +} +``` + diff --git a/doc/models/bank-account-type.md b/doc/models/bank-account-type.md index 8bbb5ed2..86a4b637 100644 --- a/doc/models/bank-account-type.md +++ b/doc/models/bank-account-type.md @@ -1,16 +1,16 @@ - -# Bank Account Type - -Defaults to checking - -## Enumeration - -`BankAccountType` - -## Fields - -| Name | -| --- | -| `CHECKING` | -| `SAVINGS` | - + +# Bank Account Type + +Defaults to checking + +## Enumeration + +`BankAccountType` + +## Fields + +| Name | +| --- | +| `CHECKING` | +| `SAVINGS` | + diff --git a/doc/models/bank-account-vault.md b/doc/models/bank-account-vault.md index f4b8850c..bfbce7bf 100644 --- a/doc/models/bank-account-vault.md +++ b/doc/models/bank-account-vault.md @@ -1,19 +1,19 @@ - -# Bank Account Vault - -The vault that stores the payment profile with the provided vault_token. - -## Enumeration - -`BankAccountVault` - -## Fields - -| Name | -| --- | -| `BOGUS` | -| `AUTHORIZENET` | -| `STRIPECONNECT` | -| `BRAINTREEBLUE` | -| `GOCARDLESS` | - + +# Bank Account Vault + +The vault that stores the payment profile with the provided vault_token. + +## Enumeration + +`BankAccountVault` + +## Fields + +| Name | +| --- | +| `BOGUS` | +| `AUTHORIZENET` | +| `STRIPECONNECT` | +| `BRAINTREEBLUE` | +| `GOCARDLESS` | + diff --git a/doc/models/bank-account-verification-request.md b/doc/models/bank-account-verification-request.md index dfcbbf3b..08a5646f 100644 --- a/doc/models/bank-account-verification-request.md +++ b/doc/models/bank-account-verification-request.md @@ -1,24 +1,24 @@ - -# Bank Account Verification Request - -## Structure - -`BankAccountVerificationRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `BankAccountVerification` | [`models.BankAccountVerification`](../../doc/models/bank-account-verification.md) | Required | - | - -## Example (as JSON) - -```json -{ - "bank_account_verification": { - "deposit_1_in_cents": 244, - "deposit_2_in_cents": 6 - } -} -``` - + +# Bank Account Verification Request + +## Structure + +`BankAccountVerificationRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `BankAccountVerification` | [`models.BankAccountVerification`](../../doc/models/bank-account-verification.md) | Required | - | + +## Example (as JSON) + +```json +{ + "bank_account_verification": { + "deposit_1_in_cents": 244, + "deposit_2_in_cents": 6 + } +} +``` + diff --git a/doc/models/bank-account-verification.md b/doc/models/bank-account-verification.md index ef670f78..7e595ecd 100644 --- a/doc/models/bank-account-verification.md +++ b/doc/models/bank-account-verification.md @@ -1,23 +1,23 @@ - -# Bank Account Verification - -## Structure - -`BankAccountVerification` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Deposit1InCents` | `*int64` | Optional | - | -| `Deposit2InCents` | `*int64` | Optional | - | - -## Example (as JSON) - -```json -{ - "deposit_1_in_cents": 142, - "deposit_2_in_cents": 132 -} -``` - + +# Bank Account Verification + +## Structure + +`BankAccountVerification` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Deposit1InCents` | `*int64` | Optional | - | +| `Deposit2InCents` | `*int64` | Optional | - | + +## Example (as JSON) + +```json +{ + "deposit_1_in_cents": 142, + "deposit_2_in_cents": 132 +} +``` + diff --git a/doc/models/base-refund-error.md b/doc/models/base-refund-error.md index a83468aa..3416a4d3 100644 --- a/doc/models/base-refund-error.md +++ b/doc/models/base-refund-error.md @@ -1,34 +1,34 @@ - -# Base Refund Error - -## Structure - -`BaseRefundError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Base` | `[]interface{}` | Optional | - | - -## Example (as JSON) - -```json -{ - "base": [ - { - "key1": "val1", - "key2": "val2" - }, - { - "key1": "val1", - "key2": "val2" - }, - { - "key1": "val1", - "key2": "val2" - } - ] -} -``` - + +# Base Refund Error + +## Structure + +`BaseRefundError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Base` | `[]interface{}` | Optional | - | + +## Example (as JSON) + +```json +{ + "base": [ + { + "key1": "val1", + "key2": "val2" + }, + { + "key1": "val1", + "key2": "val2" + }, + { + "key1": "val1", + "key2": "val2" + } + ] +} +``` + diff --git a/doc/models/base-string-error.md b/doc/models/base-string-error.md index eada7dcc..bda3a9b7 100644 --- a/doc/models/base-string-error.md +++ b/doc/models/base-string-error.md @@ -1,25 +1,25 @@ - -# Base String Error - -The error is base if it is not directly associated with a single attribute. - -## Structure - -`BaseStringError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Base` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "base": [ - "base3" - ] -} -``` - + +# Base String Error + +The error is base if it is not directly associated with a single attribute. + +## Structure + +`BaseStringError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Base` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "base": [ + "base3" + ] +} +``` + diff --git a/doc/models/basic-date-field.md b/doc/models/basic-date-field.md index 38fc4f76..138377f1 100644 --- a/doc/models/basic-date-field.md +++ b/doc/models/basic-date-field.md @@ -1,22 +1,22 @@ - -# Basic Date Field - -Allows to filter by `created_at` or `updated_at`. - -## Enumeration - -`BasicDateField` - -## Fields - -| Name | -| --- | -| `UPDATEDAT` | -| `CREATEDAT` | - -## Example - -``` -updated_at -``` - + +# Basic Date Field + +Allows to filter by `created_at` or `updated_at`. + +## Enumeration + +`BasicDateField` + +## Fields + +| Name | +| --- | +| `UPDATEDAT` | +| `CREATEDAT` | + +## Example + +``` +updated_at +``` + diff --git a/doc/models/batch-job-response.md b/doc/models/batch-job-response.md index cc4374ed..82d7adae 100644 --- a/doc/models/batch-job-response.md +++ b/doc/models/batch-job-response.md @@ -1,27 +1,27 @@ - -# Batch Job Response - -## Structure - -`BatchJobResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Batchjob` | [`models.BatchJob`](../../doc/models/batch-job.md) | Required | - | - -## Example (as JSON) - -```json -{ - "batchjob": { - "id": 54, - "finished_at": "2016-03-13T12:52:32.123Z", - "row_count": 62, - "created_at": "2016-03-13T12:52:32.123Z", - "completed": "completed4" - } -} -``` - + +# Batch Job Response + +## Structure + +`BatchJobResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Batchjob` | [`models.BatchJob`](../../doc/models/batch-job.md) | Required | - | + +## Example (as JSON) + +```json +{ + "batchjob": { + "id": 54, + "finished_at": "2016-03-13T12:52:32.123Z", + "row_count": 62, + "created_at": "2016-03-13T12:52:32.123Z", + "completed": "completed4" + } +} +``` + diff --git a/doc/models/batch-job.md b/doc/models/batch-job.md index 8f4d606c..8e7869fe 100644 --- a/doc/models/batch-job.md +++ b/doc/models/batch-job.md @@ -1,29 +1,29 @@ - -# Batch Job - -## Structure - -`BatchJob` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `FinishedAt` | `Optional[time.Time]` | Optional | - | -| `RowCount` | `Optional[int]` | Optional | - | -| `CreatedAt` | `Optional[time.Time]` | Optional | - | -| `Completed` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 246, - "finished_at": "2016-03-13T12:52:32.123Z", - "row_count": 254, - "created_at": "2016-03-13T12:52:32.123Z", - "completed": "completed0" -} -``` - + +# Batch Job + +## Structure + +`BatchJob` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `FinishedAt` | `models.Optional[time.Time]` | Optional | - | +| `RowCount` | `models.Optional[int]` | Optional | - | +| `CreatedAt` | `models.Optional[time.Time]` | Optional | - | +| `Completed` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 246, + "finished_at": "2016-03-13T12:52:32.123Z", + "row_count": 254, + "created_at": "2016-03-13T12:52:32.123Z", + "completed": "completed0" +} +``` + diff --git a/doc/models/billing-address.md b/doc/models/billing-address.md index 6200eec0..a3a53b7d 100644 --- a/doc/models/billing-address.md +++ b/doc/models/billing-address.md @@ -1,30 +1,30 @@ - -# Billing Address - -## Structure - -`BillingAddress` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Street` | `Optional[string]` | Optional | - | -| `Line2` | `Optional[string]` | Optional | - | -| `City` | `Optional[string]` | Optional | - | -| `State` | `Optional[string]` | Optional | - | -| `Zip` | `Optional[string]` | Optional | - | -| `Country` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "street": "street6", - "line2": "line20", - "city": "city6", - "state": "state2", - "zip": "zip0" -} -``` - + +# Billing Address + +## Structure + +`BillingAddress` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Street` | `models.Optional[string]` | Optional | - | +| `Line2` | `models.Optional[string]` | Optional | - | +| `City` | `models.Optional[string]` | Optional | - | +| `State` | `models.Optional[string]` | Optional | - | +| `Zip` | `models.Optional[string]` | Optional | - | +| `Country` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "street": "street6", + "line2": "line20", + "city": "city6", + "state": "state2", + "zip": "zip0" +} +``` + diff --git a/doc/models/billing-manifest-item.md b/doc/models/billing-manifest-item.md index 44db9885..539bc03f 100644 --- a/doc/models/billing-manifest-item.md +++ b/doc/models/billing-manifest-item.md @@ -1,38 +1,38 @@ - -# Billing Manifest Item - -## Structure - -`BillingManifestItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TransactionType` | [`*models.LineItemTransactionType`](../../doc/models/line-item-transaction-type.md) | Optional | A handle for the line item transaction type | -| `Kind` | [`*models.BillingManifestLineItemKind`](../../doc/models/billing-manifest-line-item-kind.md) | Optional | A handle for the billing manifest line item kind | -| `AmountInCents` | `*int64` | Optional | - | -| `Memo` | `*string` | Optional | - | -| `DiscountAmountInCents` | `*int64` | Optional | - | -| `TaxableAmountInCents` | `*int64` | Optional | - | -| `ComponentId` | `*int` | Optional | - | -| `ComponentHandle` | `*string` | Optional | - | -| `ComponentName` | `*string` | Optional | - | -| `ProductId` | `*int` | Optional | - | -| `ProductHandle` | `*string` | Optional | - | -| `ProductName` | `*string` | Optional | - | -| `PeriodRangeStart` | `*string` | Optional | - | -| `PeriodRangeEnd` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "transaction_type": "info_transaction", - "kind": "baseline", - "amount_in_cents": 216, - "memo": "memo4", - "discount_amount_in_cents": 236 -} -``` - + +# Billing Manifest Item + +## Structure + +`BillingManifestItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TransactionType` | [`*models.LineItemTransactionType`](../../doc/models/line-item-transaction-type.md) | Optional | A handle for the line item transaction type | +| `Kind` | [`*models.BillingManifestLineItemKind`](../../doc/models/billing-manifest-line-item-kind.md) | Optional | A handle for the billing manifest line item kind | +| `AmountInCents` | `*int64` | Optional | - | +| `Memo` | `*string` | Optional | - | +| `DiscountAmountInCents` | `*int64` | Optional | - | +| `TaxableAmountInCents` | `*int64` | Optional | - | +| `ComponentId` | `*int` | Optional | - | +| `ComponentHandle` | `*string` | Optional | - | +| `ComponentName` | `*string` | Optional | - | +| `ProductId` | `*int` | Optional | - | +| `ProductHandle` | `*string` | Optional | - | +| `ProductName` | `*string` | Optional | - | +| `PeriodRangeStart` | `*string` | Optional | - | +| `PeriodRangeEnd` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "transaction_type": "info_transaction", + "kind": "baseline", + "amount_in_cents": 216, + "memo": "memo4", + "discount_amount_in_cents": 236 +} +``` + diff --git a/doc/models/billing-manifest-line-item-kind.md b/doc/models/billing-manifest-line-item-kind.md index 270c00b8..1f99b4e3 100644 --- a/doc/models/billing-manifest-line-item-kind.md +++ b/doc/models/billing-manifest-line-item-kind.md @@ -1,20 +1,20 @@ - -# Billing Manifest Line Item Kind - -A handle for the billing manifest line item kind - -## Enumeration - -`BillingManifestLineItemKind` - -## Fields - -| Name | -| --- | -| `BASELINE` | -| `INITIAL` | -| `TRIAL` | -| `COUPON` | -| `COMPONENT` | -| `TAX` | - + +# Billing Manifest Line Item Kind + +A handle for the billing manifest line item kind + +## Enumeration + +`BillingManifestLineItemKind` + +## Fields + +| Name | +| --- | +| `BASELINE` | +| `INITIAL` | +| `TRIAL` | +| `COUPON` | +| `COMPONENT` | +| `TAX` | + diff --git a/doc/models/billing-manifest.md b/doc/models/billing-manifest.md index 43ba074c..e7fccb2b 100644 --- a/doc/models/billing-manifest.md +++ b/doc/models/billing-manifest.md @@ -1,55 +1,55 @@ - -# Billing Manifest - -## Structure - -`BillingManifest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `LineItems` | [`[]models.BillingManifestItem`](../../doc/models/billing-manifest-item.md) | Optional | - | -| `TotalInCents` | `*int64` | Optional | - | -| `TotalDiscountInCents` | `*int64` | Optional | - | -| `TotalTaxInCents` | `*int64` | Optional | - | -| `SubtotalInCents` | `*int64` | Optional | - | -| `StartDate` | `*time.Time` | Optional | - | -| `EndDate` | `*time.Time` | Optional | - | -| `PeriodType` | `*string` | Optional | - | -| `ExistingBalanceInCents` | `*int64` | Optional | - | - -## Example (as JSON) - -```json -{ - "line_items": [ - { - "transaction_type": "credit", - "kind": "component", - "amount_in_cents": 24, - "memo": "memo2", - "discount_amount_in_cents": 172 - }, - { - "transaction_type": "credit", - "kind": "component", - "amount_in_cents": 24, - "memo": "memo2", - "discount_amount_in_cents": 172 - }, - { - "transaction_type": "credit", - "kind": "component", - "amount_in_cents": 24, - "memo": "memo2", - "discount_amount_in_cents": 172 - } - ], - "total_in_cents": 192, - "total_discount_in_cents": 178, - "total_tax_in_cents": 172, - "subtotal_in_cents": 48 -} -``` - + +# Billing Manifest + +## Structure + +`BillingManifest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `LineItems` | [`[]models.BillingManifestItem`](../../doc/models/billing-manifest-item.md) | Optional | - | +| `TotalInCents` | `*int64` | Optional | - | +| `TotalDiscountInCents` | `*int64` | Optional | - | +| `TotalTaxInCents` | `*int64` | Optional | - | +| `SubtotalInCents` | `*int64` | Optional | - | +| `StartDate` | `*time.Time` | Optional | - | +| `EndDate` | `*time.Time` | Optional | - | +| `PeriodType` | `*string` | Optional | - | +| `ExistingBalanceInCents` | `*int64` | Optional | - | + +## Example (as JSON) + +```json +{ + "line_items": [ + { + "transaction_type": "credit", + "kind": "component", + "amount_in_cents": 24, + "memo": "memo2", + "discount_amount_in_cents": 172 + }, + { + "transaction_type": "credit", + "kind": "component", + "amount_in_cents": 24, + "memo": "memo2", + "discount_amount_in_cents": 172 + }, + { + "transaction_type": "credit", + "kind": "component", + "amount_in_cents": 24, + "memo": "memo2", + "discount_amount_in_cents": 172 + } + ], + "total_in_cents": 192, + "total_discount_in_cents": 178, + "total_tax_in_cents": 172, + "subtotal_in_cents": 48 +} +``` + diff --git a/doc/models/billing-schedule.md b/doc/models/billing-schedule.md index 40ba4091..3baf55f0 100644 --- a/doc/models/billing-schedule.md +++ b/doc/models/billing-schedule.md @@ -1,23 +1,23 @@ - -# Billing Schedule - -This attribute is particularly useful when you need to align billing events for different components on distinct schedules within a subscription. Please note this only works for site with Multifrequency enabled - -## Structure - -`BillingSchedule` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `InitialBillingAt` | `*time.Time` | Optional | The initial_billing_at attribute in Maxio allows you to specify a custom starting date for billing cycles associated with components that have their own billing frequency set. Only ISO8601 format is supported. | - -## Example (as JSON) - -```json -{ - "initial_billing_at": "2024-01-01" -} -``` - + +# Billing Schedule + +This attribute is particularly useful when you need to align billing events for different components on distinct schedules within a subscription. Please note this only works for site with Multifrequency enabled + +## Structure + +`BillingSchedule` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `InitialBillingAt` | `*time.Time` | Optional | The initial_billing_at attribute in Maxio allows you to specify a custom starting date for billing cycles associated with components that have their own billing frequency set. Only ISO8601 format is supported. | + +## Example (as JSON) + +```json +{ + "initial_billing_at": "2024-01-01" +} +``` + diff --git a/doc/models/breakouts.md b/doc/models/breakouts.md index fde46c3c..5ff93445 100644 --- a/doc/models/breakouts.md +++ b/doc/models/breakouts.md @@ -1,27 +1,27 @@ - -# Breakouts - -## Structure - -`Breakouts` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PlanAmountInCents` | `*int64` | Optional | - | -| `PlanAmountFormatted` | `*string` | Optional | - | -| `UsageAmountInCents` | `*int64` | Optional | - | -| `UsageAmountFormatted` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "plan_amount_in_cents": 68, - "plan_amount_formatted": "plan_amount_formatted2", - "usage_amount_in_cents": 176, - "usage_amount_formatted": "usage_amount_formatted0" -} -``` - + +# Breakouts + +## Structure + +`Breakouts` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PlanAmountInCents` | `*int64` | Optional | - | +| `PlanAmountFormatted` | `*string` | Optional | - | +| `UsageAmountInCents` | `*int64` | Optional | - | +| `UsageAmountFormatted` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "plan_amount_in_cents": 68, + "plan_amount_formatted": "plan_amount_formatted2", + "usage_amount_in_cents": 176, + "usage_amount_formatted": "usage_amount_formatted0" +} +``` + diff --git a/doc/models/bulk-components-price-point-assignment.md b/doc/models/bulk-components-price-point-assignment.md index 67fa646d..9aef8152 100644 --- a/doc/models/bulk-components-price-point-assignment.md +++ b/doc/models/bulk-components-price-point-assignment.md @@ -1,29 +1,26 @@ - -# Bulk Components Price Point Assignment - -## Structure - -`BulkComponentsPricePointAssignment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Components` | [`[]models.ComponentPricePointAssignment`](../../doc/models/component-price-point-assignment.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "components": [ - { - "component_id": 108, - "price_point": { - "key1": "val1", - "key2": "val2" - } - } - ] -} -``` - + +# Bulk Components Price Point Assignment + +## Structure + +`BulkComponentsPricePointAssignment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Components` | [`[]models.ComponentPricePointAssignment`](../../doc/models/component-price-point-assignment.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "components": [ + { + "component_id": 108, + "price_point": "String5" + } + ] +} +``` + diff --git a/doc/models/bulk-create-product-price-points-request.md b/doc/models/bulk-create-product-price-points-request.md index 3ade444b..b76c2527 100644 --- a/doc/models/bulk-create-product-price-points-request.md +++ b/doc/models/bulk-create-product-price-points-request.md @@ -1,34 +1,34 @@ - -# Bulk Create Product Price Points Request - -## Structure - -`BulkCreateProductPricePointsRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoints` | [`[]models.CreateProductPricePoint`](../../doc/models/create-product-price-point.md) | Required | - | - -## Example (as JSON) - -```json -{ - "price_points": [ - { - "name": "name2", - "price_in_cents": 108, - "interval": 92, - "interval_unit": "day", - "use_site_exchange_rate": true, - "handle": "handle8", - "trial_price_in_cents": 196, - "trial_interval": 250, - "trial_interval_unit": "day", - "trial_type": "trial_type6" - } - ] -} -``` - + +# Bulk Create Product Price Points Request + +## Structure + +`BulkCreateProductPricePointsRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoints` | [`[]models.CreateProductPricePoint`](../../doc/models/create-product-price-point.md) | Required | - | + +## Example (as JSON) + +```json +{ + "price_points": [ + { + "name": "name2", + "price_in_cents": 108, + "interval": 92, + "interval_unit": "day", + "use_site_exchange_rate": true, + "handle": "handle8", + "trial_price_in_cents": 196, + "trial_interval": 250, + "trial_interval_unit": "day", + "trial_type": "trial_type6" + } + ] +} +``` + diff --git a/doc/models/bulk-create-product-price-points-response.md b/doc/models/bulk-create-product-price-points-response.md index 83f8a618..a23ba4dd 100644 --- a/doc/models/bulk-create-product-price-points-response.md +++ b/doc/models/bulk-create-product-price-points-response.md @@ -1,29 +1,29 @@ - -# Bulk Create Product Price Points Response - -## Structure - -`BulkCreateProductPricePointsResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoints` | [`[]models.ProductPricePoint`](../../doc/models/product-price-point.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "price_points": [ - { - "id": 40, - "name": "name2", - "handle": "handle8", - "price_in_cents": 108, - "interval": 92 - } - ] -} -``` - + +# Bulk Create Product Price Points Response + +## Structure + +`BulkCreateProductPricePointsResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoints` | [`[]models.ProductPricePoint`](../../doc/models/product-price-point.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "price_points": [ + { + "id": 40, + "name": "name2", + "handle": "handle8", + "price_in_cents": 108, + "interval": 92 + } + ] +} +``` + diff --git a/doc/models/bulk-create-segments.md b/doc/models/bulk-create-segments.md index f95732d3..a6e1c92e 100644 --- a/doc/models/bulk-create-segments.md +++ b/doc/models/bulk-create-segments.md @@ -1,67 +1,46 @@ - -# Bulk Create Segments - -## Structure - -`BulkCreateSegments` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Segments` | [`[]models.CreateSegment`](../../doc/models/create-segment.md) | Optional | **Constraints**: *Maximum Items*: `2000` | - -## Example (as JSON) - -```json -{ - "segments": [ - { - "segment_property_1_value": { - "key1": "val1", - "key2": "val2" - }, - "segment_property_2_value": { - "key1": "val1", - "key2": "val2" - }, - "segment_property_3_value": { - "key1": "val1", - "key2": "val2" - }, - "segment_property_4_value": { - "key1": "val1", - "key2": "val2" - }, - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - } - ] -} -``` - + +# Bulk Create Segments + +## Structure + +`BulkCreateSegments` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Segments` | [`[]models.CreateSegment`](../../doc/models/create-segment.md) | Optional | **Constraints**: *Maximum Items*: `2000` | + +## Example (as JSON) + +```json +{ + "segments": [ + { + "segment_property_1_value": "String3", + "segment_property_2_value": "String5", + "segment_property_3_value": "String3", + "segment_property_4_value": "String7", + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + } + ] + } + ] +} +``` + diff --git a/doc/models/bulk-update-segments-item.md b/doc/models/bulk-update-segments-item.md index d33895be..39093d88 100644 --- a/doc/models/bulk-update-segments-item.md +++ b/doc/models/bulk-update-segments-item.md @@ -1,34 +1,31 @@ - -# Bulk Update Segments Item - -## Structure - -`BulkUpdateSegmentsItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `int` | Required | The ID of the segment you want to update. | -| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Prices` | [`[]models.CreateOrUpdateSegmentPrice`](../../doc/models/create-or-update-segment-price.md) | Required | - | - -## Example (as JSON) - -```json -{ - "id": 180, - "pricing_scheme": "per_unit", - "prices": [ - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] -} -``` - + +# Bulk Update Segments Item + +## Structure + +`BulkUpdateSegmentsItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `int` | Required | The ID of the segment you want to update. | +| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.CreateOrUpdateSegmentPrice`](../../doc/models/create-or-update-segment-price.md) | Required | - | + +## Example (as JSON) + +```json +{ + "id": 180, + "pricing_scheme": "per_unit", + "prices": [ + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + } + ] +} +``` + diff --git a/doc/models/bulk-update-segments.md b/doc/models/bulk-update-segments.md index 85ecc5c8..e7e436fb 100644 --- a/doc/models/bulk-update-segments.md +++ b/doc/models/bulk-update-segments.md @@ -1,82 +1,64 @@ - -# Bulk Update Segments - -## Structure - -`BulkUpdateSegments` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Segments` | [`[]models.BulkUpdateSegmentsItem`](../../doc/models/bulk-update-segments-item.md) | Optional | **Constraints**: *Maximum Items*: `1000` | - -## Example (as JSON) - -```json -{ - "segments": [ - { - "id": 50, - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - }, - { - "id": 50, - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - } - ] -} -``` - + +# Bulk Update Segments + +## Structure + +`BulkUpdateSegments` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Segments` | [`[]models.BulkUpdateSegmentsItem`](../../doc/models/bulk-update-segments-item.md) | Optional | **Constraints**: *Maximum Items*: `1000` | + +## Example (as JSON) + +```json +{ + "segments": [ + { + "id": 50, + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + } + ] + }, + { + "id": 50, + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + } + ] + } + ] +} +``` + diff --git a/doc/models/calendar-billing.md b/doc/models/calendar-billing.md index 2f8a9497..7795e695 100644 --- a/doc/models/calendar-billing.md +++ b/doc/models/calendar-billing.md @@ -1,28 +1,25 @@ - -# Calendar Billing - -(Optional). Cannot be used when also specifying next_billing_at - -## Structure - -`CalendarBilling` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SnapDay` | `*interface{}` | Optional | A day of month that subscription will be processed on. Can be 1 up to 28 or 'end'. | -| `CalendarBillingFirstCharge` | [`*models.FirstChargeType`](../../doc/models/first-charge-type.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "snap_day": { - "key1": "val1", - "key2": "val2" - }, - "calendar_billing_first_charge": "prorated" -} -``` - + +# Calendar Billing + +(Optional). Cannot be used when also specifying next_billing_at + +## Structure + +`CalendarBilling` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SnapDay` | [`*models.CalendarBillingSnapDay`](../../doc/models/containers/calendar-billing-snap-day.md) | Optional | This is a container for one-of cases. | +| `CalendarBillingFirstCharge` | [`*models.FirstChargeType`](../../doc/models/first-charge-type.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "snap_day": 210, + "calendar_billing_first_charge": "prorated" +} +``` + diff --git a/doc/models/cancel-grouped-subscriptions-request.md b/doc/models/cancel-grouped-subscriptions-request.md index 3e7ea341..ac2c871f 100644 --- a/doc/models/cancel-grouped-subscriptions-request.md +++ b/doc/models/cancel-grouped-subscriptions-request.md @@ -1,21 +1,21 @@ - -# Cancel Grouped Subscriptions Request - -## Structure - -`CancelGroupedSubscriptionsRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ChargeUnbilledUsage` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "charge_unbilled_usage": false -} -``` - + +# Cancel Grouped Subscriptions Request + +## Structure + +`CancelGroupedSubscriptionsRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ChargeUnbilledUsage` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "charge_unbilled_usage": false +} +``` + diff --git a/doc/models/cancellation-method.md b/doc/models/cancellation-method.md index 62bfc38f..a2ba3621 100644 --- a/doc/models/cancellation-method.md +++ b/doc/models/cancellation-method.md @@ -1,19 +1,19 @@ - -# Cancellation Method - -The process used to cancel the subscription, if the subscription has been canceled. It is nil if the subscription's state is not canceled. - -## Enumeration - -`CancellationMethod` - -## Fields - -| Name | -| --- | -| `MERCHANTUI` | -| `MERCHANTAPI` | -| `DUNNING` | -| `BILLINGPORTAL` | -| `UNKNOWN` | - + +# Cancellation Method + +The process used to cancel the subscription, if the subscription has been canceled. It is nil if the subscription's state is not canceled. + +## Enumeration + +`CancellationMethod` + +## Fields + +| Name | +| --- | +| `MERCHANTUI` | +| `MERCHANTAPI` | +| `DUNNING` | +| `BILLINGPORTAL` | +| `UNKNOWN` | + diff --git a/doc/models/cancellation-options.md b/doc/models/cancellation-options.md index 162c0791..abd5ef25 100644 --- a/doc/models/cancellation-options.md +++ b/doc/models/cancellation-options.md @@ -1,23 +1,23 @@ - -# Cancellation Options - -## Structure - -`CancellationOptions` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CancellationMessage` | `*string` | Optional | For your internal use. An indication as to why the subscription is being canceled. | -| `ReasonCode` | `*string` | Optional | The reason code associated with the cancellation. See the list of reason codes associated with your site. | - -## Example (as JSON) - -```json -{ - "cancellation_message": "cancellation_message0", - "reason_code": "reason_code6" -} -``` - + +# Cancellation Options + +## Structure + +`CancellationOptions` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CancellationMessage` | `*string` | Optional | For your internal use. An indication as to why the subscription is being canceled. | +| `ReasonCode` | `*string` | Optional | The reason code associated with the cancellation. See the list of reason codes associated with your site. | + +## Example (as JSON) + +```json +{ + "cancellation_message": "cancellation_message0", + "reason_code": "reason_code6" +} +``` + diff --git a/doc/models/cancellation-request.md b/doc/models/cancellation-request.md index c48c77f2..dc0627a4 100644 --- a/doc/models/cancellation-request.md +++ b/doc/models/cancellation-request.md @@ -1,24 +1,24 @@ - -# Cancellation Request - -## Structure - -`CancellationRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Subscription` | [`models.CancellationOptions`](../../doc/models/cancellation-options.md) | Required | - | - -## Example (as JSON) - -```json -{ - "subscription": { - "cancellation_message": "cancellation_message2", - "reason_code": "reason_code8" - } -} -``` - + +# Cancellation Request + +## Structure + +`CancellationRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Subscription` | [`models.CancellationOptions`](../../doc/models/cancellation-options.md) | Required | - | + +## Example (as JSON) + +```json +{ + "subscription": { + "cancellation_message": "cancellation_message2", + "reason_code": "reason_code8" + } +} +``` + diff --git a/doc/models/card-type.md b/doc/models/card-type.md index 4ae44cca..2929f9b0 100644 --- a/doc/models/card-type.md +++ b/doc/models/card-type.md @@ -1,50 +1,50 @@ - -# Card Type - -The type of card used. - -## Enumeration - -`CardType` - -## Fields - -| Name | -| --- | -| `VISA` | -| `MASTER` | -| `ELO` | -| `CABAL` | -| `ALELO` | -| `DISCOVER` | -| `AMERICANEXPRESS` | -| `NARANJA` | -| `DINERSCLUB` | -| `JCB` | -| `DANKORT` | -| `MAESTRO` | -| `MAESTRONOLUHN` | -| `FORBRUGSFORENINGEN` | -| `SODEXO` | -| `ALIA` | -| `VR` | -| `UNIONPAY` | -| `CARNET` | -| `CARTESBANCAIRES` | -| `OLIMPICA` | -| `CREDITEL` | -| `CONFIABLE` | -| `SYNCHRONY` | -| `ROUTEX` | -| `MADA` | -| `BPPLUS` | -| `PASSCARD` | -| `EDENRED` | -| `ANDA` | -| `TARJETAD` | -| `HIPERCARD` | -| `BOGUS` | -| `ENUMSWITCH` | -| `SOLO` | -| `LASER` | - + +# Card Type + +The type of card used. + +## Enumeration + +`CardType` + +## Fields + +| Name | +| --- | +| `VISA` | +| `MASTER` | +| `ELO` | +| `CABAL` | +| `ALELO` | +| `DISCOVER` | +| `AMERICANEXPRESS` | +| `NARANJA` | +| `DINERSCLUB` | +| `JCB` | +| `DANKORT` | +| `MAESTRO` | +| `MAESTRONOLUHN` | +| `FORBRUGSFORENINGEN` | +| `SODEXO` | +| `ALIA` | +| `VR` | +| `UNIONPAY` | +| `CARNET` | +| `CARTESBANCAIRES` | +| `OLIMPICA` | +| `CREDITEL` | +| `CONFIABLE` | +| `SYNCHRONY` | +| `ROUTEX` | +| `MADA` | +| `BPPLUS` | +| `PASSCARD` | +| `EDENRED` | +| `ANDA` | +| `TARJETAD` | +| `HIPERCARD` | +| `BOGUS` | +| `ENUMSWITCH` | +| `SOLO` | +| `LASER` | + diff --git a/doc/models/change-invoice-collection-method-event-data.md b/doc/models/change-invoice-collection-method-event-data.md new file mode 100644 index 00000000..739d8dcf --- /dev/null +++ b/doc/models/change-invoice-collection-method-event-data.md @@ -0,0 +1,25 @@ + +# Change Invoice Collection Method Event Data + +Example schema for an `change_invoice_collection_method` event + +## Structure + +`ChangeInvoiceCollectionMethodEventData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FromCollectionMethod` | `string` | Required | The previous collection method of the invoice. | +| `ToCollectionMethod` | `string` | Required | The new collection method of the invoice. | + +## Example (as JSON) + +```json +{ + "from_collection_method": "from_collection_method4", + "to_collection_method": "to_collection_method2" +} +``` + diff --git a/doc/models/chargify-ebb.md b/doc/models/chargify-ebb.md index 8a766e7c..4d1c0e5d 100644 --- a/doc/models/chargify-ebb.md +++ b/doc/models/chargify-ebb.md @@ -1,30 +1,30 @@ - -# Chargify EBB - -## Structure - -`ChargifyEBB` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Timestamp` | `*time.Time` | Optional | This timestamp determines what billing period the event will be billed in. If your request payload does not include it, Chargify will add `chargify.timestamp` to the event payload and set the value to `now`. | -| `Id` | `*string` | Optional | A unique ID set by Chargify. Please note that this field is reserved. If `chargify.id` is present in the request payload, it will be overwritten. | -| `CreatedAt` | `*time.Time` | Optional | An ISO-8601 timestamp, set by Chargify at the time each event is recorded. Please note that this field is reserved. If `chargify.created_at` is present in the request payload, it will be overwritten. | -| `UniquenessToken` | `*string` | Optional | User-defined string scoped per-stream. Duplicate events within a stream will be silently ignored. Tokens expire after 31 days.
**Constraints**: *Maximum Length*: `64` | -| `SubscriptionId` | `*int` | Optional | Id of Maxio Advanced Billing Subscription which is connected to this event.
Provide `subscription_id` if you configured `chargify.subscription_id` as Subscription Identifier in your Event Stream. | -| `SubscriptionReference` | `*string` | Optional | Reference of Maxio Advanced Billing Subscription which is connected to this event.
Provide `subscription_reference` if you configured `chargify.subscription_reference` as Subscription Identifier in your Event Stream. | - -## Example (as JSON) - -```json -{ - "timestamp": "2016-03-13T12:52:32.123Z", - "id": "id4", - "created_at": "2016-03-13T12:52:32.123Z", - "uniqueness_token": "uniqueness_token0", - "subscription_id": 200 -} -``` - + +# Chargify EBB + +## Structure + +`ChargifyEBB` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Timestamp` | `*time.Time` | Optional | This timestamp determines what billing period the event will be billed in. If your request payload does not include it, Chargify will add `chargify.timestamp` to the event payload and set the value to `now`. | +| `Id` | `*string` | Optional | A unique ID set by Chargify. Please note that this field is reserved. If `chargify.id` is present in the request payload, it will be overwritten. | +| `CreatedAt` | `*time.Time` | Optional | An ISO-8601 timestamp, set by Chargify at the time each event is recorded. Please note that this field is reserved. If `chargify.created_at` is present in the request payload, it will be overwritten. | +| `UniquenessToken` | `*string` | Optional | User-defined string scoped per-stream. Duplicate events within a stream will be silently ignored. Tokens expire after 31 days.
**Constraints**: *Maximum Length*: `64` | +| `SubscriptionId` | `*int` | Optional | Id of Maxio Advanced Billing Subscription which is connected to this event.
Provide `subscription_id` if you configured `chargify.subscription_id` as Subscription Identifier in your Event Stream. | +| `SubscriptionReference` | `*string` | Optional | Reference of Maxio Advanced Billing Subscription which is connected to this event.
Provide `subscription_reference` if you configured `chargify.subscription_reference` as Subscription Identifier in your Event Stream. | + +## Example (as JSON) + +```json +{ + "timestamp": "2016-03-13T12:52:32.123Z", + "id": "id4", + "created_at": "2016-03-13T12:52:32.123Z", + "uniqueness_token": "uniqueness_token0", + "subscription_id": 200 +} +``` + diff --git a/doc/models/cleanup-scope.md b/doc/models/cleanup-scope.md index 7f8b82e4..234cc07c 100644 --- a/doc/models/cleanup-scope.md +++ b/doc/models/cleanup-scope.md @@ -1,16 +1,16 @@ - -# Cleanup Scope - -all: Will clear all products, customers, and related subscriptions from the site. customers: Will clear only customers and related subscriptions (leaving the products untouched) for the site. Revenue will also be reset to 0. - -## Enumeration - -`CleanupScope` - -## Fields - -| Name | -| --- | -| `ALL` | -| `CUSTOMERS` | - + +# Cleanup Scope + +all: Will clear all products, customers, and related subscriptions from the site. customers: Will clear only customers and related subscriptions (leaving the products untouched) for the site. Revenue will also be reset to 0. + +## Enumeration + +`CleanupScope` + +## Fields + +| Name | +| --- | +| `ALL` | +| `CUSTOMERS` | + diff --git a/doc/models/collection-method.md b/doc/models/collection-method.md index 70d2ed2d..50b7215d 100644 --- a/doc/models/collection-method.md +++ b/doc/models/collection-method.md @@ -1,18 +1,18 @@ - -# Collection Method - -The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. - -## Enumeration - -`CollectionMethod` - -## Fields - -| Name | -| --- | -| `AUTOMATIC` | -| `REMITTANCE` | -| `PREPAID` | -| `INVOICE` | - + +# Collection Method + +The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. + +## Enumeration + +`CollectionMethod` + +## Fields + +| Name | +| --- | +| `AUTOMATIC` | +| `REMITTANCE` | +| `PREPAID` | +| `INVOICE` | + diff --git a/doc/models/component-allocation-change.md b/doc/models/component-allocation-change.md new file mode 100644 index 00000000..d0c5dbb7 --- /dev/null +++ b/doc/models/component-allocation-change.md @@ -0,0 +1,33 @@ + +# Component Allocation Change + +## Structure + +`ComponentAllocationChange` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PreviousAllocation` | `int` | Required | - | +| `NewAllocation` | `int` | Required | - | +| `ComponentId` | `int` | Required | - | +| `ComponentHandle` | `string` | Required | - | +| `Memo` | `string` | Required | - | +| `AllocationId` | `int` | Required | - | +| `AllocatedQuantity` | [`*models.ComponentAllocationChangeAllocatedQuantity`](../../doc/models/containers/component-allocation-change-allocated-quantity.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "previous_allocation": 94, + "new_allocation": 102, + "component_id": 88, + "component_handle": "component_handle8", + "memo": "memo2", + "allocation_id": 158, + "allocated_quantity": 104 +} +``` + diff --git a/doc/models/component-allocation-error-exception.md b/doc/models/component-allocation-error-exception.md index ad3102d8..61157d85 100644 --- a/doc/models/component-allocation-error-exception.md +++ b/doc/models/component-allocation-error-exception.md @@ -1,40 +1,40 @@ - -# Component Allocation Error Exception - -## Structure - -`ComponentAllocationErrorException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`[]models.ComponentAllocationErrorItem`](../../doc/models/component-allocation-error-item.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": [ - { - "component_id": 236, - "message": "message0", - "kind": "kind8", - "on": "on0" - }, - { - "component_id": 236, - "message": "message0", - "kind": "kind8", - "on": "on0" - }, - { - "component_id": 236, - "message": "message0", - "kind": "kind8", - "on": "on0" - } - ] -} -``` - + +# Component Allocation Error Exception + +## Structure + +`ComponentAllocationErrorException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`[]models.ComponentAllocationErrorItem`](../../doc/models/component-allocation-error-item.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": [ + { + "component_id": 236, + "message": "message0", + "kind": "kind8", + "on": "on0" + }, + { + "component_id": 236, + "message": "message0", + "kind": "kind8", + "on": "on0" + }, + { + "component_id": 236, + "message": "message0", + "kind": "kind8", + "on": "on0" + } + ] +} +``` + diff --git a/doc/models/component-allocation-error-item.md b/doc/models/component-allocation-error-item.md index 0de5b681..8d59142f 100644 --- a/doc/models/component-allocation-error-item.md +++ b/doc/models/component-allocation-error-item.md @@ -1,27 +1,27 @@ - -# Component Allocation Error Item - -## Structure - -`ComponentAllocationErrorItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ComponentId` | `*int` | Optional | - | -| `Message` | `*string` | Optional | - | -| `Kind` | `*string` | Optional | - | -| `On` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "component_id": 188, - "message": "message0", - "kind": "kind8", - "on": "on0" -} -``` - + +# Component Allocation Error Item + +## Structure + +`ComponentAllocationErrorItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ComponentId` | `*int` | Optional | - | +| `Message` | `*string` | Optional | - | +| `Kind` | `*string` | Optional | - | +| `On` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "component_id": 188, + "message": "message0", + "kind": "kind8", + "on": "on0" +} +``` + diff --git a/doc/models/component-cost-data-rate-tier.md b/doc/models/component-cost-data-rate-tier.md index 5e836a4f..47688104 100644 --- a/doc/models/component-cost-data-rate-tier.md +++ b/doc/models/component-cost-data-rate-tier.md @@ -1,29 +1,29 @@ - -# Component Cost Data Rate Tier - -## Structure - -`ComponentCostDataRateTier` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `StartingQuantity` | `*int` | Optional | - | -| `EndingQuantity` | `Optional[int]` | Optional | - | -| `Quantity` | `*string` | Optional | - | -| `UnitPrice` | `*string` | Optional | - | -| `Amount` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "starting_quantity": 132, - "ending_quantity": 106, - "quantity": "quantity0", - "unit_price": "unit_price2", - "amount": "amount6" -} -``` - + +# Component Cost Data Rate Tier + +## Structure + +`ComponentCostDataRateTier` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `StartingQuantity` | `*int` | Optional | - | +| `EndingQuantity` | `models.Optional[int]` | Optional | - | +| `Quantity` | `*string` | Optional | - | +| `UnitPrice` | `*string` | Optional | - | +| `Amount` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "starting_quantity": 132, + "ending_quantity": 106, + "quantity": "quantity0", + "unit_price": "unit_price2", + "amount": "amount6" +} +``` + diff --git a/doc/models/component-cost-data.md b/doc/models/component-cost-data.md index 9cfdc1ed..b756432f 100644 --- a/doc/models/component-cost-data.md +++ b/doc/models/component-cost-data.md @@ -1,31 +1,31 @@ - -# Component Cost Data - -## Structure - -`ComponentCostData` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ComponentCodeId` | `Optional[int]` | Optional | - | -| `PricePointId` | `*int` | Optional | - | -| `ProductId` | `*int` | Optional | - | -| `Quantity` | `*string` | Optional | - | -| `Amount` | `*string` | Optional | - | -| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Tiers` | [`[]models.ComponentCostDataRateTier`](../../doc/models/component-cost-data-rate-tier.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "component_code_id": 16, - "price_point_id": 186, - "product_id": 250, - "quantity": "quantity8", - "amount": "amount4" -} -``` - + +# Component Cost Data + +## Structure + +`ComponentCostData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ComponentCodeId` | `models.Optional[int]` | Optional | - | +| `PricePointId` | `*int` | Optional | - | +| `ProductId` | `*int` | Optional | - | +| `Quantity` | `*string` | Optional | - | +| `Amount` | `*string` | Optional | - | +| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Tiers` | [`[]models.ComponentCostDataRateTier`](../../doc/models/component-cost-data-rate-tier.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "component_code_id": 16, + "price_point_id": 186, + "product_id": 250, + "quantity": "quantity8", + "amount": "amount4" +} +``` + diff --git a/doc/models/component-currency-price.md b/doc/models/component-currency-price.md index 5af54000..8f9c31e0 100644 --- a/doc/models/component-currency-price.md +++ b/doc/models/component-currency-price.md @@ -1,30 +1,30 @@ - -# Component Currency Price - -## Structure - -`ComponentCurrencyPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Currency` | `*string` | Optional | - | -| `Price` | `*string` | Optional | - | -| `FormattedPrice` | `*string` | Optional | - | -| `PriceId` | `*int` | Optional | - | -| `PricePointId` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 4, - "currency": "currency8", - "price": "price4", - "formatted_price": "formatted_price6", - "price_id": 162 -} -``` - + +# Component Currency Price + +## Structure + +`ComponentCurrencyPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Currency` | `*string` | Optional | - | +| `Price` | `*string` | Optional | - | +| `FormattedPrice` | `*string` | Optional | - | +| `PriceId` | `*int` | Optional | - | +| `PricePointId` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 4, + "currency": "currency8", + "price": "price4", + "formatted_price": "formatted_price6", + "price_id": 162 +} +``` + diff --git a/doc/models/component-currency-prices-response.md b/doc/models/component-currency-prices-response.md index 710c0b80..76a75b76 100644 --- a/doc/models/component-currency-prices-response.md +++ b/doc/models/component-currency-prices-response.md @@ -1,29 +1,29 @@ - -# Component Currency Prices Response - -## Structure - -`ComponentCurrencyPricesResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CurrencyPrices` | [`[]models.ComponentCurrencyPrice`](../../doc/models/component-currency-price.md) | Required | - | - -## Example (as JSON) - -```json -{ - "currency_prices": [ - { - "id": 50, - "currency": "currency8", - "price": "price4", - "formatted_price": "formatted_price6", - "price_id": 116 - } - ] -} -``` - + +# Component Currency Prices Response + +## Structure + +`ComponentCurrencyPricesResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrencyPrices` | [`[]models.ComponentCurrencyPrice`](../../doc/models/component-currency-price.md) | Required | - | + +## Example (as JSON) + +```json +{ + "currency_prices": [ + { + "id": 50, + "currency": "currency8", + "price": "price4", + "formatted_price": "formatted_price6", + "price_id": 116 + } + ] +} +``` + diff --git a/doc/models/component-custom-price.md b/doc/models/component-custom-price.md index e980d0de..2ba0b870 100644 --- a/doc/models/component-custom-price.md +++ b/doc/models/component-custom-price.md @@ -1,44 +1,35 @@ - -# Component Custom Price - -Create or update custom pricing unique to the subscription. Used in place of `price_point_id`. - -## Structure - -`ComponentCustomPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | Omit for On/Off components | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | -| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | On/off components only need one price bracket starting at 1 | - -## Example (as JSON) - -```json -{ - "pricing_scheme": "stairstep", - "interval": 162, - "interval_unit": "day", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] -} -``` - + +# Component Custom Price + +Create or update custom pricing unique to the subscription. Used in place of `price_point_id`. + +## Structure + +`ComponentCustomPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | Omit for On/Off components | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | On/off components only need one price bracket starting at 1 | + +## Example (as JSON) + +```json +{ + "pricing_scheme": "stairstep", + "interval": 162, + "interval_unit": "day", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ] +} +``` + diff --git a/doc/models/component-kind.md b/doc/models/component-kind.md index 5b9e610a..86d46440 100644 --- a/doc/models/component-kind.md +++ b/doc/models/component-kind.md @@ -1,19 +1,19 @@ - -# Component Kind - -A handle for the component type - -## Enumeration - -`ComponentKind` - -## Fields - -| Name | -| --- | -| `METEREDCOMPONENT` | -| `QUANTITYBASEDCOMPONENT` | -| `ONOFFCOMPONENT` | -| `PREPAIDUSAGECOMPONENT` | -| `EVENTBASEDCOMPONENT` | - + +# Component Kind + +A handle for the component type + +## Enumeration + +`ComponentKind` + +## Fields + +| Name | +| --- | +| `METEREDCOMPONENT` | +| `QUANTITYBASEDCOMPONENT` | +| `ONOFFCOMPONENT` | +| `PREPAIDUSAGECOMPONENT` | +| `EVENTBASEDCOMPONENT` | + diff --git a/doc/models/component-price-point-assignment.md b/doc/models/component-price-point-assignment.md index f8d03e83..d251cd8e 100644 --- a/doc/models/component-price-point-assignment.md +++ b/doc/models/component-price-point-assignment.md @@ -1,26 +1,23 @@ - -# Component Price Point Assignment - -## Structure - -`ComponentPricePointAssignment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ComponentId` | `*int` | Optional | - | -| `PricePoint` | `*interface{}` | Optional | - | - -## Example (as JSON) - -```json -{ - "component_id": 114, - "price_point": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Component Price Point Assignment + +## Structure + +`ComponentPricePointAssignment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ComponentId` | `*int` | Optional | - | +| `PricePoint` | [`*models.ComponentPricePointAssignmentPricePoint`](../../doc/models/containers/component-price-point-assignment-price-point.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "component_id": 114, + "price_point": "String9" +} +``` + diff --git a/doc/models/component-price-point-error-exception.md b/doc/models/component-price-point-error-exception.md index 9fea35e8..8fe4e1d9 100644 --- a/doc/models/component-price-point-error-exception.md +++ b/doc/models/component-price-point-error-exception.md @@ -1,32 +1,32 @@ - -# Component Price Point Error Exception - -## Structure - -`ComponentPricePointErrorException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`[]models.ComponentPricePointErrorItem`](../../doc/models/component-price-point-error-item.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": [ - { - "component_id": 236, - "message": "message0", - "price_point": 122 - }, - { - "component_id": 236, - "message": "message0", - "price_point": 122 - } - ] -} -``` - + +# Component Price Point Error Exception + +## Structure + +`ComponentPricePointErrorException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`[]models.ComponentPricePointErrorItem`](../../doc/models/component-price-point-error-item.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": [ + { + "component_id": 236, + "message": "message0", + "price_point": 122 + }, + { + "component_id": 236, + "message": "message0", + "price_point": 122 + } + ] +} +``` + diff --git a/doc/models/component-price-point-error-item.md b/doc/models/component-price-point-error-item.md index ba86d5ab..68ccee55 100644 --- a/doc/models/component-price-point-error-item.md +++ b/doc/models/component-price-point-error-item.md @@ -1,25 +1,25 @@ - -# Component Price Point Error Item - -## Structure - -`ComponentPricePointErrorItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ComponentId` | `*int` | Optional | - | -| `Message` | `*string` | Optional | - | -| `PricePoint` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "component_id": 206, - "message": "message4", - "price_point": 152 -} -``` - + +# Component Price Point Error Item + +## Structure + +`ComponentPricePointErrorItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ComponentId` | `*int` | Optional | - | +| `Message` | `*string` | Optional | - | +| `PricePoint` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "component_id": 206, + "message": "message4", + "price_point": 152 +} +``` + diff --git a/doc/models/component-price-point-item.md b/doc/models/component-price-point-item.md index 009589ba..fbee7dc3 100644 --- a/doc/models/component-price-point-item.md +++ b/doc/models/component-price-point-item.md @@ -1,30 +1,30 @@ - -# Component Price Point Item - -## Structure - -`ComponentPricePointItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `*string` | Optional | - | -| `Handle` | `*string` | Optional | - | -| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | -| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "name": "name6", - "handle": "handle2", - "pricing_scheme": "per_unit", - "interval": 196, - "interval_unit": "day" -} -``` - + +# Component Price Point Item + +## Structure + +`ComponentPricePointItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `*string` | Optional | - | +| `Handle` | `*string` | Optional | - | +| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name6", + "handle": "handle2", + "pricing_scheme": "per_unit", + "interval": 196, + "interval_unit": "day" +} +``` + diff --git a/doc/models/component-price-point-response.md b/doc/models/component-price-point-response.md index 3e367fe6..1bdbc24a 100644 --- a/doc/models/component-price-point-response.md +++ b/doc/models/component-price-point-response.md @@ -1,27 +1,27 @@ - -# Component Price Point Response - -## Structure - -`ComponentPricePointResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoint` | [`models.ComponentPricePoint`](../../doc/models/component-price-point.md) | Required | - | - -## Example (as JSON) - -```json -{ - "price_point": { - "id": 248, - "type": "default", - "default": false, - "name": "name0", - "pricing_scheme": "per_unit" - } -} -``` - + +# Component Price Point Response + +## Structure + +`ComponentPricePointResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoint` | [`models.ComponentPricePoint`](../../doc/models/component-price-point.md) | Required | - | + +## Example (as JSON) + +```json +{ + "price_point": { + "id": 248, + "type": "default", + "default": false, + "name": "name0", + "pricing_scheme": "per_unit" + } +} +``` + diff --git a/doc/models/component-price-point.md b/doc/models/component-price-point.md index 8a2b5889..fb328da8 100644 --- a/doc/models/component-price-point.md +++ b/doc/models/component-price-point.md @@ -1,41 +1,41 @@ - -# Component Price Point - -## Structure - -`ComponentPricePoint` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Type` | [`*models.PricePointType`](../../doc/models/price-point-type.md) | Optional | Price point type. We expose the following types:

1. **default**: a price point that is marked as a default price for a certain product.
2. **custom**: a custom price point.
3. **catalog**: a price point that is **not** marked as a default price for a certain product and is **not** a custom one. | -| `Default` | `*bool` | Optional | Note: Refer to type attribute instead | -| `Name` | `*string` | Optional | - | -| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `ComponentId` | `*int` | Optional | - | -| `Handle` | `*string` | Optional | - | -| `ArchivedAt` | `Optional[time.Time]` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `UpdatedAt` | `*time.Time` | Optional | - | -| `Prices` | [`[]models.ComponentPrice`](../../doc/models/component-price.md) | Optional | - | -| `UseSiteExchangeRate` | `*bool` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. Defaults to true during creation. | -| `SubscriptionId` | `*int` | Optional | (only used for Custom Pricing - ie. when the price point's type is `custom`) The id of the subscription that the custom price point is for. | -| `TaxIncluded` | `*bool` | Optional | - | -| `Interval` | `Optional[int]` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`Optional[models.IntervalUnit]`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | -| `CurrencyPrices` | [`[]models.ComponentCurrencyPrice`](../../doc/models/component-currency-price.md) | Optional | An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. | - -## Example (as JSON) - -```json -{ - "id": 190, - "type": "custom", - "default": false, - "name": "name2", - "pricing_scheme": "stairstep" -} -``` - + +# Component Price Point + +## Structure + +`ComponentPricePoint` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Type` | [`*models.PricePointType`](../../doc/models/price-point-type.md) | Optional | Price point type. We expose the following types:

1. **default**: a price point that is marked as a default price for a certain product.
2. **custom**: a custom price point.
3. **catalog**: a price point that is **not** marked as a default price for a certain product and is **not** a custom one. | +| `Default` | `*bool` | Optional | Note: Refer to type attribute instead | +| `Name` | `*string` | Optional | - | +| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `ComponentId` | `*int` | Optional | - | +| `Handle` | `*string` | Optional | - | +| `ArchivedAt` | `models.Optional[time.Time]` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `UpdatedAt` | `*time.Time` | Optional | - | +| `Prices` | [`[]models.ComponentPrice`](../../doc/models/component-price.md) | Optional | - | +| `UseSiteExchangeRate` | `*bool` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. Defaults to true during creation. | +| `SubscriptionId` | `*int` | Optional | (only used for Custom Pricing - ie. when the price point's type is `custom`) The id of the subscription that the custom price point is for. | +| `TaxIncluded` | `*bool` | Optional | - | +| `Interval` | `models.Optional[int]` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`models.Optional[models.ComponentPricePointIntervalUnit]`](../../doc/models/containers/component-price-point-interval-unit.md) | Optional | This is a container for one-of cases. | +| `CurrencyPrices` | [`[]models.ComponentCurrencyPrice`](../../doc/models/component-currency-price.md) | Optional | An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. | + +## Example (as JSON) + +```json +{ + "id": 190, + "type": "custom", + "default": false, + "name": "name2", + "pricing_scheme": "stairstep" +} +``` + diff --git a/doc/models/component-price-points-response.md b/doc/models/component-price-points-response.md index 45df0633..2dd64493 100644 --- a/doc/models/component-price-points-response.md +++ b/doc/models/component-price-points-response.md @@ -1,43 +1,43 @@ - -# Component Price Points Response - -## Structure - -`ComponentPricePointsResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoints` | [`[]models.ComponentPricePoint`](../../doc/models/component-price-point.md) | Optional | - | -| `Meta` | [`*models.ListPublicKeysMeta`](../../doc/models/list-public-keys-meta.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "price_points": [ - { - "id": 40, - "type": "default", - "default": false, - "name": "name2", - "pricing_scheme": "per_unit" - }, - { - "id": 40, - "type": "default", - "default": false, - "name": "name2", - "pricing_scheme": "per_unit" - } - ], - "meta": { - "total_count": 150, - "current_page": 126, - "total_pages": 138, - "per_page": 152 - } -} -``` - + +# Component Price Points Response + +## Structure + +`ComponentPricePointsResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoints` | [`[]models.ComponentPricePoint`](../../doc/models/component-price-point.md) | Optional | - | +| `Meta` | [`*models.ListPublicKeysMeta`](../../doc/models/list-public-keys-meta.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "price_points": [ + { + "id": 40, + "type": "default", + "default": false, + "name": "name2", + "pricing_scheme": "per_unit" + }, + { + "id": 40, + "type": "default", + "default": false, + "name": "name2", + "pricing_scheme": "per_unit" + } + ], + "meta": { + "total_count": 150, + "current_page": 126, + "total_pages": 138, + "per_page": 152 + } +} +``` + diff --git a/doc/models/component-price.md b/doc/models/component-price.md index 1190f5b0..edda81b0 100644 --- a/doc/models/component-price.md +++ b/doc/models/component-price.md @@ -1,32 +1,32 @@ - -# Component Price - -## Structure - -`ComponentPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `ComponentId` | `*int` | Optional | - | -| `StartingQuantity` | `*int` | Optional | - | -| `EndingQuantity` | `Optional[int]` | Optional | - | -| `UnitPrice` | `*string` | Optional | - | -| `PricePointId` | `*int` | Optional | - | -| `FormattedUnitPrice` | `*string` | Optional | - | -| `SegmentId` | `Optional[int]` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 234, - "component_id": 88, - "starting_quantity": 104, - "ending_quantity": 78, - "unit_price": "unit_price0" -} -``` - + +# Component Price + +## Structure + +`ComponentPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `ComponentId` | `*int` | Optional | - | +| `StartingQuantity` | `*int` | Optional | - | +| `EndingQuantity` | `models.Optional[int]` | Optional | - | +| `UnitPrice` | `*string` | Optional | - | +| `PricePointId` | `*int` | Optional | - | +| `FormattedUnitPrice` | `*string` | Optional | - | +| `SegmentId` | `models.Optional[int]` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 234, + "component_id": 88, + "starting_quantity": 104, + "ending_quantity": 78, + "unit_price": "unit_price0" +} +``` + diff --git a/doc/models/component-response.md b/doc/models/component-response.md index 71572118..66c38552 100644 --- a/doc/models/component-response.md +++ b/doc/models/component-response.md @@ -1,28 +1,28 @@ - -# Component Response - -## Structure - -`ComponentResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Component` | [`models.Component`](../../doc/models/component.md) | Required | - | - -## Example (as JSON) - -```json -{ - "component": { - "item_category": "Business Software", - "id": 80, - "name": "name8", - "handle": "handle4", - "pricing_scheme": "per_unit", - "unit_name": "unit_name0" - } -} -``` - + +# Component Response + +## Structure + +`ComponentResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Component` | [`models.Component`](../../doc/models/component.md) | Required | - | + +## Example (as JSON) + +```json +{ + "component": { + "item_category": "Business Software", + "id": 80, + "name": "name8", + "handle": "handle4", + "pricing_scheme": "tiered", + "unit_name": "unit_name0" + } +} +``` + diff --git a/doc/models/component.md b/doc/models/component.md index 1912ed46..79d90c66 100644 --- a/doc/models/component.md +++ b/doc/models/component.md @@ -1,59 +1,59 @@ - -# Component - -## Structure - -`Component` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | The unique ID assigned to the component by Chargify. This ID can be used to fetch the component from the API. | -| `Name` | `*string` | Optional | The name of the Component, suitable for display on statements. i.e. Text Messages. | -| `Handle` | `Optional[string]` | Optional | The component API handle | -| `PricingScheme` | [`Optional[models.PricingScheme]`](../../doc/models/pricing-scheme.md) | Optional | - | -| `UnitName` | `*string` | Optional | The name of the unit that the component’s usage is measured in. i.e. message | -| `UnitPrice` | `Optional[string]` | Optional | The amount the customer will be charged per unit. This field is only populated for ‘per_unit’ pricing schemes, otherwise it may be null. | -| `ProductFamilyId` | `*int` | Optional | The id of the Product Family to which the Component belongs | -| `ProductFamilyName` | `*string` | Optional | The name of the Product Family to which the Component belongs | -| `PricePerUnitInCents` | `Optional[int64]` | Optional | deprecated - use unit_price instead | -| `Kind` | [`*models.ComponentKind`](../../doc/models/component-kind.md) | Optional | A handle for the component type | -| `Archived` | `*bool` | Optional | Boolean flag describing whether a component is archived or not. | -| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | -| `Description` | `Optional[string]` | Optional | The description of the component. | -| `DefaultPricePointId` | `Optional[int]` | Optional | - | -| `OveragePrices` | [`Optional[[]models.ComponentPrice]`](../../doc/models/component-price.md) | Optional | An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. | -| `Prices` | [`Optional[[]models.ComponentPrice]`](../../doc/models/component-price.md) | Optional | An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. | -| `PricePointCount` | `*int` | Optional | Count for the number of price points associated with the component | -| `PricePointsUrl` | `*string` | Optional | URL that points to the location to read the existing price points via GET request | -| `DefaultPricePointName` | `*string` | Optional | - | -| `TaxCode` | `Optional[string]` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | -| `Recurring` | `*bool` | Optional | - | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `CreatedAt` | `*time.Time` | Optional | Timestamp indicating when this component was created | -| `UpdatedAt` | `*time.Time` | Optional | Timestamp indicating when this component was updated | -| `ArchivedAt` | `Optional[time.Time]` | Optional | Timestamp indicating when this component was archived | -| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | -| `AllowFractionalQuantities` | `*bool` | Optional | - | -| `ItemCategory` | [`Optional[models.ItemCategory]`](../../doc/models/item-category.md) | Optional | One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other | -| `UseSiteExchangeRate` | `Optional[bool]` | Optional | - | -| `AccountingCode` | `Optional[string]` | Optional | E.g. Internal ID or SKU Number | -| `EventBasedBillingMetricId` | `*int` | Optional | (Only for Event Based Components) This is an ID of a metric attached to the component. This metric is used to bill upon collected events. | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. | - -## Example (as JSON) - -```json -{ - "item_category": "Business Software", - "id": 24, - "name": "name2", - "handle": "handle8", - "pricing_scheme": "per_unit", - "unit_name": "unit_name4" -} -``` - + +# Component + +## Structure + +`Component` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | The unique ID assigned to the component by Chargify. This ID can be used to fetch the component from the API. | +| `Name` | `*string` | Optional | The name of the Component, suitable for display on statements. i.e. Text Messages. | +| `Handle` | `models.Optional[string]` | Optional | The component API handle | +| `PricingScheme` | [`models.Optional[models.ComponentPricingScheme]`](../../doc/models/containers/component-pricing-scheme.md) | Optional | This is a container for one-of cases. | +| `UnitName` | `*string` | Optional | The name of the unit that the component’s usage is measured in. i.e. message | +| `UnitPrice` | `models.Optional[string]` | Optional | The amount the customer will be charged per unit. This field is only populated for ‘per_unit’ pricing schemes, otherwise it may be null. | +| `ProductFamilyId` | `*int` | Optional | The id of the Product Family to which the Component belongs | +| `ProductFamilyName` | `*string` | Optional | The name of the Product Family to which the Component belongs | +| `PricePerUnitInCents` | `models.Optional[int64]` | Optional | deprecated - use unit_price instead | +| `Kind` | [`*models.ComponentKind`](../../doc/models/component-kind.md) | Optional | A handle for the component type | +| `Archived` | `*bool` | Optional | Boolean flag describing whether a component is archived or not. | +| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | +| `Description` | `models.Optional[string]` | Optional | The description of the component. | +| `DefaultPricePointId` | `models.Optional[int]` | Optional | - | +| `OveragePrices` | [`models.Optional[[]models.ComponentPrice]`](../../doc/models/component-price.md) | Optional | An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. | +| `Prices` | [`models.Optional[[]models.ComponentPrice]`](../../doc/models/component-price.md) | Optional | An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. | +| `PricePointCount` | `*int` | Optional | Count for the number of price points associated with the component | +| `PricePointsUrl` | `*string` | Optional | URL that points to the location to read the existing price points via GET request | +| `DefaultPricePointName` | `*string` | Optional | - | +| `TaxCode` | `models.Optional[string]` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | +| `Recurring` | `*bool` | Optional | - | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `CreatedAt` | `*time.Time` | Optional | Timestamp indicating when this component was created | +| `UpdatedAt` | `*time.Time` | Optional | Timestamp indicating when this component was updated | +| `ArchivedAt` | `models.Optional[time.Time]` | Optional | Timestamp indicating when this component was archived | +| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | +| `AllowFractionalQuantities` | `*bool` | Optional | - | +| `ItemCategory` | [`models.Optional[models.ItemCategory]`](../../doc/models/item-category.md) | Optional | One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other | +| `UseSiteExchangeRate` | `models.Optional[bool]` | Optional | - | +| `AccountingCode` | `models.Optional[string]` | Optional | E.g. Internal ID or SKU Number | +| `EventBasedBillingMetricId` | `*int` | Optional | (Only for Event Based Components) This is an ID of a metric attached to the component. This metric is used to bill upon collected events. | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. | + +## Example (as JSON) + +```json +{ + "item_category": "Business Software", + "id": 24, + "name": "name2", + "handle": "handle8", + "pricing_scheme": "tiered", + "unit_name": "unit_name4" +} +``` + diff --git a/doc/models/compounding-strategy.md b/doc/models/compounding-strategy.md index dd0e3c83..d3746d9f 100644 --- a/doc/models/compounding-strategy.md +++ b/doc/models/compounding-strategy.md @@ -1,14 +1,14 @@ - -# Compounding Strategy - -## Enumeration - -`CompoundingStrategy` - -## Fields - -| Name | -| --- | -| `COMPOUND` | -| `FULLPRICE` | - + +# Compounding Strategy + +## Enumeration + +`CompoundingStrategy` + +## Fields + +| Name | +| --- | +| `COMPOUND` | +| `FULLPRICE` | + diff --git a/doc/models/consolidated-invoice.md b/doc/models/consolidated-invoice.md index 71e3f022..8e49790a 100644 --- a/doc/models/consolidated-invoice.md +++ b/doc/models/consolidated-invoice.md @@ -1,36 +1,36 @@ - -# Consolidated Invoice - -## Structure - -`ConsolidatedInvoice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Invoices` | [`[]models.Invoice`](../../doc/models/invoice.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "invoices": [ - { - "id": 196, - "uid": "uid6", - "site_id": 122, - "customer_id": 234, - "subscription_id": 50 - }, - { - "id": 196, - "uid": "uid6", - "site_id": 122, - "customer_id": 234, - "subscription_id": 50 - } - ] -} -``` - + +# Consolidated Invoice + +## Structure + +`ConsolidatedInvoice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Invoices` | [`[]models.Invoice`](../../doc/models/invoice.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "invoices": [ + { + "id": 196, + "uid": "uid6", + "site_id": 122, + "customer_id": 234, + "subscription_id": 50 + }, + { + "id": 196, + "uid": "uid6", + "site_id": 122, + "customer_id": 234, + "subscription_id": 50 + } + ] +} +``` + diff --git a/doc/models/containers/add-subscription-to-a-group-group.md b/doc/models/containers/add-subscription-to-a-group-group.md new file mode 100644 index 00000000..6be00d98 --- /dev/null +++ b/doc/models/containers/add-subscription-to-a-group-group.md @@ -0,0 +1,14 @@ + +# Add Subscription to a Group Group + +## Class Name + +`AddSubscriptionToAGroupGroup` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.GroupSettings`](../../../doc/models/group-settings.md) | models.AddSubscriptionToAGroupGroupContainer.FromGroupSettings(models.GroupSettings groupSettings) | +| `bool` | models.AddSubscriptionToAGroupGroupContainer.FromBoolean(bool boolean) | + diff --git a/doc/models/containers/allocation-payment.md b/doc/models/containers/allocation-payment.md new file mode 100644 index 00000000..7b30e4fb --- /dev/null +++ b/doc/models/containers/allocation-payment.md @@ -0,0 +1,13 @@ + +# Allocation Payment + +## Class Name + +`AllocationPayment` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.PaymentForAllocation`](../../../doc/models/payment-for-allocation.md) | models.AllocationPaymentContainer.FromPaymentForAllocation(models.PaymentForAllocation paymentForAllocation) | + diff --git a/doc/models/containers/allocation-preview-item-previous-quantity.md b/doc/models/containers/allocation-preview-item-previous-quantity.md new file mode 100644 index 00000000..7b9f5d0b --- /dev/null +++ b/doc/models/containers/allocation-preview-item-previous-quantity.md @@ -0,0 +1,14 @@ + +# Allocation Preview Item Previous Quantity + +## Class Name + +`AllocationPreviewItemPreviousQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.AllocationPreviewItemPreviousQuantityContainer.FromNumber(int number) | +| `string` | models.AllocationPreviewItemPreviousQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/allocation-preview-item-quantity.md b/doc/models/containers/allocation-preview-item-quantity.md new file mode 100644 index 00000000..bb169565 --- /dev/null +++ b/doc/models/containers/allocation-preview-item-quantity.md @@ -0,0 +1,14 @@ + +# Allocation Preview Item Quantity + +## Class Name + +`AllocationPreviewItemQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.AllocationPreviewItemQuantityContainer.FromNumber(int number) | +| `string` | models.AllocationPreviewItemQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/allocation-previous-quantity.md b/doc/models/containers/allocation-previous-quantity.md new file mode 100644 index 00000000..5e30ef6b --- /dev/null +++ b/doc/models/containers/allocation-previous-quantity.md @@ -0,0 +1,14 @@ + +# Allocation Previous Quantity + +## Class Name + +`AllocationPreviousQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.AllocationPreviousQuantityContainer.FromNumber(int number) | +| `string` | models.AllocationPreviousQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/allocation-quantity.md b/doc/models/containers/allocation-quantity.md new file mode 100644 index 00000000..07feedf9 --- /dev/null +++ b/doc/models/containers/allocation-quantity.md @@ -0,0 +1,14 @@ + +# Allocation Quantity + +## Class Name + +`AllocationQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.AllocationQuantityContainer.FromNumber(int number) | +| `string` | models.AllocationQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/archive-product-price-point-price-point-id.md b/doc/models/containers/archive-product-price-point-price-point-id.md new file mode 100644 index 00000000..8e5aa158 --- /dev/null +++ b/doc/models/containers/archive-product-price-point-price-point-id.md @@ -0,0 +1,14 @@ + +# Archive Product Price Point Price Point Id + +## Class Name + +`ArchiveProductPricePointPricePointId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.ArchiveProductPricePointPricePointIdContainer.FromNumber(int number) | +| `string` | models.ArchiveProductPricePointPricePointIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/archive-product-price-point-product-id.md b/doc/models/containers/archive-product-price-point-product-id.md new file mode 100644 index 00000000..d7f25fd0 --- /dev/null +++ b/doc/models/containers/archive-product-price-point-product-id.md @@ -0,0 +1,14 @@ + +# Archive Product Price Point Product Id + +## Class Name + +`ArchiveProductPricePointProductId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.ArchiveProductPricePointProductIdContainer.FromNumber(int number) | +| `string` | models.ArchiveProductPricePointProductIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/calendar-billing-snap-day.md b/doc/models/containers/calendar-billing-snap-day.md new file mode 100644 index 00000000..733b0fd3 --- /dev/null +++ b/doc/models/containers/calendar-billing-snap-day.md @@ -0,0 +1,14 @@ + +# Calendar Billing Snap Day + +## Class Name + +`CalendarBillingSnapDay` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.CalendarBillingSnapDayContainer.FromNumber(int number) | +| `string` | models.CalendarBillingSnapDayContainer.FromString(string mString) | + diff --git a/doc/models/containers/component-allocation-change-allocated-quantity.md b/doc/models/containers/component-allocation-change-allocated-quantity.md new file mode 100644 index 00000000..e625c5f0 --- /dev/null +++ b/doc/models/containers/component-allocation-change-allocated-quantity.md @@ -0,0 +1,14 @@ + +# Component Allocation Change Allocated Quantity + +## Class Name + +`ComponentAllocationChangeAllocatedQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.ComponentAllocationChangeAllocatedQuantityContainer.FromNumber(int number) | +| `string` | models.ComponentAllocationChangeAllocatedQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/component-price-point-assignment-price-point.md b/doc/models/containers/component-price-point-assignment-price-point.md new file mode 100644 index 00000000..0f419710 --- /dev/null +++ b/doc/models/containers/component-price-point-assignment-price-point.md @@ -0,0 +1,14 @@ + +# Component Price Point Assignment Price Point + +## Class Name + +`ComponentPricePointAssignmentPricePoint` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.ComponentPricePointAssignmentPricePointContainer.FromString(string mString) | +| `int` | models.ComponentPricePointAssignmentPricePointContainer.FromNumber(int number) | + diff --git a/doc/models/containers/component-price-point-interval-unit.md b/doc/models/containers/component-price-point-interval-unit.md new file mode 100644 index 00000000..d216de4c --- /dev/null +++ b/doc/models/containers/component-price-point-interval-unit.md @@ -0,0 +1,13 @@ + +# Component Price Point Interval Unit + +## Class Name + +`ComponentPricePointIntervalUnit` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.IntervalUnit`](../../../doc/models/interval-unit.md) | models.ComponentPricePointIntervalUnitContainer.FromIntervalUnit(models.IntervalUnit intervalUnit) | + diff --git a/doc/models/containers/component-pricing-scheme.md b/doc/models/containers/component-pricing-scheme.md new file mode 100644 index 00000000..d107117a --- /dev/null +++ b/doc/models/containers/component-pricing-scheme.md @@ -0,0 +1,13 @@ + +# Component Pricing Scheme + +## Class Name + +`ComponentPricingScheme` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.PricingScheme`](../../../doc/models/pricing-scheme.md) | models.ComponentPricingSchemeContainer.FromPricingScheme(models.PricingScheme pricingScheme) | + diff --git a/doc/models/containers/coupon-compounding-strategy.md b/doc/models/containers/coupon-compounding-strategy.md new file mode 100644 index 00000000..4a85ac1c --- /dev/null +++ b/doc/models/containers/coupon-compounding-strategy.md @@ -0,0 +1,13 @@ + +# Coupon Compounding Strategy + +## Class Name + +`CouponCompoundingStrategy` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.CompoundingStrategy`](../../../doc/models/compounding-strategy.md) | models.CouponCompoundingStrategyContainer.FromCompoundingStrategy(models.CompoundingStrategy compoundingStrategy) | + diff --git a/doc/models/containers/create-allocation-price-point-id.md b/doc/models/containers/create-allocation-price-point-id.md new file mode 100644 index 00000000..22763613 --- /dev/null +++ b/doc/models/containers/create-allocation-price-point-id.md @@ -0,0 +1,14 @@ + +# Create Allocation Price Point Id + +## Class Name + +`CreateAllocationPricePointId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateAllocationPricePointIdContainer.FromString(string mString) | +| `int` | models.CreateAllocationPricePointIdContainer.FromNumber(int number) | + diff --git a/doc/models/containers/create-component-price-point-request-price-point.md b/doc/models/containers/create-component-price-point-request-price-point.md new file mode 100644 index 00000000..39e6ed55 --- /dev/null +++ b/doc/models/containers/create-component-price-point-request-price-point.md @@ -0,0 +1,14 @@ + +# Create Component Price Point Request Price Point + +## Class Name + +`CreateComponentPricePointRequestPricePoint` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.CreateComponentPricePoint`](../../../doc/models/create-component-price-point.md) | models.CreateComponentPricePointRequestPricePointContainer.FromCreateComponentPricePoint(models.CreateComponentPricePoint createComponentPricePoint) | +| [`models.CreatePrepaidUsageComponentPricePoint`](../../../doc/models/create-prepaid-usage-component-price-point.md) | models.CreateComponentPricePointRequestPricePointContainer.FromCreatePrepaidUsageComponentPricePoint(models.CreatePrepaidUsageComponentPricePoint createPrepaidUsageComponentPricePoint) | + diff --git a/doc/models/containers/create-component-price-points-request-price-points.md b/doc/models/containers/create-component-price-points-request-price-points.md new file mode 100644 index 00000000..5a90f39e --- /dev/null +++ b/doc/models/containers/create-component-price-points-request-price-points.md @@ -0,0 +1,14 @@ + +# Create Component Price Points Request Price Points + +## Class Name + +`CreateComponentPricePointsRequestPricePoints` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.CreateComponentPricePoint`](../../../doc/models/create-component-price-point.md) | models.CreateComponentPricePointsRequestPricePointsContainer.FromCreateComponentPricePoint(models.CreateComponentPricePoint createComponentPricePoint) | +| [`models.CreatePrepaidUsageComponentPricePoint`](../../../doc/models/create-prepaid-usage-component-price-point.md) | models.CreateComponentPricePointsRequestPricePointsContainer.FromCreatePrepaidUsageComponentPricePoint(models.CreatePrepaidUsageComponentPricePoint createPrepaidUsageComponentPricePoint) | + diff --git a/doc/models/containers/create-invoice-coupon-amount.md b/doc/models/containers/create-invoice-coupon-amount.md new file mode 100644 index 00000000..7a893054 --- /dev/null +++ b/doc/models/containers/create-invoice-coupon-amount.md @@ -0,0 +1,14 @@ + +# Create Invoice Coupon Amount + +## Class Name + +`CreateInvoiceCouponAmount` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateInvoiceCouponAmountContainer.FromString(string mString) | +| `float64` | models.CreateInvoiceCouponAmountContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/create-invoice-coupon-percentage.md b/doc/models/containers/create-invoice-coupon-percentage.md new file mode 100644 index 00000000..bcfb76f4 --- /dev/null +++ b/doc/models/containers/create-invoice-coupon-percentage.md @@ -0,0 +1,14 @@ + +# Create Invoice Coupon Percentage + +## Class Name + +`CreateInvoiceCouponPercentage` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateInvoiceCouponPercentageContainer.FromString(string mString) | +| `float64` | models.CreateInvoiceCouponPercentageContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/create-invoice-coupon-product-family-id.md b/doc/models/containers/create-invoice-coupon-product-family-id.md new file mode 100644 index 00000000..7202ba19 --- /dev/null +++ b/doc/models/containers/create-invoice-coupon-product-family-id.md @@ -0,0 +1,14 @@ + +# Create Invoice Coupon Product Family Id + +## Class Name + +`CreateInvoiceCouponProductFamilyId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateInvoiceCouponProductFamilyIdContainer.FromString(string mString) | +| `int` | models.CreateInvoiceCouponProductFamilyIdContainer.FromNumber(int number) | + diff --git a/doc/models/containers/create-invoice-item-component-id.md b/doc/models/containers/create-invoice-item-component-id.md new file mode 100644 index 00000000..409958b4 --- /dev/null +++ b/doc/models/containers/create-invoice-item-component-id.md @@ -0,0 +1,14 @@ + +# Create Invoice Item Component Id + +## Class Name + +`CreateInvoiceItemComponentId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateInvoiceItemComponentIdContainer.FromString(string mString) | +| `int` | models.CreateInvoiceItemComponentIdContainer.FromNumber(int number) | + diff --git a/doc/models/containers/create-invoice-item-price-point-id.md b/doc/models/containers/create-invoice-item-price-point-id.md new file mode 100644 index 00000000..43279887 --- /dev/null +++ b/doc/models/containers/create-invoice-item-price-point-id.md @@ -0,0 +1,14 @@ + +# Create Invoice Item Price Point Id + +## Class Name + +`CreateInvoiceItemPricePointId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateInvoiceItemPricePointIdContainer.FromString(string mString) | +| `int` | models.CreateInvoiceItemPricePointIdContainer.FromNumber(int number) | + diff --git a/doc/models/containers/create-invoice-item-product-id.md b/doc/models/containers/create-invoice-item-product-id.md new file mode 100644 index 00000000..b674f2d6 --- /dev/null +++ b/doc/models/containers/create-invoice-item-product-id.md @@ -0,0 +1,14 @@ + +# Create Invoice Item Product Id + +## Class Name + +`CreateInvoiceItemProductId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateInvoiceItemProductIdContainer.FromString(string mString) | +| `int` | models.CreateInvoiceItemProductIdContainer.FromNumber(int number) | + diff --git a/doc/models/containers/create-invoice-item-product-price-point-id.md b/doc/models/containers/create-invoice-item-product-price-point-id.md new file mode 100644 index 00000000..fa45733a --- /dev/null +++ b/doc/models/containers/create-invoice-item-product-price-point-id.md @@ -0,0 +1,14 @@ + +# Create Invoice Item Product Price Point Id + +## Class Name + +`CreateInvoiceItemProductPricePointId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateInvoiceItemProductPricePointIdContainer.FromString(string mString) | +| `int` | models.CreateInvoiceItemProductPricePointIdContainer.FromNumber(int number) | + diff --git a/doc/models/containers/create-invoice-item-quantity.md b/doc/models/containers/create-invoice-item-quantity.md new file mode 100644 index 00000000..2e955966 --- /dev/null +++ b/doc/models/containers/create-invoice-item-quantity.md @@ -0,0 +1,14 @@ + +# Create Invoice Item Quantity + +## Class Name + +`CreateInvoiceItemQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `float64` | models.CreateInvoiceItemQuantityContainer.FromPrecision(float64 precision) | +| `string` | models.CreateInvoiceItemQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/create-invoice-item-unit-price.md b/doc/models/containers/create-invoice-item-unit-price.md new file mode 100644 index 00000000..786cd788 --- /dev/null +++ b/doc/models/containers/create-invoice-item-unit-price.md @@ -0,0 +1,14 @@ + +# Create Invoice Item Unit Price + +## Class Name + +`CreateInvoiceItemUnitPrice` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `float64` | models.CreateInvoiceItemUnitPriceContainer.FromPrecision(float64 precision) | +| `string` | models.CreateInvoiceItemUnitPriceContainer.FromString(string mString) | + diff --git a/doc/models/containers/create-invoice-payment-amount.md b/doc/models/containers/create-invoice-payment-amount.md new file mode 100644 index 00000000..934531a9 --- /dev/null +++ b/doc/models/containers/create-invoice-payment-amount.md @@ -0,0 +1,14 @@ + +# Create Invoice Payment Amount + +## Class Name + +`CreateInvoicePaymentAmount` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateInvoicePaymentAmountContainer.FromString(string mString) | +| `float64` | models.CreateInvoicePaymentAmountContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/create-metafields-request-metafields.md b/doc/models/containers/create-metafields-request-metafields.md new file mode 100644 index 00000000..ab9d992e --- /dev/null +++ b/doc/models/containers/create-metafields-request-metafields.md @@ -0,0 +1,14 @@ + +# Create Metafields Request Metafields + +## Class Name + +`CreateMetafieldsRequestMetafields` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.CreateMetafield`](../../../doc/models/create-metafield.md) | models.CreateMetafieldsRequestMetafieldsContainer.FromCreateMetafield(models.CreateMetafield createMetafield) | +| [`[]models.CreateMetafield`](../../../doc/models/create-metafield.md) | models.CreateMetafieldsRequestMetafieldsContainer.FromArrayOfCreateMetafield([]models.CreateMetafield arrayOfCreateMetafield) | + diff --git a/doc/models/containers/create-multi-invoice-payment-amount.md b/doc/models/containers/create-multi-invoice-payment-amount.md new file mode 100644 index 00000000..8a362a0e --- /dev/null +++ b/doc/models/containers/create-multi-invoice-payment-amount.md @@ -0,0 +1,14 @@ + +# Create Multi Invoice Payment Amount + +## Class Name + +`CreateMultiInvoicePaymentAmount` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateMultiInvoicePaymentAmountContainer.FromString(string mString) | +| `float64` | models.CreateMultiInvoicePaymentAmountContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/create-or-update-coupon-coupon.md b/doc/models/containers/create-or-update-coupon-coupon.md new file mode 100644 index 00000000..faf302a5 --- /dev/null +++ b/doc/models/containers/create-or-update-coupon-coupon.md @@ -0,0 +1,14 @@ + +# Create or Update Coupon Coupon + +## Class Name + +`CreateOrUpdateCouponCoupon` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.CreateOrUpdatePercentageCoupon`](../../../doc/models/create-or-update-percentage-coupon.md) | models.CreateOrUpdateCouponCouponContainer.FromCreateOrUpdatePercentageCoupon(models.CreateOrUpdatePercentageCoupon createOrUpdatePercentageCoupon) | +| [`models.CreateOrUpdateFlatAmountCoupon`](../../../doc/models/create-or-update-flat-amount-coupon.md) | models.CreateOrUpdateCouponCouponContainer.FromCreateOrUpdateFlatAmountCoupon(models.CreateOrUpdateFlatAmountCoupon createOrUpdateFlatAmountCoupon) | + diff --git a/doc/models/containers/create-or-update-percentage-coupon-percentage.md b/doc/models/containers/create-or-update-percentage-coupon-percentage.md new file mode 100644 index 00000000..ae1e4b7a --- /dev/null +++ b/doc/models/containers/create-or-update-percentage-coupon-percentage.md @@ -0,0 +1,14 @@ + +# Create or Update Percentage Coupon Percentage + +## Class Name + +`CreateOrUpdatePercentageCouponPercentage` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateOrUpdatePercentageCouponPercentageContainer.FromString(string mString) | +| `float64` | models.CreateOrUpdatePercentageCouponPercentageContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/create-or-update-segment-price-unit-price.md b/doc/models/containers/create-or-update-segment-price-unit-price.md new file mode 100644 index 00000000..d6ef72bb --- /dev/null +++ b/doc/models/containers/create-or-update-segment-price-unit-price.md @@ -0,0 +1,14 @@ + +# Create or Update Segment Price Unit Price + +## Class Name + +`CreateOrUpdateSegmentPriceUnitPrice` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateOrUpdateSegmentPriceUnitPriceContainer.FromString(string mString) | +| `float64` | models.CreateOrUpdateSegmentPriceUnitPriceContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/create-payment-profile-expiration-month.md b/doc/models/containers/create-payment-profile-expiration-month.md new file mode 100644 index 00000000..86f9f24f --- /dev/null +++ b/doc/models/containers/create-payment-profile-expiration-month.md @@ -0,0 +1,14 @@ + +# Create Payment Profile Expiration Month + +## Class Name + +`CreatePaymentProfileExpirationMonth` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.CreatePaymentProfileExpirationMonthContainer.FromNumber(int number) | +| `string` | models.CreatePaymentProfileExpirationMonthContainer.FromString(string mString) | + diff --git a/doc/models/containers/create-payment-profile-expiration-year.md b/doc/models/containers/create-payment-profile-expiration-year.md new file mode 100644 index 00000000..42a5f306 --- /dev/null +++ b/doc/models/containers/create-payment-profile-expiration-year.md @@ -0,0 +1,14 @@ + +# Create Payment Profile Expiration Year + +## Class Name + +`CreatePaymentProfileExpirationYear` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.CreatePaymentProfileExpirationYearContainer.FromNumber(int number) | +| `string` | models.CreatePaymentProfileExpirationYearContainer.FromString(string mString) | + diff --git a/doc/models/containers/create-product-price-point-product-id.md b/doc/models/containers/create-product-price-point-product-id.md new file mode 100644 index 00000000..299560ab --- /dev/null +++ b/doc/models/containers/create-product-price-point-product-id.md @@ -0,0 +1,14 @@ + +# Create Product Price Point Product Id + +## Class Name + +`CreateProductPricePointProductId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.CreateProductPricePointProductIdContainer.FromNumber(int number) | +| `string` | models.CreateProductPricePointProductIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/create-segment-segment-property-1-value.md b/doc/models/containers/create-segment-segment-property-1-value.md new file mode 100644 index 00000000..5bfcc50c --- /dev/null +++ b/doc/models/containers/create-segment-segment-property-1-value.md @@ -0,0 +1,16 @@ + +# Create Segment Segment Property 1 Value + +## Class Name + +`CreateSegmentSegmentProperty1Value` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateSegmentSegmentProperty1ValueContainer.FromString(string mString) | +| `float64` | models.CreateSegmentSegmentProperty1ValueContainer.FromPrecision(float64 precision) | +| `int` | models.CreateSegmentSegmentProperty1ValueContainer.FromNumber(int number) | +| `bool` | models.CreateSegmentSegmentProperty1ValueContainer.FromBoolean(bool boolean) | + diff --git a/doc/models/containers/create-segment-segment-property-2-value.md b/doc/models/containers/create-segment-segment-property-2-value.md new file mode 100644 index 00000000..b2d7dac1 --- /dev/null +++ b/doc/models/containers/create-segment-segment-property-2-value.md @@ -0,0 +1,16 @@ + +# Create Segment Segment Property 2 Value + +## Class Name + +`CreateSegmentSegmentProperty2Value` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateSegmentSegmentProperty2ValueContainer.FromString(string mString) | +| `float64` | models.CreateSegmentSegmentProperty2ValueContainer.FromPrecision(float64 precision) | +| `int` | models.CreateSegmentSegmentProperty2ValueContainer.FromNumber(int number) | +| `bool` | models.CreateSegmentSegmentProperty2ValueContainer.FromBoolean(bool boolean) | + diff --git a/doc/models/containers/create-segment-segment-property-3-value.md b/doc/models/containers/create-segment-segment-property-3-value.md new file mode 100644 index 00000000..60c1155c --- /dev/null +++ b/doc/models/containers/create-segment-segment-property-3-value.md @@ -0,0 +1,16 @@ + +# Create Segment Segment Property 3 Value + +## Class Name + +`CreateSegmentSegmentProperty3Value` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateSegmentSegmentProperty3ValueContainer.FromString(string mString) | +| `float64` | models.CreateSegmentSegmentProperty3ValueContainer.FromPrecision(float64 precision) | +| `int` | models.CreateSegmentSegmentProperty3ValueContainer.FromNumber(int number) | +| `bool` | models.CreateSegmentSegmentProperty3ValueContainer.FromBoolean(bool boolean) | + diff --git a/doc/models/containers/create-segment-segment-property-4-value.md b/doc/models/containers/create-segment-segment-property-4-value.md new file mode 100644 index 00000000..be41efb3 --- /dev/null +++ b/doc/models/containers/create-segment-segment-property-4-value.md @@ -0,0 +1,16 @@ + +# Create Segment Segment Property 4 Value + +## Class Name + +`CreateSegmentSegmentProperty4Value` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateSegmentSegmentProperty4ValueContainer.FromString(string mString) | +| `float64` | models.CreateSegmentSegmentProperty4ValueContainer.FromPrecision(float64 precision) | +| `int` | models.CreateSegmentSegmentProperty4ValueContainer.FromNumber(int number) | +| `bool` | models.CreateSegmentSegmentProperty4ValueContainer.FromBoolean(bool boolean) | + diff --git a/doc/models/containers/create-subscription-component-allocated-quantity.md b/doc/models/containers/create-subscription-component-allocated-quantity.md new file mode 100644 index 00000000..e32d550f --- /dev/null +++ b/doc/models/containers/create-subscription-component-allocated-quantity.md @@ -0,0 +1,14 @@ + +# Create Subscription Component Allocated Quantity + +## Class Name + +`CreateSubscriptionComponentAllocatedQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.CreateSubscriptionComponentAllocatedQuantityContainer.FromNumber(int number) | +| `string` | models.CreateSubscriptionComponentAllocatedQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/create-subscription-component-component-id.md b/doc/models/containers/create-subscription-component-component-id.md new file mode 100644 index 00000000..2a231112 --- /dev/null +++ b/doc/models/containers/create-subscription-component-component-id.md @@ -0,0 +1,14 @@ + +# Create Subscription Component Component Id + +## Class Name + +`CreateSubscriptionComponentComponentId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.CreateSubscriptionComponentComponentIdContainer.FromNumber(int number) | +| `string` | models.CreateSubscriptionComponentComponentIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/create-subscription-component-price-point-id.md b/doc/models/containers/create-subscription-component-price-point-id.md new file mode 100644 index 00000000..a04fdb7c --- /dev/null +++ b/doc/models/containers/create-subscription-component-price-point-id.md @@ -0,0 +1,14 @@ + +# Create Subscription Component Price Point Id + +## Class Name + +`CreateSubscriptionComponentPricePointId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.CreateSubscriptionComponentPricePointIdContainer.FromNumber(int number) | +| `string` | models.CreateSubscriptionComponentPricePointIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/create-subscription-offer-id.md b/doc/models/containers/create-subscription-offer-id.md new file mode 100644 index 00000000..33500788 --- /dev/null +++ b/doc/models/containers/create-subscription-offer-id.md @@ -0,0 +1,14 @@ + +# Create Subscription Offer Id + +## Class Name + +`CreateSubscriptionOfferId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.CreateSubscriptionOfferIdContainer.FromString(string mString) | +| `int` | models.CreateSubscriptionOfferIdContainer.FromNumber(int number) | + diff --git a/doc/models/containers/create-usage-component-id.md b/doc/models/containers/create-usage-component-id.md new file mode 100644 index 00000000..184b3502 --- /dev/null +++ b/doc/models/containers/create-usage-component-id.md @@ -0,0 +1,14 @@ + +# Create Usage Component Id + +## Class Name + +`CreateUsageComponentId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.CreateUsageComponentIdContainer.FromNumber(int number) | +| `string` | models.CreateUsageComponentIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/customer-change-billing-address.md b/doc/models/containers/customer-change-billing-address.md new file mode 100644 index 00000000..073044ee --- /dev/null +++ b/doc/models/containers/customer-change-billing-address.md @@ -0,0 +1,13 @@ + +# Customer Change Billing Address + +## Class Name + +`CustomerChangeBillingAddress` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.AddressChange`](../../../doc/models/address-change.md) | models.CustomerChangeBillingAddressContainer.FromAddressChange(models.AddressChange addressChange) | + diff --git a/doc/models/containers/customer-change-custom-fields.md b/doc/models/containers/customer-change-custom-fields.md new file mode 100644 index 00000000..1667eeb8 --- /dev/null +++ b/doc/models/containers/customer-change-custom-fields.md @@ -0,0 +1,13 @@ + +# Customer Change Custom Fields + +## Class Name + +`CustomerChangeCustomFields` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.CustomerCustomFieldsChange`](../../../doc/models/customer-custom-fields-change.md) | models.CustomerChangeCustomFieldsContainer.FromCustomerCustomFieldsChange(models.CustomerCustomFieldsChange customerCustomFieldsChange) | + diff --git a/doc/models/containers/customer-change-payer.md b/doc/models/containers/customer-change-payer.md new file mode 100644 index 00000000..4838db3a --- /dev/null +++ b/doc/models/containers/customer-change-payer.md @@ -0,0 +1,13 @@ + +# Customer Change Payer + +## Class Name + +`CustomerChangePayer` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.CustomerPayerChange`](../../../doc/models/customer-payer-change.md) | models.CustomerChangePayerContainer.FromCustomerPayerChange(models.CustomerPayerChange customerPayerChange) | + diff --git a/doc/models/containers/customer-change-shipping-address.md b/doc/models/containers/customer-change-shipping-address.md new file mode 100644 index 00000000..f7409636 --- /dev/null +++ b/doc/models/containers/customer-change-shipping-address.md @@ -0,0 +1,13 @@ + +# Customer Change Shipping Address + +## Class Name + +`CustomerChangeShippingAddress` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.AddressChange`](../../../doc/models/address-change.md) | models.CustomerChangeShippingAddressContainer.FromAddressChange(models.AddressChange addressChange) | + diff --git a/doc/models/containers/customer-error-response-errors.md b/doc/models/containers/customer-error-response-errors.md new file mode 100644 index 00000000..c6c62983 --- /dev/null +++ b/doc/models/containers/customer-error-response-errors.md @@ -0,0 +1,14 @@ + +# Customer Error Response Errors + +## Class Name + +`CustomerErrorResponseErrors` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.CustomerError`](../../../doc/models/customer-error.md) | models.CustomerErrorResponseErrorsContainer.FromCustomerError(models.CustomerError customerError) | +| `[]string` | models.CustomerErrorResponseErrorsContainer.FromArrayOfString([]string arrayOfString) | + diff --git a/doc/models/containers/deduct-service-credit-amount.md b/doc/models/containers/deduct-service-credit-amount.md new file mode 100644 index 00000000..3a56c2e7 --- /dev/null +++ b/doc/models/containers/deduct-service-credit-amount.md @@ -0,0 +1,14 @@ + +# Deduct Service Credit Amount + +## Class Name + +`DeductServiceCreditAmount` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.DeductServiceCreditAmountContainer.FromString(string mString) | +| `float64` | models.DeductServiceCreditAmountContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/ebb-component-unit-price.md b/doc/models/containers/ebb-component-unit-price.md new file mode 100644 index 00000000..1ecf0087 --- /dev/null +++ b/doc/models/containers/ebb-component-unit-price.md @@ -0,0 +1,14 @@ + +# EBB Component Unit Price + +## Class Name + +`EBBComponentUnitPrice` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.EBBComponentUnitPriceContainer.FromString(string mString) | +| `float64` | models.EBBComponentUnitPriceContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/event-event-specific-data.md b/doc/models/containers/event-event-specific-data.md new file mode 100644 index 00000000..97236be5 --- /dev/null +++ b/doc/models/containers/event-event-specific-data.md @@ -0,0 +1,31 @@ + +# Event Event Specific Data + +## Class Name + +`EventEventSpecificData` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.SubscriptionProductChange`](../../../doc/models/subscription-product-change.md) | models.EventEventSpecificDataContainer.FromSubscriptionProductChange(models.SubscriptionProductChange subscriptionProductChange) | +| [`models.SubscriptionStateChange`](../../../doc/models/subscription-state-change.md) | models.EventEventSpecificDataContainer.FromSubscriptionStateChange(models.SubscriptionStateChange subscriptionStateChange) | +| [`models.PaymentRelatedEvents`](../../../doc/models/payment-related-events.md) | models.EventEventSpecificDataContainer.FromPaymentRelatedEvents(models.PaymentRelatedEvents paymentRelatedEvents) | +| [`models.RefundSuccess`](../../../doc/models/refund-success.md) | models.EventEventSpecificDataContainer.FromRefundSuccess(models.RefundSuccess refundSuccess) | +| [`models.ComponentAllocationChange`](../../../doc/models/component-allocation-change.md) | models.EventEventSpecificDataContainer.FromComponentAllocationChange(models.ComponentAllocationChange componentAllocationChange) | +| [`models.MeteredUsage`](../../../doc/models/metered-usage.md) | models.EventEventSpecificDataContainer.FromMeteredUsage(models.MeteredUsage meteredUsage) | +| [`models.PrepaidUsage`](../../../doc/models/prepaid-usage.md) | models.EventEventSpecificDataContainer.FromPrepaidUsage(models.PrepaidUsage prepaidUsage) | +| [`models.DunningStepReached`](../../../doc/models/dunning-step-reached.md) | models.EventEventSpecificDataContainer.FromDunningStepReached(models.DunningStepReached dunningStepReached) | +| [`models.InvoiceIssued`](../../../doc/models/invoice-issued.md) | models.EventEventSpecificDataContainer.FromInvoiceIssued(models.InvoiceIssued invoiceIssued) | +| [`models.PendingCancellationChange`](../../../doc/models/pending-cancellation-change.md) | models.EventEventSpecificDataContainer.FromPendingCancellationChange(models.PendingCancellationChange pendingCancellationChange) | +| [`models.PrepaidSubscriptionBalanceChanged`](../../../doc/models/prepaid-subscription-balance-changed.md) | models.EventEventSpecificDataContainer.FromPrepaidSubscriptionBalanceChanged(models.PrepaidSubscriptionBalanceChanged prepaidSubscriptionBalanceChanged) | +| [`models.ProformaInvoiceIssued`](../../../doc/models/proforma-invoice-issued.md) | models.EventEventSpecificDataContainer.FromProformaInvoiceIssued(models.ProformaInvoiceIssued proformaInvoiceIssued) | +| [`models.SubscriptionGroupSignupSuccess`](../../../doc/models/subscription-group-signup-success.md) | models.EventEventSpecificDataContainer.FromSubscriptionGroupSignupSuccess(models.SubscriptionGroupSignupSuccess subscriptionGroupSignupSuccess) | +| [`models.SubscriptionGroupSignupFailure`](../../../doc/models/subscription-group-signup-failure.md) | models.EventEventSpecificDataContainer.FromSubscriptionGroupSignupFailure(models.SubscriptionGroupSignupFailure subscriptionGroupSignupFailure) | +| [`models.CreditAccountBalanceChanged`](../../../doc/models/credit-account-balance-changed.md) | models.EventEventSpecificDataContainer.FromCreditAccountBalanceChanged(models.CreditAccountBalanceChanged creditAccountBalanceChanged) | +| [`models.PrepaymentAccountBalanceChanged`](../../../doc/models/prepayment-account-balance-changed.md) | models.EventEventSpecificDataContainer.FromPrepaymentAccountBalanceChanged(models.PrepaymentAccountBalanceChanged prepaymentAccountBalanceChanged) | +| [`models.PaymentCollectionMethodChanged`](../../../doc/models/payment-collection-method-changed.md) | models.EventEventSpecificDataContainer.FromPaymentCollectionMethodChanged(models.PaymentCollectionMethodChanged paymentCollectionMethodChanged) | +| [`models.ItemPricePointChanged`](../../../doc/models/item-price-point-changed.md) | models.EventEventSpecificDataContainer.FromItemPricePointChanged(models.ItemPricePointChanged itemPricePointChanged) | +| [`models.CustomFieldValueChange`](../../../doc/models/custom-field-value-change.md) | models.EventEventSpecificDataContainer.FromCustomFieldValueChange(models.CustomFieldValueChange customFieldValueChange) | + diff --git a/doc/models/containers/invoice-event-data-payment-method.md b/doc/models/containers/invoice-event-data-payment-method.md new file mode 100644 index 00000000..b876e922 --- /dev/null +++ b/doc/models/containers/invoice-event-data-payment-method.md @@ -0,0 +1,17 @@ + +# Invoice Event Data Payment Method + +## Class Name + +`InvoiceEventDataPaymentMethod` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.PaymentMethodApplePay`](../../../doc/models/payment-method-apple-pay.md) | models.InvoiceEventDataPaymentMethodContainer.FromPaymentMethodApplePay(models.PaymentMethodApplePay paymentMethodApplePay) | +| [`models.PaymentMethodBankAccount`](../../../doc/models/payment-method-bank-account.md) | models.InvoiceEventDataPaymentMethodContainer.FromPaymentMethodBankAccount(models.PaymentMethodBankAccount paymentMethodBankAccount) | +| [`models.PaymentMethodCreditCard`](../../../doc/models/payment-method-credit-card.md) | models.InvoiceEventDataPaymentMethodContainer.FromPaymentMethodCreditCard(models.PaymentMethodCreditCard paymentMethodCreditCard) | +| [`models.PaymentMethodExternal`](../../../doc/models/payment-method-external.md) | models.InvoiceEventDataPaymentMethodContainer.FromPaymentMethodExternal(models.PaymentMethodExternal paymentMethodExternal) | +| [`models.PaymentMethodPaypal`](../../../doc/models/payment-method-paypal.md) | models.InvoiceEventDataPaymentMethodContainer.FromPaymentMethodPaypal(models.PaymentMethodPaypal paymentMethodPaypal) | + diff --git a/doc/models/containers/invoice-event-event-data.md b/doc/models/containers/invoice-event-event-data.md new file mode 100644 index 00000000..897ee977 --- /dev/null +++ b/doc/models/containers/invoice-event-event-data.md @@ -0,0 +1,21 @@ + +# Invoice Event Event Data + +## Class Name + +`InvoiceEventEventData` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.ApplyCreditNoteEventData`](../../../doc/models/apply-credit-note-event-data.md) | models.InvoiceEventEventDataContainer.FromApplyCreditNoteEventData(models.ApplyCreditNoteEventData applyCreditNoteEventData) | +| [`models.ApplyDebitNoteEventData`](../../../doc/models/apply-debit-note-event-data.md) | models.InvoiceEventEventDataContainer.FromApplyDebitNoteEventData(models.ApplyDebitNoteEventData applyDebitNoteEventData) | +| [`models.ApplyPaymentEventData`](../../../doc/models/apply-payment-event-data.md) | models.InvoiceEventEventDataContainer.FromApplyPaymentEventData(models.ApplyPaymentEventData applyPaymentEventData) | +| [`models.ChangeInvoiceCollectionMethodEventData`](../../../doc/models/change-invoice-collection-method-event-data.md) | models.InvoiceEventEventDataContainer.FromChangeInvoiceCollectionMethodEventData(models.ChangeInvoiceCollectionMethodEventData changeInvoiceCollectionMethodEventData) | +| [`models.IssueInvoiceEventData`](../../../doc/models/issue-invoice-event-data.md) | models.InvoiceEventEventDataContainer.FromIssueInvoiceEventData(models.IssueInvoiceEventData issueInvoiceEventData) | +| [`models.RefundInvoiceEventData`](../../../doc/models/refund-invoice-event-data.md) | models.InvoiceEventEventDataContainer.FromRefundInvoiceEventData(models.RefundInvoiceEventData refundInvoiceEventData) | +| [`models.RemovePaymentEventData`](../../../doc/models/remove-payment-event-data.md) | models.InvoiceEventEventDataContainer.FromRemovePaymentEventData(models.RemovePaymentEventData removePaymentEventData) | +| [`models.VoidInvoiceEventData`](../../../doc/models/void-invoice-event-data.md) | models.InvoiceEventEventDataContainer.FromVoidInvoiceEventData(models.VoidInvoiceEventData voidInvoiceEventData) | +| [`models.VoidRemainderEventData`](../../../doc/models/void-remainder-event-data.md) | models.InvoiceEventEventDataContainer.FromVoidRemainderEventData(models.VoidRemainderEventData voidRemainderEventData) | + diff --git a/doc/models/containers/invoice-event-payment-2.md b/doc/models/containers/invoice-event-payment-2.md new file mode 100644 index 00000000..c9f007d8 --- /dev/null +++ b/doc/models/containers/invoice-event-payment-2.md @@ -0,0 +1,17 @@ + +# Invoice Event Payment 2 + +## Class Name + +`InvoiceEventPayment2` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.PaymentMethodApplePay`](../../../doc/models/payment-method-apple-pay.md) | models.InvoiceEventPaymentContainer.FromPaymentMethodApplePay(models.PaymentMethodApplePay paymentMethodApplePay) | +| [`models.PaymentMethodBankAccount`](../../../doc/models/payment-method-bank-account.md) | models.InvoiceEventPaymentContainer.FromPaymentMethodBankAccount(models.PaymentMethodBankAccount paymentMethodBankAccount) | +| [`models.PaymentMethodCreditCard`](../../../doc/models/payment-method-credit-card.md) | models.InvoiceEventPaymentContainer.FromPaymentMethodCreditCard(models.PaymentMethodCreditCard paymentMethodCreditCard) | +| [`models.PaymentMethodExternal`](../../../doc/models/payment-method-external.md) | models.InvoiceEventPaymentContainer.FromPaymentMethodExternal(models.PaymentMethodExternal paymentMethodExternal) | +| [`models.PaymentMethodPaypal`](../../../doc/models/payment-method-paypal.md) | models.InvoiceEventPaymentContainer.FromPaymentMethodPaypal(models.PaymentMethodPaypal paymentMethodPaypal) | + diff --git a/doc/models/containers/invoice-line-item-component-cost-data-2.md b/doc/models/containers/invoice-line-item-component-cost-data-2.md new file mode 100644 index 00000000..9ac21055 --- /dev/null +++ b/doc/models/containers/invoice-line-item-component-cost-data-2.md @@ -0,0 +1,13 @@ + +# Invoice Line Item Component Cost Data 2 + +## Class Name + +`InvoiceLineItemComponentCostData2` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.InvoiceLineItemComponentCostData`](../../../doc/models/invoice-line-item-component-cost-data.md) | models.InvoiceLineItemComponentCostData2Container.FromInvoiceLineItemComponentCostData(models.InvoiceLineItemComponentCostData invoiceLineItemComponentCostData) | + diff --git a/doc/models/containers/issue-service-credit-amount.md b/doc/models/containers/issue-service-credit-amount.md new file mode 100644 index 00000000..531247fa --- /dev/null +++ b/doc/models/containers/issue-service-credit-amount.md @@ -0,0 +1,14 @@ + +# Issue Service Credit Amount + +## Class Name + +`IssueServiceCreditAmount` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `float64` | models.IssueServiceCreditAmountContainer.FromPrecision(float64 precision) | +| `string` | models.IssueServiceCreditAmountContainer.FromString(string mString) | + diff --git a/doc/models/containers/list-product-price-points-input-product-id.md b/doc/models/containers/list-product-price-points-input-product-id.md new file mode 100644 index 00000000..acf53dff --- /dev/null +++ b/doc/models/containers/list-product-price-points-input-product-id.md @@ -0,0 +1,14 @@ + +# List Product Price Points Input Product Id + +## Class Name + +`ListProductPricePointsInputProductId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.ListProductPricePointsInputProductIdContainer.FromNumber(int number) | +| `string` | models.ListProductPricePointsInputProductIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/list-usages-input-component-id.md b/doc/models/containers/list-usages-input-component-id.md new file mode 100644 index 00000000..56916699 --- /dev/null +++ b/doc/models/containers/list-usages-input-component-id.md @@ -0,0 +1,14 @@ + +# List Usages Input Component Id + +## Class Name + +`ListUsagesInputComponentId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.ListUsagesInputComponentIdContainer.FromNumber(int number) | +| `string` | models.ListUsagesInputComponentIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/metafield-enum.md b/doc/models/containers/metafield-enum.md new file mode 100644 index 00000000..f71317ae --- /dev/null +++ b/doc/models/containers/metafield-enum.md @@ -0,0 +1,14 @@ + +# Metafield Enum + +## Class Name + +`MetafieldEnum` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.MetafieldEnumContainer.FromString(string mString) | +| `[]string` | models.MetafieldEnumContainer.FromArrayOfString([]string arrayOfString) | + diff --git a/doc/models/containers/metered-component-unit-price.md b/doc/models/containers/metered-component-unit-price.md new file mode 100644 index 00000000..8f146d37 --- /dev/null +++ b/doc/models/containers/metered-component-unit-price.md @@ -0,0 +1,14 @@ + +# Metered Component Unit Price + +## Class Name + +`MeteredComponentUnitPrice` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.MeteredComponentUnitPriceContainer.FromString(string mString) | +| `float64` | models.MeteredComponentUnitPriceContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/on-off-component-unit-price.md b/doc/models/containers/on-off-component-unit-price.md new file mode 100644 index 00000000..33ff7e7c --- /dev/null +++ b/doc/models/containers/on-off-component-unit-price.md @@ -0,0 +1,14 @@ + +# On Off Component Unit Price + +## Class Name + +`OnOffComponentUnitPrice` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.OnOffComponentUnitPriceContainer.FromString(string mString) | +| `float64` | models.OnOffComponentUnitPriceContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/payment-profile-attributes-expiration-month.md b/doc/models/containers/payment-profile-attributes-expiration-month.md new file mode 100644 index 00000000..ba85dc21 --- /dev/null +++ b/doc/models/containers/payment-profile-attributes-expiration-month.md @@ -0,0 +1,14 @@ + +# Payment Profile Attributes Expiration Month + +## Class Name + +`PaymentProfileAttributesExpirationMonth` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.PaymentProfileAttributesExpirationMonthContainer.FromNumber(int number) | +| `string` | models.PaymentProfileAttributesExpirationMonthContainer.FromString(string mString) | + diff --git a/doc/models/containers/payment-profile-attributes-expiration-year.md b/doc/models/containers/payment-profile-attributes-expiration-year.md new file mode 100644 index 00000000..e99013af --- /dev/null +++ b/doc/models/containers/payment-profile-attributes-expiration-year.md @@ -0,0 +1,14 @@ + +# Payment Profile Attributes Expiration Year + +## Class Name + +`PaymentProfileAttributesExpirationYear` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.PaymentProfileAttributesExpirationYearContainer.FromNumber(int number) | +| `string` | models.PaymentProfileAttributesExpirationYearContainer.FromString(string mString) | + diff --git a/doc/models/containers/payment-profile-response-payment-profile.md b/doc/models/containers/payment-profile-response-payment-profile.md new file mode 100644 index 00000000..5d16c5eb --- /dev/null +++ b/doc/models/containers/payment-profile-response-payment-profile.md @@ -0,0 +1,14 @@ + +# Payment Profile Response Payment Profile + +## Class Name + +`PaymentProfileResponsePaymentProfile` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.BankAccountPaymentProfile`](../../../doc/models/bank-account-payment-profile.md) | models.PaymentProfileResponsePaymentProfileContainer.FromBankAccountPaymentProfile(models.BankAccountPaymentProfile bankAccountPaymentProfile) | +| [`models.CreditCardPaymentProfile`](../../../doc/models/credit-card-payment-profile.md) | models.PaymentProfileResponsePaymentProfileContainer.FromCreditCardPaymentProfile(models.CreditCardPaymentProfile creditCardPaymentProfile) | + diff --git a/doc/models/containers/prepaid-usage-component-unit-price.md b/doc/models/containers/prepaid-usage-component-unit-price.md new file mode 100644 index 00000000..ae0d4d3a --- /dev/null +++ b/doc/models/containers/prepaid-usage-component-unit-price.md @@ -0,0 +1,14 @@ + +# Prepaid Usage Component Unit Price + +## Class Name + +`PrepaidUsageComponentUnitPrice` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.PrepaidUsageComponentUnitPriceContainer.FromString(string mString) | +| `float64` | models.PrepaidUsageComponentUnitPriceContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/price-ending-quantity.md b/doc/models/containers/price-ending-quantity.md new file mode 100644 index 00000000..784e26f7 --- /dev/null +++ b/doc/models/containers/price-ending-quantity.md @@ -0,0 +1,14 @@ + +# Price Ending Quantity + +## Class Name + +`PriceEndingQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.PriceEndingQuantityContainer.FromNumber(int number) | +| `string` | models.PriceEndingQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/price-starting-quantity.md b/doc/models/containers/price-starting-quantity.md new file mode 100644 index 00000000..ba348732 --- /dev/null +++ b/doc/models/containers/price-starting-quantity.md @@ -0,0 +1,14 @@ + +# Price Starting Quantity + +## Class Name + +`PriceStartingQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.PriceStartingQuantityContainer.FromNumber(int number) | +| `string` | models.PriceStartingQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/price-unit-price.md b/doc/models/containers/price-unit-price.md new file mode 100644 index 00000000..bb1e6f50 --- /dev/null +++ b/doc/models/containers/price-unit-price.md @@ -0,0 +1,14 @@ + +# Price Unit Price + +## Class Name + +`PriceUnitPrice` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `float64` | models.PriceUnitPriceContainer.FromPrecision(float64 precision) | +| `string` | models.PriceUnitPriceContainer.FromString(string mString) | + diff --git a/doc/models/containers/product-expiration-interval-unit.md b/doc/models/containers/product-expiration-interval-unit.md new file mode 100644 index 00000000..ad1d5141 --- /dev/null +++ b/doc/models/containers/product-expiration-interval-unit.md @@ -0,0 +1,13 @@ + +# Product Expiration Interval Unit + +## Class Name + +`ProductExpirationIntervalUnit` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.ExtendedIntervalUnit`](../../../doc/models/extended-interval-unit.md) | models.ProductExpirationIntervalUnitContainer.FromExtendedIntervalUnit(models.ExtendedIntervalUnit extendedIntervalUnit) | + diff --git a/doc/models/containers/product-trial-interval-unit.md b/doc/models/containers/product-trial-interval-unit.md new file mode 100644 index 00000000..3f3f0683 --- /dev/null +++ b/doc/models/containers/product-trial-interval-unit.md @@ -0,0 +1,13 @@ + +# Product Trial Interval Unit + +## Class Name + +`ProductTrialIntervalUnit` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.IntervalUnit`](../../../doc/models/interval-unit.md) | models.ProductTrialIntervalUnitContainer.FromIntervalUnit(models.IntervalUnit intervalUnit) | + diff --git a/doc/models/containers/quantity-based-component-unit-price.md b/doc/models/containers/quantity-based-component-unit-price.md new file mode 100644 index 00000000..0247c70b --- /dev/null +++ b/doc/models/containers/quantity-based-component-unit-price.md @@ -0,0 +1,14 @@ + +# Quantity Based Component Unit Price + +## Class Name + +`QuantityBasedComponentUnitPrice` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.QuantityBasedComponentUnitPriceContainer.FromString(string mString) | +| `float64` | models.QuantityBasedComponentUnitPriceContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/reactivate-subscription-request-resume.md b/doc/models/containers/reactivate-subscription-request-resume.md new file mode 100644 index 00000000..fffe2542 --- /dev/null +++ b/doc/models/containers/reactivate-subscription-request-resume.md @@ -0,0 +1,14 @@ + +# Reactivate Subscription Request Resume + +## Class Name + +`ReactivateSubscriptionRequestResume` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `bool` | models.ReactivateSubscriptionRequestResumeContainer.FromBoolean(bool boolean) | +| [`models.ResumeOptions`](../../../doc/models/resume-options.md) | models.ReactivateSubscriptionRequestResumeContainer.FromResumeOptions(models.ResumeOptions resumeOptions) | + diff --git a/doc/models/containers/read-product-price-point-price-point-id.md b/doc/models/containers/read-product-price-point-price-point-id.md new file mode 100644 index 00000000..65d8a14a --- /dev/null +++ b/doc/models/containers/read-product-price-point-price-point-id.md @@ -0,0 +1,14 @@ + +# Read Product Price Point Price Point Id + +## Class Name + +`ReadProductPricePointPricePointId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.ReadProductPricePointPricePointIdContainer.FromNumber(int number) | +| `string` | models.ReadProductPricePointPricePointIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/read-product-price-point-product-id.md b/doc/models/containers/read-product-price-point-product-id.md new file mode 100644 index 00000000..678c2824 --- /dev/null +++ b/doc/models/containers/read-product-price-point-product-id.md @@ -0,0 +1,14 @@ + +# Read Product Price Point Product Id + +## Class Name + +`ReadProductPricePointProductId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.ReadProductPricePointProductIdContainer.FromNumber(int number) | +| `string` | models.ReadProductPricePointProductIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/record-payment-response-prepayment.md b/doc/models/containers/record-payment-response-prepayment.md new file mode 100644 index 00000000..7adca76e --- /dev/null +++ b/doc/models/containers/record-payment-response-prepayment.md @@ -0,0 +1,13 @@ + +# Record Payment Response Prepayment + +## Class Name + +`RecordPaymentResponsePrepayment` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.InvoicePrePayment`](../../../doc/models/invoice-pre-payment.md) | models.RecordPaymentResponsePrepaymentContainer.FromInvoicePrePayment(models.InvoicePrePayment invoicePrePayment) | + diff --git a/doc/models/containers/refund-consolidated-invoice-segment-uids.md b/doc/models/containers/refund-consolidated-invoice-segment-uids.md new file mode 100644 index 00000000..0a402c27 --- /dev/null +++ b/doc/models/containers/refund-consolidated-invoice-segment-uids.md @@ -0,0 +1,14 @@ + +# Refund Consolidated Invoice Segment Uids + +## Class Name + +`RefundConsolidatedInvoiceSegmentUids` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `[]string` | models.RefundConsolidatedInvoiceSegmentUidsContainer.FromArrayOfString([]string arrayOfString) | +| `string` | models.RefundConsolidatedInvoiceSegmentUidsContainer.FromString(string mString) | + diff --git a/doc/models/containers/refund-invoice-request-refund.md b/doc/models/containers/refund-invoice-request-refund.md new file mode 100644 index 00000000..2e0acb8e --- /dev/null +++ b/doc/models/containers/refund-invoice-request-refund.md @@ -0,0 +1,14 @@ + +# Refund Invoice Request Refund + +## Class Name + +`RefundInvoiceRequestRefund` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.RefundInvoice`](../../../doc/models/refund-invoice.md) | models.RefundInvoiceRequestRefundContainer.FromRefundInvoice(models.RefundInvoice refundInvoice) | +| [`models.RefundConsolidatedInvoice`](../../../doc/models/refund-consolidated-invoice.md) | models.RefundInvoiceRequestRefundContainer.FromRefundConsolidatedInvoice(models.RefundConsolidatedInvoice refundConsolidatedInvoice) | + diff --git a/doc/models/containers/refund-prepayment-amount.md b/doc/models/containers/refund-prepayment-amount.md new file mode 100644 index 00000000..34ba7624 --- /dev/null +++ b/doc/models/containers/refund-prepayment-amount.md @@ -0,0 +1,14 @@ + +# Refund Prepayment Amount + +## Class Name + +`RefundPrepaymentAmount` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.RefundPrepaymentAmountContainer.FromString(string mString) | +| `float64` | models.RefundPrepaymentAmountContainer.FromPrecision(float64 precision) | + diff --git a/doc/models/containers/refund-segment-uids.md b/doc/models/containers/refund-segment-uids.md new file mode 100644 index 00000000..af6a673c --- /dev/null +++ b/doc/models/containers/refund-segment-uids.md @@ -0,0 +1,14 @@ + +# Refund Segment Uids + +## Class Name + +`RefundSegmentUids` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `[]string` | models.RefundSegmentUidsContainer.FromArrayOfString([]string arrayOfString) | +| `string` | models.RefundSegmentUidsContainer.FromString(string mString) | + diff --git a/doc/models/containers/renewal-preview-component-component-id.md b/doc/models/containers/renewal-preview-component-component-id.md new file mode 100644 index 00000000..535c0d7a --- /dev/null +++ b/doc/models/containers/renewal-preview-component-component-id.md @@ -0,0 +1,14 @@ + +# Renewal Preview Component Component Id + +## Class Name + +`RenewalPreviewComponentComponentId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.RenewalPreviewComponentComponentIdContainer.FromString(string mString) | +| `int` | models.RenewalPreviewComponentComponentIdContainer.FromNumber(int number) | + diff --git a/doc/models/containers/renewal-preview-component-price-point-id.md b/doc/models/containers/renewal-preview-component-price-point-id.md new file mode 100644 index 00000000..457d72cb --- /dev/null +++ b/doc/models/containers/renewal-preview-component-price-point-id.md @@ -0,0 +1,14 @@ + +# Renewal Preview Component Price Point Id + +## Class Name + +`RenewalPreviewComponentPricePointId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.RenewalPreviewComponentPricePointIdContainer.FromString(string mString) | +| `int` | models.RenewalPreviewComponentPricePointIdContainer.FromNumber(int number) | + diff --git a/doc/models/containers/segment-segment-property-1-value.md b/doc/models/containers/segment-segment-property-1-value.md new file mode 100644 index 00000000..13c577b6 --- /dev/null +++ b/doc/models/containers/segment-segment-property-1-value.md @@ -0,0 +1,16 @@ + +# Segment Segment Property 1 Value + +## Class Name + +`SegmentSegmentProperty1Value` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SegmentSegmentProperty1ValueContainer.FromString(string mString) | +| `float64` | models.SegmentSegmentProperty1ValueContainer.FromPrecision(float64 precision) | +| `int` | models.SegmentSegmentProperty1ValueContainer.FromNumber(int number) | +| `bool` | models.SegmentSegmentProperty1ValueContainer.FromBoolean(bool boolean) | + diff --git a/doc/models/containers/segment-segment-property-2-value.md b/doc/models/containers/segment-segment-property-2-value.md new file mode 100644 index 00000000..9b99e7e1 --- /dev/null +++ b/doc/models/containers/segment-segment-property-2-value.md @@ -0,0 +1,16 @@ + +# Segment Segment Property 2 Value + +## Class Name + +`SegmentSegmentProperty2Value` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SegmentSegmentProperty2ValueContainer.FromString(string mString) | +| `float64` | models.SegmentSegmentProperty2ValueContainer.FromPrecision(float64 precision) | +| `int` | models.SegmentSegmentProperty2ValueContainer.FromNumber(int number) | +| `bool` | models.SegmentSegmentProperty2ValueContainer.FromBoolean(bool boolean) | + diff --git a/doc/models/containers/segment-segment-property-3-value.md b/doc/models/containers/segment-segment-property-3-value.md new file mode 100644 index 00000000..2e910f48 --- /dev/null +++ b/doc/models/containers/segment-segment-property-3-value.md @@ -0,0 +1,16 @@ + +# Segment Segment Property 3 Value + +## Class Name + +`SegmentSegmentProperty3Value` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SegmentSegmentProperty3ValueContainer.FromString(string mString) | +| `float64` | models.SegmentSegmentProperty3ValueContainer.FromPrecision(float64 precision) | +| `int` | models.SegmentSegmentProperty3ValueContainer.FromNumber(int number) | +| `bool` | models.SegmentSegmentProperty3ValueContainer.FromBoolean(bool boolean) | + diff --git a/doc/models/containers/segment-segment-property-4-value.md b/doc/models/containers/segment-segment-property-4-value.md new file mode 100644 index 00000000..3927caa2 --- /dev/null +++ b/doc/models/containers/segment-segment-property-4-value.md @@ -0,0 +1,16 @@ + +# Segment Segment Property 4 Value + +## Class Name + +`SegmentSegmentProperty4Value` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SegmentSegmentProperty4ValueContainer.FromString(string mString) | +| `float64` | models.SegmentSegmentProperty4ValueContainer.FromPrecision(float64 precision) | +| `int` | models.SegmentSegmentProperty4ValueContainer.FromNumber(int number) | +| `bool` | models.SegmentSegmentProperty4ValueContainer.FromBoolean(bool boolean) | + diff --git a/doc/models/containers/subscription-component-allocated-quantity.md b/doc/models/containers/subscription-component-allocated-quantity.md new file mode 100644 index 00000000..0f6a372f --- /dev/null +++ b/doc/models/containers/subscription-component-allocated-quantity.md @@ -0,0 +1,14 @@ + +# Subscription Component Allocated Quantity + +## Class Name + +`SubscriptionComponentAllocatedQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.SubscriptionComponentAllocatedQuantityContainer.FromNumber(int number) | +| `string` | models.SubscriptionComponentAllocatedQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/subscription-component-price-point-type.md b/doc/models/containers/subscription-component-price-point-type.md new file mode 100644 index 00000000..3e074fcf --- /dev/null +++ b/doc/models/containers/subscription-component-price-point-type.md @@ -0,0 +1,13 @@ + +# Subscription Component Price Point Type + +## Class Name + +`SubscriptionComponentPricePointType` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.PricePointType`](../../../doc/models/price-point-type.md) | models.SubscriptionComponentPricePointTypeContainer.FromPricePointType(models.PricePointType pricePointType) | + diff --git a/doc/models/containers/subscription-component-pricing-scheme.md b/doc/models/containers/subscription-component-pricing-scheme.md new file mode 100644 index 00000000..174e1628 --- /dev/null +++ b/doc/models/containers/subscription-component-pricing-scheme.md @@ -0,0 +1,13 @@ + +# Subscription Component Pricing Scheme + +## Class Name + +`SubscriptionComponentPricingScheme` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.PricingScheme`](../../../doc/models/pricing-scheme.md) | models.SubscriptionComponentPricingSchemeContainer.FromPricingScheme(models.PricingScheme pricingScheme) | + diff --git a/doc/models/containers/subscription-custom-price-expiration-interval.md b/doc/models/containers/subscription-custom-price-expiration-interval.md new file mode 100644 index 00000000..c5ede2b1 --- /dev/null +++ b/doc/models/containers/subscription-custom-price-expiration-interval.md @@ -0,0 +1,14 @@ + +# Subscription Custom Price Expiration Interval + +## Class Name + +`SubscriptionCustomPriceExpirationInterval` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionCustomPriceExpirationIntervalContainer.FromString(string mString) | +| `int` | models.SubscriptionCustomPriceExpirationIntervalContainer.FromNumber(int number) | + diff --git a/doc/models/containers/subscription-custom-price-initial-charge-in-cents.md b/doc/models/containers/subscription-custom-price-initial-charge-in-cents.md new file mode 100644 index 00000000..b1111677 --- /dev/null +++ b/doc/models/containers/subscription-custom-price-initial-charge-in-cents.md @@ -0,0 +1,14 @@ + +# Subscription Custom Price Initial Charge in Cents + +## Class Name + +`SubscriptionCustomPriceInitialChargeInCents` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionCustomPriceInitialChargeInCentsContainer.FromString(string mString) | +| `int64` | models.SubscriptionCustomPriceInitialChargeInCentsContainer.FromLong(int64 long) | + diff --git a/doc/models/containers/subscription-custom-price-interval.md b/doc/models/containers/subscription-custom-price-interval.md new file mode 100644 index 00000000..dca51fb4 --- /dev/null +++ b/doc/models/containers/subscription-custom-price-interval.md @@ -0,0 +1,14 @@ + +# Subscription Custom Price Interval + +## Class Name + +`SubscriptionCustomPriceInterval` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionCustomPriceIntervalContainer.FromString(string mString) | +| `int` | models.SubscriptionCustomPriceIntervalContainer.FromNumber(int number) | + diff --git a/doc/models/containers/subscription-custom-price-price-in-cents.md b/doc/models/containers/subscription-custom-price-price-in-cents.md new file mode 100644 index 00000000..8f6be6ab --- /dev/null +++ b/doc/models/containers/subscription-custom-price-price-in-cents.md @@ -0,0 +1,14 @@ + +# Subscription Custom Price Price in Cents + +## Class Name + +`SubscriptionCustomPricePriceInCents` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionCustomPricePriceInCentsContainer.FromString(string mString) | +| `int64` | models.SubscriptionCustomPricePriceInCentsContainer.FromLong(int64 long) | + diff --git a/doc/models/containers/subscription-custom-price-trial-interval.md b/doc/models/containers/subscription-custom-price-trial-interval.md new file mode 100644 index 00000000..80e34e8f --- /dev/null +++ b/doc/models/containers/subscription-custom-price-trial-interval.md @@ -0,0 +1,14 @@ + +# Subscription Custom Price Trial Interval + +## Class Name + +`SubscriptionCustomPriceTrialInterval` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionCustomPriceTrialIntervalContainer.FromString(string mString) | +| `int` | models.SubscriptionCustomPriceTrialIntervalContainer.FromNumber(int number) | + diff --git a/doc/models/containers/subscription-custom-price-trial-price-in-cents.md b/doc/models/containers/subscription-custom-price-trial-price-in-cents.md new file mode 100644 index 00000000..6fa96274 --- /dev/null +++ b/doc/models/containers/subscription-custom-price-trial-price-in-cents.md @@ -0,0 +1,14 @@ + +# Subscription Custom Price Trial Price in Cents + +## Class Name + +`SubscriptionCustomPriceTrialPriceInCents` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionCustomPriceTrialPriceInCentsContainer.FromString(string mString) | +| `int64` | models.SubscriptionCustomPriceTrialPriceInCentsContainer.FromLong(int64 long) | + diff --git a/doc/models/containers/subscription-group-2.md b/doc/models/containers/subscription-group-2.md new file mode 100644 index 00000000..e79a3ee4 --- /dev/null +++ b/doc/models/containers/subscription-group-2.md @@ -0,0 +1,13 @@ + +# Subscription Group 2 + +## Class Name + +`SubscriptionGroup2` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.NestedSubscriptionGroup`](../../../doc/models/nested-subscription-group.md) | models.SubscriptionGroup2Container.FromNestedSubscriptionGroup(models.NestedSubscriptionGroup nestedSubscriptionGroup) | + diff --git a/doc/models/containers/subscription-group-create-error-response-errors.md b/doc/models/containers/subscription-group-create-error-response-errors.md new file mode 100644 index 00000000..a987530b --- /dev/null +++ b/doc/models/containers/subscription-group-create-error-response-errors.md @@ -0,0 +1,15 @@ + +# Subscription Group Create Error Response Errors + +## Class Name + +`SubscriptionGroupCreateErrorResponseErrors` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.SubscriptionGroupMembersArrayError`](../../../doc/models/subscription-group-members-array-error.md) | models.SubscriptionGroupCreateErrorResponseErrorsContainer.FromSubscriptionGroupMembersArrayError(models.SubscriptionGroupMembersArrayError subscriptionGroupMembersArrayError) | +| [`models.SubscriptionGroupSingleError`](../../../doc/models/subscription-group-single-error.md) | models.SubscriptionGroupCreateErrorResponseErrorsContainer.FromSubscriptionGroupSingleError(models.SubscriptionGroupSingleError subscriptionGroupSingleError) | +| `string` | models.SubscriptionGroupCreateErrorResponseErrorsContainer.FromString(string mString) | + diff --git a/doc/models/containers/subscription-group-credit-card-expiration-month.md b/doc/models/containers/subscription-group-credit-card-expiration-month.md new file mode 100644 index 00000000..44fa51df --- /dev/null +++ b/doc/models/containers/subscription-group-credit-card-expiration-month.md @@ -0,0 +1,14 @@ + +# Subscription Group Credit Card Expiration Month + +## Class Name + +`SubscriptionGroupCreditCardExpirationMonth` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionGroupCreditCardExpirationMonthContainer.FromString(string mString) | +| `int` | models.SubscriptionGroupCreditCardExpirationMonthContainer.FromNumber(int number) | + diff --git a/doc/models/containers/subscription-group-credit-card-expiration-year.md b/doc/models/containers/subscription-group-credit-card-expiration-year.md new file mode 100644 index 00000000..e3d88acc --- /dev/null +++ b/doc/models/containers/subscription-group-credit-card-expiration-year.md @@ -0,0 +1,14 @@ + +# Subscription Group Credit Card Expiration Year + +## Class Name + +`SubscriptionGroupCreditCardExpirationYear` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionGroupCreditCardExpirationYearContainer.FromString(string mString) | +| `int` | models.SubscriptionGroupCreditCardExpirationYearContainer.FromNumber(int number) | + diff --git a/doc/models/containers/subscription-group-credit-card-full-number.md b/doc/models/containers/subscription-group-credit-card-full-number.md new file mode 100644 index 00000000..e988b58e --- /dev/null +++ b/doc/models/containers/subscription-group-credit-card-full-number.md @@ -0,0 +1,14 @@ + +# Subscription Group Credit Card Full Number + +## Class Name + +`SubscriptionGroupCreditCardFullNumber` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionGroupCreditCardFullNumberContainer.FromString(string mString) | +| `int` | models.SubscriptionGroupCreditCardFullNumberContainer.FromNumber(int number) | + diff --git a/doc/models/containers/subscription-group-signup-component-allocated-quantity.md b/doc/models/containers/subscription-group-signup-component-allocated-quantity.md new file mode 100644 index 00000000..65225c45 --- /dev/null +++ b/doc/models/containers/subscription-group-signup-component-allocated-quantity.md @@ -0,0 +1,14 @@ + +# Subscription Group Signup Component Allocated Quantity + +## Class Name + +`SubscriptionGroupSignupComponentAllocatedQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionGroupSignupComponentAllocatedQuantityContainer.FromString(string mString) | +| `int` | models.SubscriptionGroupSignupComponentAllocatedQuantityContainer.FromNumber(int number) | + diff --git a/doc/models/containers/subscription-group-signup-component-component-id.md b/doc/models/containers/subscription-group-signup-component-component-id.md new file mode 100644 index 00000000..5ead316d --- /dev/null +++ b/doc/models/containers/subscription-group-signup-component-component-id.md @@ -0,0 +1,14 @@ + +# Subscription Group Signup Component Component Id + +## Class Name + +`SubscriptionGroupSignupComponentComponentId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionGroupSignupComponentComponentIdContainer.FromString(string mString) | +| `int` | models.SubscriptionGroupSignupComponentComponentIdContainer.FromNumber(int number) | + diff --git a/doc/models/containers/subscription-group-signup-component-price-point-id.md b/doc/models/containers/subscription-group-signup-component-price-point-id.md new file mode 100644 index 00000000..76d9a8cb --- /dev/null +++ b/doc/models/containers/subscription-group-signup-component-price-point-id.md @@ -0,0 +1,14 @@ + +# Subscription Group Signup Component Price Point Id + +## Class Name + +`SubscriptionGroupSignupComponentPricePointId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionGroupSignupComponentPricePointIdContainer.FromString(string mString) | +| `int` | models.SubscriptionGroupSignupComponentPricePointIdContainer.FromNumber(int number) | + diff --git a/doc/models/containers/subscription-group-signup-component-unit-balance.md b/doc/models/containers/subscription-group-signup-component-unit-balance.md new file mode 100644 index 00000000..4b418d4c --- /dev/null +++ b/doc/models/containers/subscription-group-signup-component-unit-balance.md @@ -0,0 +1,14 @@ + +# Subscription Group Signup Component Unit Balance + +## Class Name + +`SubscriptionGroupSignupComponentUnitBalance` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.SubscriptionGroupSignupComponentUnitBalanceContainer.FromString(string mString) | +| `int` | models.SubscriptionGroupSignupComponentUnitBalanceContainer.FromNumber(int number) | + diff --git a/doc/models/containers/update-metafields-request-metafields.md b/doc/models/containers/update-metafields-request-metafields.md new file mode 100644 index 00000000..6645ffc3 --- /dev/null +++ b/doc/models/containers/update-metafields-request-metafields.md @@ -0,0 +1,14 @@ + +# Update Metafields Request Metafields + +## Class Name + +`UpdateMetafieldsRequestMetafields` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.UpdateMetafield`](../../../doc/models/update-metafield.md) | models.UpdateMetafieldsRequestMetafieldsContainer.FromUpdateMetafield(models.UpdateMetafield updateMetafield) | +| [`[]models.UpdateMetafield`](../../../doc/models/update-metafield.md) | models.UpdateMetafieldsRequestMetafieldsContainer.FromArrayOfUpdateMetafield([]models.UpdateMetafield arrayOfUpdateMetafield) | + diff --git a/doc/models/containers/update-price-ending-quantity.md b/doc/models/containers/update-price-ending-quantity.md new file mode 100644 index 00000000..bac7dee5 --- /dev/null +++ b/doc/models/containers/update-price-ending-quantity.md @@ -0,0 +1,14 @@ + +# Update Price Ending Quantity + +## Class Name + +`UpdatePriceEndingQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.UpdatePriceEndingQuantityContainer.FromNumber(int number) | +| `string` | models.UpdatePriceEndingQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/update-price-starting-quantity.md b/doc/models/containers/update-price-starting-quantity.md new file mode 100644 index 00000000..8be0a601 --- /dev/null +++ b/doc/models/containers/update-price-starting-quantity.md @@ -0,0 +1,14 @@ + +# Update Price Starting Quantity + +## Class Name + +`UpdatePriceStartingQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.UpdatePriceStartingQuantityContainer.FromNumber(int number) | +| `string` | models.UpdatePriceStartingQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/update-price-unit-price.md b/doc/models/containers/update-price-unit-price.md new file mode 100644 index 00000000..9c007ade --- /dev/null +++ b/doc/models/containers/update-price-unit-price.md @@ -0,0 +1,14 @@ + +# Update Price Unit Price + +## Class Name + +`UpdatePriceUnitPrice` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `float64` | models.UpdatePriceUnitPriceContainer.FromPrecision(float64 precision) | +| `string` | models.UpdatePriceUnitPriceContainer.FromString(string mString) | + diff --git a/doc/models/containers/update-product-price-point-price-point-id.md b/doc/models/containers/update-product-price-point-price-point-id.md new file mode 100644 index 00000000..274b4f39 --- /dev/null +++ b/doc/models/containers/update-product-price-point-price-point-id.md @@ -0,0 +1,14 @@ + +# Update Product Price Point Price Point Id + +## Class Name + +`UpdateProductPricePointPricePointId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.UpdateProductPricePointPricePointIdContainer.FromNumber(int number) | +| `string` | models.UpdateProductPricePointPricePointIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/update-product-price-point-product-id.md b/doc/models/containers/update-product-price-point-product-id.md new file mode 100644 index 00000000..e29c050d --- /dev/null +++ b/doc/models/containers/update-product-price-point-product-id.md @@ -0,0 +1,14 @@ + +# Update Product Price Point Product Id + +## Class Name + +`UpdateProductPricePointProductId` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.UpdateProductPricePointProductIdContainer.FromNumber(int number) | +| `string` | models.UpdateProductPricePointProductIdContainer.FromString(string mString) | + diff --git a/doc/models/containers/update-subscription-net-terms.md b/doc/models/containers/update-subscription-net-terms.md new file mode 100644 index 00000000..3ccb1c2b --- /dev/null +++ b/doc/models/containers/update-subscription-net-terms.md @@ -0,0 +1,14 @@ + +# Update Subscription Net Terms + +## Class Name + +`UpdateSubscriptionNetTerms` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `string` | models.UpdateSubscriptionNetTermsContainer.FromString(string mString) | +| `int` | models.UpdateSubscriptionNetTermsContainer.FromNumber(int number) | + diff --git a/doc/models/containers/update-subscription-snap-day.md b/doc/models/containers/update-subscription-snap-day.md new file mode 100644 index 00000000..baa6efa3 --- /dev/null +++ b/doc/models/containers/update-subscription-snap-day.md @@ -0,0 +1,14 @@ + +# Update Subscription Snap Day + +## Class Name + +`UpdateSubscriptionSnapDay` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.SnapDay`](../../../doc/models/snap-day.md) | models.UpdateSubscriptionSnapDayContainer.FromSnapDay(models.SnapDay snapDay) | +| `int` | models.UpdateSubscriptionSnapDayContainer.FromNumber(int number) | + diff --git a/doc/models/containers/usage-quantity.md b/doc/models/containers/usage-quantity.md new file mode 100644 index 00000000..55e99a47 --- /dev/null +++ b/doc/models/containers/usage-quantity.md @@ -0,0 +1,14 @@ + +# Usage Quantity + +## Class Name + +`UsageQuantity` + +## Cases + +| Type | Factory Method | +| --- | --- | +| `int` | models.UsageQuantityContainer.FromNumber(int number) | +| `string` | models.UsageQuantityContainer.FromString(string mString) | + diff --git a/doc/models/containers/void-invoice-event-data-credit-note-attributes.md b/doc/models/containers/void-invoice-event-data-credit-note-attributes.md new file mode 100644 index 00000000..a60ddb29 --- /dev/null +++ b/doc/models/containers/void-invoice-event-data-credit-note-attributes.md @@ -0,0 +1,13 @@ + +# Void Invoice Event Data Credit Note Attributes + +## Class Name + +`VoidInvoiceEventDataCreditNoteAttributes` + +## Cases + +| Type | Factory Method | +| --- | --- | +| [`models.CreditNote`](../../../doc/models/credit-note.md) | models.VoidInvoiceEventDataCreditNoteAttributesContainer.FromCreditNote(models.CreditNote creditNote) | + diff --git a/doc/models/count-response.md b/doc/models/count-response.md index 033525a0..7b584cb9 100644 --- a/doc/models/count-response.md +++ b/doc/models/count-response.md @@ -1,21 +1,21 @@ - -# Count Response - -## Structure - -`CountResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Count` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "count": 60 -} -``` - + +# Count Response + +## Structure + +`CountResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Count` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "count": 60 +} +``` + diff --git a/doc/models/coupon-currency-request.md b/doc/models/coupon-currency-request.md index 7eadcabb..e830058c 100644 --- a/doc/models/coupon-currency-request.md +++ b/doc/models/coupon-currency-request.md @@ -1,26 +1,26 @@ - -# Coupon Currency Request - -## Structure - -`CouponCurrencyRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CurrencyPrices` | [`[]models.UpdateCouponCurrency`](../../doc/models/update-coupon-currency.md) | Required | - | - -## Example (as JSON) - -```json -{ - "currency_prices": [ - { - "currency": "currency8", - "price": 78 - } - ] -} -``` - + +# Coupon Currency Request + +## Structure + +`CouponCurrencyRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrencyPrices` | [`[]models.UpdateCouponCurrency`](../../doc/models/update-coupon-currency.md) | Required | - | + +## Example (as JSON) + +```json +{ + "currency_prices": [ + { + "currency": "currency8", + "price": 78 + } + ] +} +``` + diff --git a/doc/models/coupon-currency-response.md b/doc/models/coupon-currency-response.md index 6c2206b6..5c72de8f 100644 --- a/doc/models/coupon-currency-response.md +++ b/doc/models/coupon-currency-response.md @@ -1,40 +1,40 @@ - -# Coupon Currency Response - -## Structure - -`CouponCurrencyResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CurrencyPrices` | [`[]models.CouponCurrency`](../../doc/models/coupon-currency.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "currency_prices": [ - { - "id": 50, - "currency": "currency8", - "price": 78, - "coupon_id": 224 - }, - { - "id": 50, - "currency": "currency8", - "price": 78, - "coupon_id": 224 - }, - { - "id": 50, - "currency": "currency8", - "price": 78, - "coupon_id": 224 - } - ] -} -``` - + +# Coupon Currency Response + +## Structure + +`CouponCurrencyResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrencyPrices` | [`[]models.CouponCurrency`](../../doc/models/coupon-currency.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "currency_prices": [ + { + "id": 50, + "currency": "currency8", + "price": 78, + "coupon_id": 224 + }, + { + "id": 50, + "currency": "currency8", + "price": 78, + "coupon_id": 224 + }, + { + "id": 50, + "currency": "currency8", + "price": 78, + "coupon_id": 224 + } + ] +} +``` + diff --git a/doc/models/coupon-currency.md b/doc/models/coupon-currency.md index e4e88d32..9d611507 100644 --- a/doc/models/coupon-currency.md +++ b/doc/models/coupon-currency.md @@ -1,27 +1,27 @@ - -# Coupon Currency - -## Structure - -`CouponCurrency` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Currency` | `*string` | Optional | - | -| `Price` | `*int` | Optional | - | -| `CouponId` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 228, - "currency": "currency8", - "price": 100, - "coupon_id": 210 -} -``` - + +# Coupon Currency + +## Structure + +`CouponCurrency` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Currency` | `*string` | Optional | - | +| `Price` | `*int` | Optional | - | +| `CouponId` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 228, + "currency": "currency8", + "price": 100, + "coupon_id": 210 +} +``` + diff --git a/doc/models/coupon-response.md b/doc/models/coupon-response.md index 3626510a..5a3e3f1c 100644 --- a/doc/models/coupon-response.md +++ b/doc/models/coupon-response.md @@ -1,27 +1,27 @@ - -# Coupon Response - -## Structure - -`CouponResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Coupon` | [`*models.Coupon`](../../doc/models/coupon.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "coupon": { - "id": 196, - "name": "name4", - "code": "code2", - "description": "description6", - "amount": 97.66 - } -} -``` - + +# Coupon Response + +## Structure + +`CouponResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Coupon` | [`*models.Coupon`](../../doc/models/coupon.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "coupon": { + "id": 196, + "name": "name4", + "code": "code2", + "description": "description6", + "amount": 97.66 + } +} +``` + diff --git a/doc/models/coupon-restriction.md b/doc/models/coupon-restriction.md index c8ef6242..c5edb32e 100644 --- a/doc/models/coupon-restriction.md +++ b/doc/models/coupon-restriction.md @@ -1,29 +1,29 @@ - -# Coupon Restriction - -## Structure - -`CouponRestriction` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `ItemType` | [`*models.RestrictionType`](../../doc/models/restriction-type.md) | Optional | - | -| `ItemId` | `*int` | Optional | - | -| `Name` | `*string` | Optional | - | -| `Handle` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 180, - "item_type": "Component", - "item_id": 184, - "name": "name4", - "handle": "handle0" -} -``` - + +# Coupon Restriction + +## Structure + +`CouponRestriction` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `ItemType` | [`*models.RestrictionType`](../../doc/models/restriction-type.md) | Optional | - | +| `ItemId` | `*int` | Optional | - | +| `Name` | `*string` | Optional | - | +| `Handle` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 180, + "item_type": "Component", + "item_id": 184, + "name": "name4", + "handle": "handle0" +} +``` + diff --git a/doc/models/coupon-subcodes-response.md b/doc/models/coupon-subcodes-response.md index 1735c80e..24fe7899 100644 --- a/doc/models/coupon-subcodes-response.md +++ b/doc/models/coupon-subcodes-response.md @@ -1,35 +1,35 @@ - -# Coupon Subcodes Response - -## Structure - -`CouponSubcodesResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CreatedCodes` | `[]string` | Optional | - | -| `DuplicateCodes` | `[]string` | Optional | - | -| `InvalidCodes` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "created_codes": [ - "created_codes1", - "created_codes2" - ], - "duplicate_codes": [ - "duplicate_codes8", - "duplicate_codes7" - ], - "invalid_codes": [ - "invalid_codes0", - "invalid_codes9", - "invalid_codes8" - ] -} -``` - + +# Coupon Subcodes Response + +## Structure + +`CouponSubcodesResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CreatedCodes` | `[]string` | Optional | - | +| `DuplicateCodes` | `[]string` | Optional | - | +| `InvalidCodes` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "created_codes": [ + "created_codes1", + "created_codes2" + ], + "duplicate_codes": [ + "duplicate_codes8", + "duplicate_codes7" + ], + "invalid_codes": [ + "invalid_codes0", + "invalid_codes9", + "invalid_codes8" + ] +} +``` + diff --git a/doc/models/coupon-subcodes.md b/doc/models/coupon-subcodes.md index 7d64cf53..ab8f8629 100644 --- a/doc/models/coupon-subcodes.md +++ b/doc/models/coupon-subcodes.md @@ -1,23 +1,23 @@ - -# Coupon Subcodes - -## Structure - -`CouponSubcodes` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Codes` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "codes": [ - "codes8" - ] -} -``` - + +# Coupon Subcodes + +## Structure + +`CouponSubcodes` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Codes` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "codes": [ + "codes8" + ] +} +``` + diff --git a/doc/models/coupon-usage.md b/doc/models/coupon-usage.md index 8aee95b8..197f30c9 100644 --- a/doc/models/coupon-usage.md +++ b/doc/models/coupon-usage.md @@ -1,31 +1,31 @@ - -# Coupon Usage - -## Structure - -`CouponUsage` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | The Chargify id of the product | -| `Name` | `*string` | Optional | Name of the product | -| `Signups` | `*int` | Optional | Number of times the coupon has been applied | -| `Savings` | `Optional[int]` | Optional | Dollar amount of customer savings as a result of the coupon. | -| `SavingsInCents` | `Optional[int64]` | Optional | Dollar amount of customer savings as a result of the coupon. | -| `Revenue` | `Optional[int]` | Optional | Total revenue of the all subscriptions that have received a discount from this coupon. | -| `RevenueInCents` | `*int64` | Optional | Total revenue of the all subscriptions that have received a discount from this coupon. | - -## Example (as JSON) - -```json -{ - "id": 14, - "name": "name0", - "signups": 34, - "savings": 52, - "savings_in_cents": 138 -} -``` - + +# Coupon Usage + +## Structure + +`CouponUsage` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | The Chargify id of the product | +| `Name` | `*string` | Optional | Name of the product | +| `Signups` | `*int` | Optional | Number of times the coupon has been applied | +| `Savings` | `models.Optional[int]` | Optional | Dollar amount of customer savings as a result of the coupon. | +| `SavingsInCents` | `models.Optional[int64]` | Optional | Dollar amount of customer savings as a result of the coupon. | +| `Revenue` | `models.Optional[int]` | Optional | Total revenue of the all subscriptions that have received a discount from this coupon. | +| `RevenueInCents` | `*int64` | Optional | Total revenue of the all subscriptions that have received a discount from this coupon. | + +## Example (as JSON) + +```json +{ + "id": 14, + "name": "name0", + "signups": 34, + "savings": 52, + "savings_in_cents": 138 +} +``` + diff --git a/doc/models/coupon.md b/doc/models/coupon.md index d988430b..7dc2d9cb 100644 --- a/doc/models/coupon.md +++ b/doc/models/coupon.md @@ -1,54 +1,54 @@ - -# Coupon - -## Structure - -`Coupon` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Name` | `*string` | Optional | - | -| `Code` | `*string` | Optional | - | -| `Description` | `*string` | Optional | - | -| `Amount` | `Optional[float64]` | Optional | - | -| `AmountInCents` | `Optional[int]` | Optional | - | -| `ProductFamilyId` | `*int` | Optional | - | -| `ProductFamilyName` | `Optional[string]` | Optional | - | -| `StartDate` | `*time.Time` | Optional | - | -| `EndDate` | `Optional[time.Time]` | Optional | - | -| `Percentage` | `Optional[string]` | Optional | - | -| `Recurring` | `*bool` | Optional | - | -| `RecurringScheme` | [`*models.RecurringScheme`](../../doc/models/recurring-scheme.md) | Optional | - | -| `DurationPeriodCount` | `Optional[int]` | Optional | - | -| `DurationInterval` | `Optional[int]` | Optional | - | -| `DurationIntervalUnit` | `Optional[string]` | Optional | - | -| `DurationIntervalSpan` | `Optional[string]` | Optional | - | -| `AllowNegativeBalance` | `*bool` | Optional | - | -| `ArchivedAt` | `Optional[time.Time]` | Optional | - | -| `ConversionLimit` | `Optional[string]` | Optional | - | -| `Stackable` | `*bool` | Optional | - | -| `CompoundingStrategy` | `*interface{}` | Optional | - | -| `UseSiteExchangeRate` | `*bool` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `UpdatedAt` | `*time.Time` | Optional | - | -| `DiscountType` | [`*models.DiscountType`](../../doc/models/discount-type.md) | Optional | - | -| `ExcludeMidPeriodAllocations` | `*bool` | Optional | - | -| `ApplyOnCancelAtEndOfPeriod` | `*bool` | Optional | - | -| `ApplyOnSubscriptionExpiration` | `*bool` | Optional | - | -| `CouponRestrictions` | [`[]models.CouponRestriction`](../../doc/models/coupon-restriction.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 22, - "name": "name2", - "code": "code0", - "description": "description2", - "amount": 62.64 -} -``` - + +# Coupon + +## Structure + +`Coupon` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Name` | `*string` | Optional | - | +| `Code` | `*string` | Optional | - | +| `Description` | `*string` | Optional | - | +| `Amount` | `models.Optional[float64]` | Optional | - | +| `AmountInCents` | `models.Optional[int]` | Optional | - | +| `ProductFamilyId` | `*int` | Optional | - | +| `ProductFamilyName` | `models.Optional[string]` | Optional | - | +| `StartDate` | `*time.Time` | Optional | - | +| `EndDate` | `models.Optional[time.Time]` | Optional | - | +| `Percentage` | `models.Optional[string]` | Optional | - | +| `Recurring` | `*bool` | Optional | - | +| `RecurringScheme` | [`*models.RecurringScheme`](../../doc/models/recurring-scheme.md) | Optional | - | +| `DurationPeriodCount` | `models.Optional[int]` | Optional | - | +| `DurationInterval` | `models.Optional[int]` | Optional | - | +| `DurationIntervalUnit` | `models.Optional[string]` | Optional | - | +| `DurationIntervalSpan` | `models.Optional[string]` | Optional | - | +| `AllowNegativeBalance` | `*bool` | Optional | - | +| `ArchivedAt` | `models.Optional[time.Time]` | Optional | - | +| `ConversionLimit` | `models.Optional[string]` | Optional | - | +| `Stackable` | `*bool` | Optional | - | +| `CompoundingStrategy` | [`*models.CouponCompoundingStrategy`](../../doc/models/containers/coupon-compounding-strategy.md) | Optional | This is a container for any-of cases. | +| `UseSiteExchangeRate` | `*bool` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `UpdatedAt` | `*time.Time` | Optional | - | +| `DiscountType` | [`*models.DiscountType`](../../doc/models/discount-type.md) | Optional | - | +| `ExcludeMidPeriodAllocations` | `*bool` | Optional | - | +| `ApplyOnCancelAtEndOfPeriod` | `*bool` | Optional | - | +| `ApplyOnSubscriptionExpiration` | `*bool` | Optional | - | +| `CouponRestrictions` | [`[]models.CouponRestriction`](../../doc/models/coupon-restriction.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 22, + "name": "name2", + "code": "code0", + "description": "description2", + "amount": 62.64 +} +``` + diff --git a/doc/models/create-allocation-request.md b/doc/models/create-allocation-request.md index f6231036..377578c7 100644 --- a/doc/models/create-allocation-request.md +++ b/doc/models/create-allocation-request.md @@ -1,28 +1,28 @@ - -# Create Allocation Request - -## Structure - -`CreateAllocationRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Allocation` | [`models.CreateAllocation`](../../doc/models/create-allocation.md) | Required | - | - -## Example (as JSON) - -```json -{ - "allocation": { - "quantity": 228.94, - "component_id": 8, - "memo": "memo2", - "proration_downgrade_scheme": "proration_downgrade_scheme4", - "proration_upgrade_scheme": "proration_upgrade_scheme6", - "accrue_charge": false - } -} -``` - + +# Create Allocation Request + +## Structure + +`CreateAllocationRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Allocation` | [`models.CreateAllocation`](../../doc/models/create-allocation.md) | Required | - | + +## Example (as JSON) + +```json +{ + "allocation": { + "quantity": 228.94, + "component_id": 8, + "memo": "memo2", + "proration_downgrade_scheme": "proration_downgrade_scheme4", + "proration_upgrade_scheme": "proration_upgrade_scheme6", + "accrue_charge": false + } +} +``` + diff --git a/doc/models/create-allocation.md b/doc/models/create-allocation.md index 70bd64f4..6066c624 100644 --- a/doc/models/create-allocation.md +++ b/doc/models/create-allocation.md @@ -1,36 +1,36 @@ - -# Create Allocation - -## Structure - -`CreateAllocation` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Quantity` | `float64` | Required | The allocated quantity to which to set the line-items allocated quantity. By default, this is an integer. If decimal allocations are enabled for the component, it will be a decimal number. For On/Off components, use 1for on and 0 for off. | -| `ComponentId` | `*int` | Optional | (required for the multiple allocations endpoint) The id associated with the component for which the allocation is being made | -| `Memo` | `*string` | Optional | A memo to record along with the allocation | -| `ProrationDowngradeScheme` | `*string` | Optional | The scheme used if the proration is a downgrade. Defaults to the site setting if one is not provided. | -| `ProrationUpgradeScheme` | `*string` | Optional | The scheme used if the proration is an upgrade. Defaults to the site setting if one is not provided. | -| `AccrueCharge` | `*bool` | Optional | If the change in cost is an upgrade, this determines if the charge should accrue to the next renewal or if capture should be attempted immediately. Defaults to the site setting if one is not provided. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `InitiateDunning` | `*bool` | Optional | If set to true, if the immediate component payment fails, initiate dunning for the subscription.
Otherwise, leave the charges on the subscription to pay for at renewal. Defaults to false. | -| `PricePointId` | `Optional[interface{}]` | Optional | Price point that the allocation should be charged at. Accepts either the price point's id (integer) or handle (string). When not specified, the default price point will be used. | -| `BillingSchedule` | [`*models.BillingSchedule`](../../doc/models/billing-schedule.md) | Optional | This attribute is particularly useful when you need to align billing events for different components on distinct schedules within a subscription. Please note this only works for site with Multifrequency enabled | - -## Example (as JSON) - -```json -{ - "quantity": 8.06, - "component_id": 192, - "memo": "memo4", - "proration_downgrade_scheme": "proration_downgrade_scheme2", - "proration_upgrade_scheme": "proration_upgrade_scheme4", - "accrue_charge": false -} -``` - + +# Create Allocation + +## Structure + +`CreateAllocation` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Quantity` | `float64` | Required | The allocated quantity to which to set the line-items allocated quantity. By default, this is an integer. If decimal allocations are enabled for the component, it will be a decimal number. For On/Off components, use 1for on and 0 for off. | +| `ComponentId` | `*int` | Optional | (required for the multiple allocations endpoint) The id associated with the component for which the allocation is being made | +| `Memo` | `*string` | Optional | A memo to record along with the allocation | +| `ProrationDowngradeScheme` | `*string` | Optional | The scheme used if the proration is a downgrade. Defaults to the site setting if one is not provided. | +| `ProrationUpgradeScheme` | `*string` | Optional | The scheme used if the proration is an upgrade. Defaults to the site setting if one is not provided. | +| `AccrueCharge` | `*bool` | Optional | If the change in cost is an upgrade, this determines if the charge should accrue to the next renewal or if capture should be attempted immediately. Defaults to the site setting if one is not provided. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `InitiateDunning` | `*bool` | Optional | If set to true, if the immediate component payment fails, initiate dunning for the subscription.
Otherwise, leave the charges on the subscription to pay for at renewal. Defaults to false. | +| `PricePointId` | [`models.Optional[models.CreateAllocationPricePointId]`](../../doc/models/containers/create-allocation-price-point-id.md) | Optional | This is a container for one-of cases. | +| `BillingSchedule` | [`*models.BillingSchedule`](../../doc/models/billing-schedule.md) | Optional | This attribute is particularly useful when you need to align billing events for different components on distinct schedules within a subscription. Please note this only works for site with Multifrequency enabled | + +## Example (as JSON) + +```json +{ + "quantity": 8.06, + "component_id": 192, + "memo": "memo4", + "proration_downgrade_scheme": "proration_downgrade_scheme2", + "proration_upgrade_scheme": "proration_upgrade_scheme4", + "accrue_charge": false +} +``` + diff --git a/doc/models/create-component-price-point-request.md b/doc/models/create-component-price-point-request.md index 10166679..7c97d1d7 100644 --- a/doc/models/create-component-price-point-request.md +++ b/doc/models/create-component-price-point-request.md @@ -1,70 +1,36 @@ - -# Create Component Price Point Request - -## Structure - -`CreateComponentPricePointRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoint` | [`models.PricePoint`](../../doc/models/price-point.md) | Required | - | - -## Example (as JSON) - -```json -{ - "price_point": { - "use_site_exchange_rate": true, - "name": "name0", - "handle": "handle6", - "pricing_scheme": "per_unit", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - } -} -``` - + +# Create Component Price Point Request + +## Structure + +`CreateComponentPricePointRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoint` | [`models.CreateComponentPricePointRequestPricePoint`](../../doc/models/containers/create-component-price-point-request-price-point.md) | Required | This is a container for any-of cases. | + +## Example (as JSON) + +```json +{ + "price_point": { + "name": "name0", + "pricing_scheme": "per_unit", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "use_site_exchange_rate": true, + "handle": "handle6", + "tax_included": false, + "interval": 24, + "interval_unit": "day" + } +} +``` + diff --git a/doc/models/create-component-price-point.md b/doc/models/create-component-price-point.md new file mode 100644 index 00000000..8f1924e1 --- /dev/null +++ b/doc/models/create-component-price-point.md @@ -0,0 +1,41 @@ + +# Create Component Price Point + +## Structure + +`CreateComponentPricePoint` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | - | +| `Handle` | `*string` | Optional | - | +| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Required | - | +| `UseSiteExchangeRate` | `*bool` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site.
**Default**: `true` | +| `TaxIncluded` | `*bool` | Optional | Whether or not the price point includes tax | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this price point, either month or day. This property is only available for sites with Multifrequency enabled. | + +## Example (as JSON) + +```json +{ + "name": "name0", + "pricing_scheme": "per_unit", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "use_site_exchange_rate": true, + "handle": "handle6", + "tax_included": false, + "interval": 24, + "interval_unit": "day" +} +``` + diff --git a/doc/models/create-component-price-points-request.md b/doc/models/create-component-price-points-request.md index d9b0b592..1fae98d7 100644 --- a/doc/models/create-component-price-points-request.md +++ b/doc/models/create-component-price-points-request.md @@ -1,44 +1,74 @@ - -# Create Component Price Points Request - -## Structure - -`CreateComponentPricePointsRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoints` | [`[]models.PricePoint`](../../doc/models/price-point.md) | Required | - | - -## Example (as JSON) - -```json -{ - "price_points": [ - { - "use_site_exchange_rate": true, - "name": "name2", - "handle": "handle8", - "pricing_scheme": "per_unit", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - } - ] -} -``` - + +# Create Component Price Points Request + +## Structure + +`CreateComponentPricePointsRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoints` | [`[]models.CreateComponentPricePointsRequestPricePoints`](../../doc/models/containers/create-component-price-points-request-price-points.md) | Required | This is Array of a container for any-of cases. | + +## Example (as JSON) + +```json +{ + "price_points": [ + { + "name": "name0", + "handle": "handle6", + "pricing_scheme": "per_unit", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "use_site_exchange_rate": false, + "tax_included": false, + "interval": 24, + "interval_unit": "day" + }, + { + "name": "name0", + "handle": "handle6", + "pricing_scheme": "per_unit", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "use_site_exchange_rate": false, + "tax_included": false, + "interval": 24, + "interval_unit": "day" + } + ] +} +``` + diff --git a/doc/models/create-currency-price.md b/doc/models/create-currency-price.md index e1b71970..7bbb5622 100644 --- a/doc/models/create-currency-price.md +++ b/doc/models/create-currency-price.md @@ -1,25 +1,25 @@ - -# Create Currency Price - -## Structure - -`CreateCurrencyPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Currency` | `*string` | Optional | ISO code for a currency defined on the site level | -| `Price` | `*float64` | Optional | Price for the price level in this currency | -| `PriceId` | `*int` | Optional | ID of the price that this corresponds with | - -## Example (as JSON) - -```json -{ - "currency": "currency2", - "price": 10.4, - "price_id": 54 -} -``` - + +# Create Currency Price + +## Structure + +`CreateCurrencyPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Currency` | `*string` | Optional | ISO code for a currency defined on the site level | +| `Price` | `*float64` | Optional | Price for the price level in this currency | +| `PriceId` | `*int` | Optional | ID of the price that this corresponds with | + +## Example (as JSON) + +```json +{ + "currency": "currency2", + "price": 10.4, + "price_id": 54 +} +``` + diff --git a/doc/models/create-currency-prices-request.md b/doc/models/create-currency-prices-request.md index efc181fd..1e5c58f1 100644 --- a/doc/models/create-currency-prices-request.md +++ b/doc/models/create-currency-prices-request.md @@ -1,27 +1,27 @@ - -# Create Currency Prices Request - -## Structure - -`CreateCurrencyPricesRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CurrencyPrices` | [`[]models.CreateCurrencyPrice`](../../doc/models/create-currency-price.md) | Required | - | - -## Example (as JSON) - -```json -{ - "currency_prices": [ - { - "currency": "currency8", - "price": 233.74, - "price_id": 116 - } - ] -} -``` - + +# Create Currency Prices Request + +## Structure + +`CreateCurrencyPricesRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrencyPrices` | [`[]models.CreateCurrencyPrice`](../../doc/models/create-currency-price.md) | Required | - | + +## Example (as JSON) + +```json +{ + "currency_prices": [ + { + "currency": "currency8", + "price": 233.74, + "price_id": 116 + } + ] +} +``` + diff --git a/doc/models/create-customer-request.md b/doc/models/create-customer-request.md index 36f9a02f..568c14dd 100644 --- a/doc/models/create-customer-request.md +++ b/doc/models/create-customer-request.md @@ -1,30 +1,30 @@ - -# Create Customer Request - -## Structure - -`CreateCustomerRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Customer` | [`models.CreateCustomer`](../../doc/models/create-customer.md) | Required | - | - -## Example (as JSON) - -```json -{ - "customer": { - "first_name": "first_name0", - "last_name": "last_name8", - "email": "email6", - "cc_emails": "cc_emails0", - "organization": "organization6", - "reference": "reference4", - "address": "address6", - "address_2": "address_24" - } -} -``` - + +# Create Customer Request + +## Structure + +`CreateCustomerRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Customer` | [`models.CreateCustomer`](../../doc/models/create-customer.md) | Required | - | + +## Example (as JSON) + +```json +{ + "customer": { + "first_name": "first_name0", + "last_name": "last_name8", + "email": "email6", + "cc_emails": "cc_emails0", + "organization": "organization6", + "reference": "reference4", + "address": "address6", + "address_2": "address_24" + } +} +``` + diff --git a/doc/models/create-customer.md b/doc/models/create-customer.md index 70731a3b..cfbd83d9 100644 --- a/doc/models/create-customer.md +++ b/doc/models/create-customer.md @@ -1,45 +1,45 @@ - -# Create Customer - -## Structure - -`CreateCustomer` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `FirstName` | `string` | Required | - | -| `LastName` | `string` | Required | - | -| `Email` | `string` | Required | - | -| `CcEmails` | `*string` | Optional | - | -| `Organization` | `*string` | Optional | - | -| `Reference` | `*string` | Optional | - | -| `Address` | `*string` | Optional | - | -| `Address2` | `*string` | Optional | - | -| `City` | `*string` | Optional | - | -| `State` | `*string` | Optional | - | -| `Zip` | `*string` | Optional | - | -| `Country` | `*string` | Optional | - | -| `Phone` | `*string` | Optional | - | -| `Locale` | `*string` | Optional | Set a specific language on a customer record. | -| `VatNumber` | `*string` | Optional | - | -| `TaxExempt` | `*bool` | Optional | - | -| `TaxExemptReason` | `*string` | Optional | - | -| `ParentId` | `Optional[int]` | Optional | The parent ID in Chargify if applicable. Parent is another Customer object. | - -## Example (as JSON) - -```json -{ - "first_name": "first_name8", - "last_name": "last_name6", - "email": "email8", - "cc_emails": "cc_emails8", - "organization": "organization2", - "reference": "reference4", - "address": "address4", - "address_2": "address_22" -} -``` - + +# Create Customer + +## Structure + +`CreateCustomer` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FirstName` | `string` | Required | - | +| `LastName` | `string` | Required | - | +| `Email` | `string` | Required | - | +| `CcEmails` | `*string` | Optional | - | +| `Organization` | `*string` | Optional | - | +| `Reference` | `*string` | Optional | - | +| `Address` | `*string` | Optional | - | +| `Address2` | `*string` | Optional | - | +| `City` | `*string` | Optional | - | +| `State` | `*string` | Optional | - | +| `Zip` | `*string` | Optional | - | +| `Country` | `*string` | Optional | - | +| `Phone` | `*string` | Optional | - | +| `Locale` | `*string` | Optional | Set a specific language on a customer record. | +| `VatNumber` | `*string` | Optional | - | +| `TaxExempt` | `*bool` | Optional | - | +| `TaxExemptReason` | `*string` | Optional | - | +| `ParentId` | `models.Optional[int]` | Optional | The parent ID in Chargify if applicable. Parent is another Customer object. | + +## Example (as JSON) + +```json +{ + "first_name": "first_name8", + "last_name": "last_name6", + "email": "email8", + "cc_emails": "cc_emails8", + "organization": "organization2", + "reference": "reference4", + "address": "address4", + "address_2": "address_22" +} +``` + diff --git a/doc/models/create-ebb-component.md b/doc/models/create-ebb-component.md index 72720e7b..69c6b4a9 100644 --- a/doc/models/create-ebb-component.md +++ b/doc/models/create-ebb-component.md @@ -1,46 +1,37 @@ - -# Create EBB Component - -## Structure - -`CreateEBBComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `EventBasedComponent` | [`models.EBBComponent`](../../doc/models/ebb-component.md) | Required | - | - -## Example (as JSON) - -```json -{ - "event_based_component": { - "name": "name8", - "unit_name": "unit_name0", - "description": "description8", - "handle": "handle4", - "taxable": false, - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ], - "upgrade_charge": "full", - "event_based_billing_metric_id": 68 - } -} -``` - + +# Create EBB Component + +## Structure + +`CreateEBBComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `EventBasedComponent` | [`models.EBBComponent`](../../doc/models/ebb-component.md) | Required | - | + +## Example (as JSON) + +```json +{ + "event_based_component": { + "name": "name8", + "unit_name": "unit_name0", + "description": "description8", + "handle": "handle4", + "taxable": false, + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "upgrade_charge": "full", + "event_based_billing_metric_id": 68 + } +} +``` + diff --git a/doc/models/create-invoice-address.md b/doc/models/create-invoice-address.md index 665050df..572f0f43 100644 --- a/doc/models/create-invoice-address.md +++ b/doc/models/create-invoice-address.md @@ -1,35 +1,35 @@ - -# Create Invoice Address - -Overrides the default address. - -## Structure - -`CreateInvoiceAddress` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `FirstName` | `*string` | Optional | - | -| `LastName` | `*string` | Optional | - | -| `Phone` | `*string` | Optional | - | -| `Address` | `*string` | Optional | - | -| `Address2` | `*string` | Optional | - | -| `City` | `*string` | Optional | - | -| `State` | `*string` | Optional | - | -| `Zip` | `*string` | Optional | - | -| `Country` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "first_name": "first_name4", - "last_name": "last_name2", - "phone": "phone6", - "address": "address0", - "address_2": "address_28" -} -``` - + +# Create Invoice Address + +Overrides the default address. + +## Structure + +`CreateInvoiceAddress` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FirstName` | `*string` | Optional | - | +| `LastName` | `*string` | Optional | - | +| `Phone` | `*string` | Optional | - | +| `Address` | `*string` | Optional | - | +| `Address2` | `*string` | Optional | - | +| `City` | `*string` | Optional | - | +| `State` | `*string` | Optional | - | +| `Zip` | `*string` | Optional | - | +| `Country` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "first_name": "first_name4", + "last_name": "last_name2", + "phone": "phone6", + "address": "address0", + "address_2": "address_28" +} +``` + diff --git a/doc/models/create-invoice-coupon.md b/doc/models/create-invoice-coupon.md index 979143f8..1d35792d 100644 --- a/doc/models/create-invoice-coupon.md +++ b/doc/models/create-invoice-coupon.md @@ -1,39 +1,30 @@ - -# Create Invoice Coupon - -## Structure - -`CreateInvoiceCoupon` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Code` | `*string` | Optional | - | -| `Percentage` | `*interface{}` | Optional | - | -| `Amount` | `*interface{}` | Optional | - | -| `Description` | `*string` | Optional | **Constraints**: *Maximum Length*: `255` | -| `ProductFamilyId` | `*interface{}` | Optional | - | -| `CompoundingStrategy` | [`*models.CompoundingStrategy`](../../doc/models/compounding-strategy.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "percentage": { - "key1": "val1", - "key2": "val2" - }, - "code": "code4", - "amount": { - "key1": "val1", - "key2": "val2" - }, - "description": "description4", - "product_family_id": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Create Invoice Coupon + +## Structure + +`CreateInvoiceCoupon` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Code` | `*string` | Optional | - | +| `Percentage` | [`*models.CreateInvoiceCouponPercentage`](../../doc/models/containers/create-invoice-coupon-percentage.md) | Optional | This is a container for one-of cases. | +| `Amount` | [`*models.CreateInvoiceCouponAmount`](../../doc/models/containers/create-invoice-coupon-amount.md) | Optional | This is a container for one-of cases. | +| `Description` | `*string` | Optional | **Constraints**: *Maximum Length*: `255` | +| `ProductFamilyId` | [`*models.CreateInvoiceCouponProductFamilyId`](../../doc/models/containers/create-invoice-coupon-product-family-id.md) | Optional | This is a container for one-of cases. | +| `CompoundingStrategy` | [`*models.CompoundingStrategy`](../../doc/models/compounding-strategy.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "percentage": 50.0, + "code": "code4", + "amount": "String9", + "description": "description4", + "product_family_id": "String3" +} +``` + diff --git a/doc/models/create-invoice-item.md b/doc/models/create-invoice-item.md index 45b123f7..18b69f34 100644 --- a/doc/models/create-invoice-item.md +++ b/doc/models/create-invoice-item.md @@ -1,42 +1,36 @@ - -# Create Invoice Item - -## Structure - -`CreateInvoiceItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Title` | `*string` | Optional | - | -| `Quantity` | `*interface{}` | Optional | The quantity can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065. If you submit a value with more than 8 decimal places, we will round it down to the 8th decimal place. | -| `UnitPrice` | `*interface{}` | Optional | The unit_price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065. If you submit a value with more than 8 decimal places, we will round it down to the 8th decimal place. | -| `Taxable` | `*bool` | Optional | Set to true to automatically calculate taxes. Site must be configured to use and calculate taxes.

If using Avalara, a tax_code parameter must also be sent. | -| `TaxCode` | `*string` | Optional | - | -| `PeriodRangeStart` | `*string` | Optional | YYYY-MM-DD | -| `PeriodRangeEnd` | `*string` | Optional | YYYY-MM-DD | -| `ProductId` | `*interface{}` | Optional | Product handle or product id. | -| `ComponentId` | `*interface{}` | Optional | Component handle or component id. | -| `PricePointId` | `*interface{}` | Optional | Price point handle or id. For component. | -| `ProductPricePointId` | `*interface{}` | Optional | - | -| `Description` | `*string` | Optional | **Constraints**: *Maximum Length*: `255` | - -## Example (as JSON) - -```json -{ - "title": "title2", - "quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - }, - "taxable": false, - "tax_code": "tax_code4" -} -``` - + +# Create Invoice Item + +## Structure + +`CreateInvoiceItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Title` | `*string` | Optional | - | +| `Quantity` | [`*models.CreateInvoiceItemQuantity`](../../doc/models/containers/create-invoice-item-quantity.md) | Optional | This is a container for one-of cases. | +| `UnitPrice` | [`*models.CreateInvoiceItemUnitPrice`](../../doc/models/containers/create-invoice-item-unit-price.md) | Optional | This is a container for one-of cases. | +| `Taxable` | `*bool` | Optional | Set to true to automatically calculate taxes. Site must be configured to use and calculate taxes.

If using Avalara, a tax_code parameter must also be sent. | +| `TaxCode` | `*string` | Optional | - | +| `PeriodRangeStart` | `*string` | Optional | YYYY-MM-DD | +| `PeriodRangeEnd` | `*string` | Optional | YYYY-MM-DD | +| `ProductId` | [`*models.CreateInvoiceItemProductId`](../../doc/models/containers/create-invoice-item-product-id.md) | Optional | This is a container for one-of cases. | +| `ComponentId` | [`*models.CreateInvoiceItemComponentId`](../../doc/models/containers/create-invoice-item-component-id.md) | Optional | This is a container for one-of cases. | +| `PricePointId` | [`*models.CreateInvoiceItemPricePointId`](../../doc/models/containers/create-invoice-item-price-point-id.md) | Optional | This is a container for one-of cases. | +| `ProductPricePointId` | [`*models.CreateInvoiceItemProductPricePointId`](../../doc/models/containers/create-invoice-item-product-price-point-id.md) | Optional | This is a container for one-of cases. | +| `Description` | `*string` | Optional | **Constraints**: *Maximum Length*: `255` | + +## Example (as JSON) + +```json +{ + "title": "title2", + "quantity": 154.86, + "unit_price": 138.08, + "taxable": false, + "tax_code": "tax_code4" +} +``` + diff --git a/doc/models/create-invoice-payment-application.md b/doc/models/create-invoice-payment-application.md index aaadb5c9..1b970f24 100644 --- a/doc/models/create-invoice-payment-application.md +++ b/doc/models/create-invoice-payment-application.md @@ -1,23 +1,23 @@ - -# Create Invoice Payment Application - -## Structure - -`CreateInvoicePaymentApplication` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `InvoiceUid` | `string` | Required | Unique identifier for the invoice. It has the prefix "inv_" followed by alphanumeric characters. | -| `Amount` | `string` | Required | Dollar amount of the invoice payment (eg. "10.50" => $10.50). | - -## Example (as JSON) - -```json -{ - "invoice_uid": "invoice_uid4", - "amount": "amount6" -} -``` - + +# Create Invoice Payment Application + +## Structure + +`CreateInvoicePaymentApplication` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `InvoiceUid` | `string` | Required | Unique identifier for the invoice. It has the prefix "inv_" followed by alphanumeric characters. | +| `Amount` | `string` | Required | Dollar amount of the invoice payment (eg. "10.50" => $10.50). | + +## Example (as JSON) + +```json +{ + "invoice_uid": "invoice_uid4", + "amount": "amount6" +} +``` + diff --git a/doc/models/create-invoice-payment-request.md b/doc/models/create-invoice-payment-request.md index 46fc57fb..3a760149 100644 --- a/doc/models/create-invoice-payment-request.md +++ b/doc/models/create-invoice-payment-request.md @@ -1,32 +1,29 @@ - -# Create Invoice Payment Request - -## Structure - -`CreateInvoicePaymentRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Payment` | [`models.CreateInvoicePayment`](../../doc/models/create-invoice-payment.md) | Required | - | -| `Type` | [`*models.InvoicePaymentType`](../../doc/models/invoice-payment-type.md) | Optional | The type of payment to be applied to an Invoice. Defaults to external. | - -## Example (as JSON) - -```json -{ - "payment": { - "amount": { - "key1": "val1", - "key2": "val2" - }, - "memo": "memo0", - "method": "ach", - "details": "details6", - "payment_profile_id": 42 - }, - "type": "external" -} -``` - + +# Create Invoice Payment Request + +## Structure + +`CreateInvoicePaymentRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Payment` | [`models.CreateInvoicePayment`](../../doc/models/create-invoice-payment.md) | Required | - | +| `Type` | [`*models.InvoicePaymentType`](../../doc/models/invoice-payment-type.md) | Optional | The type of payment to be applied to an Invoice. Defaults to external. | + +## Example (as JSON) + +```json +{ + "payment": { + "amount": "String9", + "memo": "memo0", + "method": "ach", + "details": "details6", + "payment_profile_id": 42 + }, + "type": "external" +} +``` + diff --git a/doc/models/create-invoice-payment.md b/doc/models/create-invoice-payment.md index 186dbd23..b5a57117 100644 --- a/doc/models/create-invoice-payment.md +++ b/doc/models/create-invoice-payment.md @@ -1,32 +1,29 @@ - -# Create Invoice Payment - -## Structure - -`CreateInvoicePayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Amount` | `*interface{}` | Optional | A string of the dollar amount to be refunded (eg. "10.50" => $10.50) | -| `Memo` | `*string` | Optional | A description to be attached to the payment. | -| `Method` | [`*models.InvoicePaymentMethodType`](../../doc/models/invoice-payment-method-type.md) | Optional | The type of payment method used. Defaults to other. | -| `Details` | `*string` | Optional | Additional information related to the payment method (eg. Check #) | -| `PaymentProfileId` | `*int` | Optional | The ID of the payment profile to be used for the payment. | - -## Example (as JSON) - -```json -{ - "amount": { - "key1": "val1", - "key2": "val2" - }, - "memo": "memo0", - "method": "cash", - "details": "details6", - "payment_profile_id": 122 -} -``` - + +# Create Invoice Payment + +## Structure + +`CreateInvoicePayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Amount` | [`*models.CreateInvoicePaymentAmount`](../../doc/models/containers/create-invoice-payment-amount.md) | Optional | This is a container for one-of cases. | +| `Memo` | `*string` | Optional | A description to be attached to the payment. | +| `Method` | [`*models.InvoicePaymentMethodType`](../../doc/models/invoice-payment-method-type.md) | Optional | The type of payment method used. Defaults to other. | +| `Details` | `*string` | Optional | Additional information related to the payment method (eg. Check #) | +| `PaymentProfileId` | `*int` | Optional | The ID of the payment profile to be used for the payment. | + +## Example (as JSON) + +```json +{ + "amount": "String9", + "memo": "memo0", + "method": "cash", + "details": "details6", + "payment_profile_id": 122 +} +``` + diff --git a/doc/models/create-invoice-request.md b/doc/models/create-invoice-request.md index ad1c5d26..763a9469 100644 --- a/doc/models/create-invoice-request.md +++ b/doc/models/create-invoice-request.md @@ -1,68 +1,50 @@ - -# Create Invoice Request - -## Structure - -`CreateInvoiceRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Invoice` | [`models.CreateInvoice`](../../doc/models/create-invoice.md) | Required | - | - -## Example (as JSON) - -```json -{ - "invoice": { - "issue_date": "2024-01-01", - "status": "draft", - "line_items": [ - { - "title": "title4", - "quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - }, - "taxable": false, - "tax_code": "tax_code6" - }, - { - "title": "title4", - "quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - }, - "taxable": false, - "tax_code": "tax_code6" - }, - { - "title": "title4", - "quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - }, - "taxable": false, - "tax_code": "tax_code6" - } - ], - "net_terms": 144, - "payment_instructions": "payment_instructions6", - "memo": "memo0" - } -} -``` - + +# Create Invoice Request + +## Structure + +`CreateInvoiceRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Invoice` | [`models.CreateInvoice`](../../doc/models/create-invoice.md) | Required | - | + +## Example (as JSON) + +```json +{ + "invoice": { + "issue_date": "2024-01-01", + "status": "draft", + "line_items": [ + { + "title": "title4", + "quantity": 56.68, + "unit_price": 39.9, + "taxable": false, + "tax_code": "tax_code6" + }, + { + "title": "title4", + "quantity": 56.68, + "unit_price": 39.9, + "taxable": false, + "tax_code": "tax_code6" + }, + { + "title": "title4", + "quantity": 56.68, + "unit_price": 39.9, + "taxable": false, + "tax_code": "tax_code6" + } + ], + "net_terms": 144, + "payment_instructions": "payment_instructions6", + "memo": "memo0" + } +} +``` + diff --git a/doc/models/create-invoice-status.md b/doc/models/create-invoice-status.md index 645cff05..73171a87 100644 --- a/doc/models/create-invoice-status.md +++ b/doc/models/create-invoice-status.md @@ -1,20 +1,20 @@ - -# Create Invoice Status - -## Enumeration - -`CreateInvoiceStatus` - -## Fields - -| Name | -| --- | -| `DRAFT` | -| `OPEN` | - -## Example - -``` -draft -``` - + +# Create Invoice Status + +## Enumeration + +`CreateInvoiceStatus` + +## Fields + +| Name | +| --- | +| `DRAFT` | +| `OPEN` | + +## Example + +``` +draft +``` + diff --git a/doc/models/create-invoice.md b/doc/models/create-invoice.md index 791ac285..5c2acfef 100644 --- a/doc/models/create-invoice.md +++ b/doc/models/create-invoice.md @@ -1,49 +1,43 @@ - -# Create Invoice - -## Structure - -`CreateInvoice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `LineItems` | [`[]models.CreateInvoiceItem`](../../doc/models/create-invoice-item.md) | Optional | - | -| `IssueDate` | `*time.Time` | Optional | - | -| `NetTerms` | `*int` | Optional | By default, invoices will be created with a due date matching the date of invoice creation. If a different due date is desired, the net_terms parameter can be sent indicating the number of days in advance the due date should be. | -| `PaymentInstructions` | `*string` | Optional | - | -| `Memo` | `*string` | Optional | A custom memo can be sent to override the site's default. | -| `SellerAddress` | [`*models.CreateInvoiceAddress`](../../doc/models/create-invoice-address.md) | Optional | Overrides the defaults for the site | -| `BillingAddress` | [`*models.CreateInvoiceAddress`](../../doc/models/create-invoice-address.md) | Optional | Overrides the default for the customer | -| `ShippingAddress` | [`*models.CreateInvoiceAddress`](../../doc/models/create-invoice-address.md) | Optional | Overrides the default for the customer | -| `Coupons` | [`[]models.CreateInvoiceCoupon`](../../doc/models/create-invoice-coupon.md) | Optional | - | -| `Status` | [`*models.CreateInvoiceStatus`](../../doc/models/create-invoice-status.md) | Optional | **Default**: `"open"` | - -## Example (as JSON) - -```json -{ - "issue_date": "2024-01-01", - "status": "draft", - "line_items": [ - { - "title": "title4", - "quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - }, - "taxable": false, - "tax_code": "tax_code6" - } - ], - "net_terms": 18, - "payment_instructions": "payment_instructions0", - "memo": "memo6" -} -``` - + +# Create Invoice + +## Structure + +`CreateInvoice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `LineItems` | [`[]models.CreateInvoiceItem`](../../doc/models/create-invoice-item.md) | Optional | - | +| `IssueDate` | `*time.Time` | Optional | - | +| `NetTerms` | `*int` | Optional | By default, invoices will be created with a due date matching the date of invoice creation. If a different due date is desired, the net_terms parameter can be sent indicating the number of days in advance the due date should be. | +| `PaymentInstructions` | `*string` | Optional | - | +| `Memo` | `*string` | Optional | A custom memo can be sent to override the site's default. | +| `SellerAddress` | [`*models.CreateInvoiceAddress`](../../doc/models/create-invoice-address.md) | Optional | Overrides the defaults for the site | +| `BillingAddress` | [`*models.CreateInvoiceAddress`](../../doc/models/create-invoice-address.md) | Optional | Overrides the default for the customer | +| `ShippingAddress` | [`*models.CreateInvoiceAddress`](../../doc/models/create-invoice-address.md) | Optional | Overrides the default for the customer | +| `Coupons` | [`[]models.CreateInvoiceCoupon`](../../doc/models/create-invoice-coupon.md) | Optional | - | +| `Status` | [`*models.CreateInvoiceStatus`](../../doc/models/create-invoice-status.md) | Optional | **Default**: `"open"` | + +## Example (as JSON) + +```json +{ + "issue_date": "2024-01-01", + "status": "draft", + "line_items": [ + { + "title": "title4", + "quantity": 56.68, + "unit_price": 39.9, + "taxable": false, + "tax_code": "tax_code6" + } + ], + "net_terms": 18, + "payment_instructions": "payment_instructions0", + "memo": "memo6" +} +``` + diff --git a/doc/models/create-metadata-request.md b/doc/models/create-metadata-request.md index 6f3a0092..8ba9892b 100644 --- a/doc/models/create-metadata-request.md +++ b/doc/models/create-metadata-request.md @@ -1,26 +1,26 @@ - -# Create Metadata Request - -## Structure - -`CreateMetadataRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Metadata` | [`[]models.CreateMetadata`](../../doc/models/create-metadata.md) | Required | - | - -## Example (as JSON) - -```json -{ - "metadata": [ - { - "name": "name6", - "value": "value8" - } - ] -} -``` - + +# Create Metadata Request + +## Structure + +`CreateMetadataRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Metadata` | [`[]models.CreateMetadata`](../../doc/models/create-metadata.md) | Required | - | + +## Example (as JSON) + +```json +{ + "metadata": [ + { + "name": "name6", + "value": "value8" + } + ] +} +``` + diff --git a/doc/models/create-metadata.md b/doc/models/create-metadata.md index f4e4fb63..3eb40e9d 100644 --- a/doc/models/create-metadata.md +++ b/doc/models/create-metadata.md @@ -1,23 +1,23 @@ - -# Create Metadata - -## Structure - -`CreateMetadata` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `*string` | Optional | - | -| `Value` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "name": "name4", - "value": "value6" -} -``` - + +# Create Metadata + +## Structure + +`CreateMetadata` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `*string` | Optional | - | +| `Value` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name4", + "value": "value6" +} +``` + diff --git a/doc/models/create-metafield.md b/doc/models/create-metafield.md new file mode 100644 index 00000000..453277a0 --- /dev/null +++ b/doc/models/create-metafield.md @@ -0,0 +1,36 @@ + +# Create Metafield + +## Structure + +`CreateMetafield` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `*string` | Optional | - | +| `Scope` | [`*models.MetafieldScope`](../../doc/models/metafield-scope.md) | Optional | Warning: When updating a metafield's scope attribute, all scope attributes must be passed. Partially complete scope attributes will override the existing settings. | +| `InputType` | [`*models.MetafieldInput`](../../doc/models/metafield-input.md) | Optional | Indicates how data should be added to the metafield. For example, a text type is just a string, so a given metafield of this type can have any value attached. On the other hand, dropdown and radio have a set of allowed values that can be input, and appear differently on a Public Signup Page. Defaults to 'text' | +| `Enum` | `[]string` | Optional | Only applicable when input_type is radio or dropdown | + +## Example (as JSON) + +```json +{ + "name": "my_field", + "scope": { + "csv": "0", + "invoices": "0", + "statements": "0", + "portal": "0", + "public_show": "0", + "public_edit": "0" + }, + "input_type": "text", + "enum": [ + "string" + ] +} +``` + diff --git a/doc/models/create-metafields-request.md b/doc/models/create-metafields-request.md index 3ac223bf..8b5e1f9a 100644 --- a/doc/models/create-metafields-request.md +++ b/doc/models/create-metafields-request.md @@ -1,24 +1,35 @@ - -# Create Metafields Request - -## Structure - -`CreateMetafieldsRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Metafields` | `interface{}` | Required | - | - -## Example (as JSON) - -```json -{ - "metafields": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Create Metafields Request + +## Structure + +`CreateMetafieldsRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Metafields` | [`models.CreateMetafieldsRequestMetafields`](../../doc/models/containers/create-metafields-request-metafields.md) | Required | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "metafields": { + "name": "my_field", + "scope": { + "csv": "0", + "invoices": "0", + "statements": "0", + "portal": "0", + "public_show": "0", + "public_edit": "0" + }, + "input_type": "text", + "enum": [ + "string" + ] + } +} +``` + diff --git a/doc/models/create-metered-component.md b/doc/models/create-metered-component.md index 002f5850..91922958 100644 --- a/doc/models/create-metered-component.md +++ b/doc/models/create-metered-component.md @@ -1,73 +1,46 @@ - -# Create Metered Component - -## Structure - -`CreateMeteredComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `MeteredComponent` | [`models.MeteredComponent`](../../doc/models/metered-component.md) | Required | - | - -## Example (as JSON) - -```json -{ - "metered_component": { - "name": "name0", - "unit_name": "unit_name2", - "description": "description0", - "handle": "handle6", - "taxable": false, - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ], - "upgrade_charge": "none" - } -} -``` - + +# Create Metered Component + +## Structure + +`CreateMeteredComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `MeteredComponent` | [`models.MeteredComponent`](../../doc/models/metered-component.md) | Required | - | + +## Example (as JSON) + +```json +{ + "metered_component": { + "name": "name0", + "unit_name": "unit_name2", + "description": "description0", + "handle": "handle6", + "taxable": false, + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "upgrade_charge": "none" + } +} +``` + diff --git a/doc/models/create-multi-invoice-payment-request.md b/doc/models/create-multi-invoice-payment-request.md index 5dd512d2..c699bdd6 100644 --- a/doc/models/create-multi-invoice-payment-request.md +++ b/doc/models/create-multi-invoice-payment-request.md @@ -1,36 +1,33 @@ - -# Create Multi Invoice Payment Request - -## Structure - -`CreateMultiInvoicePaymentRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Payment` | [`models.CreateMultiInvoicePayment`](../../doc/models/create-multi-invoice-payment.md) | Required | - | - -## Example (as JSON) - -```json -{ - "payment": { - "amount": { - "key1": "val1", - "key2": "val2" - }, - "applications": [ - { - "invoice_uid": "invoice_uid8", - "amount": "amount0" - } - ], - "memo": "memo0", - "details": "details6", - "method": "ach", - "received_on": "received_on8" - } -} -``` - + +# Create Multi Invoice Payment Request + +## Structure + +`CreateMultiInvoicePaymentRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Payment` | [`models.CreateMultiInvoicePayment`](../../doc/models/create-multi-invoice-payment.md) | Required | - | + +## Example (as JSON) + +```json +{ + "payment": { + "amount": "String9", + "applications": [ + { + "invoice_uid": "invoice_uid8", + "amount": "amount0" + } + ], + "memo": "memo0", + "details": "details6", + "method": "ach", + "received_on": "received_on8" + } +} +``` + diff --git a/doc/models/create-multi-invoice-payment.md b/doc/models/create-multi-invoice-payment.md index 4a93fdce..321b94e5 100644 --- a/doc/models/create-multi-invoice-payment.md +++ b/doc/models/create-multi-invoice-payment.md @@ -1,39 +1,36 @@ - -# Create Multi Invoice Payment - -## Structure - -`CreateMultiInvoicePayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Memo` | `*string` | Optional | A description to be attached to the payment. | -| `Details` | `*string` | Optional | Additional information related to the payment method (eg. Check #). | -| `Method` | [`*models.InvoicePaymentMethodType`](../../doc/models/invoice-payment-method-type.md) | Optional | The type of payment method used. Defaults to other. | -| `Amount` | `interface{}` | Required | Dollar amount of the sum of the invoices payment (eg. "10.50" => $10.50). | -| `ReceivedOn` | `*string` | Optional | Date reflecting when the payment was received from a customer. Must be in the past. | -| `Applications` | [`[]models.CreateInvoicePaymentApplication`](../../doc/models/create-invoice-payment-application.md) | Required | - | - -## Example (as JSON) - -```json -{ - "amount": { - "key1": "val1", - "key2": "val2" - }, - "applications": [ - { - "invoice_uid": "invoice_uid8", - "amount": "amount0" - } - ], - "memo": "memo8", - "details": "details4", - "method": "credit_card", - "received_on": "received_on6" -} -``` - + +# Create Multi Invoice Payment + +## Structure + +`CreateMultiInvoicePayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Memo` | `*string` | Optional | A description to be attached to the payment. | +| `Details` | `*string` | Optional | Additional information related to the payment method (eg. Check #). | +| `Method` | [`*models.InvoicePaymentMethodType`](../../doc/models/invoice-payment-method-type.md) | Optional | The type of payment method used. Defaults to other. | +| `Amount` | [`models.CreateMultiInvoicePaymentAmount`](../../doc/models/containers/create-multi-invoice-payment-amount.md) | Required | This is a container for one-of cases. | +| `ReceivedOn` | `*string` | Optional | Date reflecting when the payment was received from a customer. Must be in the past. | +| `Applications` | [`[]models.CreateInvoicePaymentApplication`](../../doc/models/create-invoice-payment-application.md) | Required | - | + +## Example (as JSON) + +```json +{ + "amount": "String7", + "applications": [ + { + "invoice_uid": "invoice_uid8", + "amount": "amount0" + } + ], + "memo": "memo8", + "details": "details4", + "method": "credit_card", + "received_on": "received_on6" +} +``` + diff --git a/doc/models/create-offer-component.md b/doc/models/create-offer-component.md index 96533c2f..382f1ea3 100644 --- a/doc/models/create-offer-component.md +++ b/doc/models/create-offer-component.md @@ -1,23 +1,23 @@ - -# Create Offer Component - -## Structure - -`CreateOfferComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ComponentId` | `*int` | Optional | - | -| `StartingQuantity` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "component_id": 242, - "starting_quantity": 50 -} -``` - + +# Create Offer Component + +## Structure + +`CreateOfferComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ComponentId` | `*int` | Optional | - | +| `StartingQuantity` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "component_id": 242, + "starting_quantity": 50 +} +``` + diff --git a/doc/models/create-offer-request.md b/doc/models/create-offer-request.md index 1c6e2774..0c7b2313 100644 --- a/doc/models/create-offer-request.md +++ b/doc/models/create-offer-request.md @@ -1,40 +1,40 @@ - -# Create Offer Request - -## Structure - -`CreateOfferRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Offer` | [`models.CreateOffer`](../../doc/models/create-offer.md) | Required | - | - -## Example (as JSON) - -```json -{ - "offer": { - "name": "name4", - "handle": "handle0", - "description": "description6", - "product_id": 30, - "product_price_point_id": 150, - "components": [ - { - "component_id": 108, - "starting_quantity": 84 - }, - { - "component_id": 108, - "starting_quantity": 84 - } - ], - "coupons": [ - "coupons6" - ] - } -} -``` - + +# Create Offer Request + +## Structure + +`CreateOfferRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Offer` | [`models.CreateOffer`](../../doc/models/create-offer.md) | Required | - | + +## Example (as JSON) + +```json +{ + "offer": { + "name": "name4", + "handle": "handle0", + "description": "description6", + "product_id": 30, + "product_price_point_id": 150, + "components": [ + { + "component_id": 108, + "starting_quantity": 84 + }, + { + "component_id": 108, + "starting_quantity": 84 + } + ], + "coupons": [ + "coupons6" + ] + } +} +``` + diff --git a/doc/models/create-offer.md b/doc/models/create-offer.md index 9937bc03..fdcc57c5 100644 --- a/doc/models/create-offer.md +++ b/doc/models/create-offer.md @@ -1,44 +1,44 @@ - -# Create Offer - -## Structure - -`CreateOffer` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `string` | Required | - | -| `Handle` | `string` | Required | - | -| `Description` | `*string` | Optional | - | -| `ProductId` | `int` | Required | - | -| `ProductPricePointId` | `*int` | Optional | - | -| `Components` | [`[]models.CreateOfferComponent`](../../doc/models/create-offer-component.md) | Optional | - | -| `Coupons` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "name": "name4", - "handle": "handle0", - "description": "description4", - "product_id": 208, - "product_price_point_id": 132, - "components": [ - { - "component_id": 108, - "starting_quantity": 84 - }, - { - "component_id": 108, - "starting_quantity": 84 - } - ], - "coupons": [ - "coupons4" - ] -} -``` - + +# Create Offer + +## Structure + +`CreateOffer` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | - | +| `Handle` | `string` | Required | - | +| `Description` | `*string` | Optional | - | +| `ProductId` | `int` | Required | - | +| `ProductPricePointId` | `*int` | Optional | - | +| `Components` | [`[]models.CreateOfferComponent`](../../doc/models/create-offer-component.md) | Optional | - | +| `Coupons` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name4", + "handle": "handle0", + "description": "description4", + "product_id": 208, + "product_price_point_id": 132, + "components": [ + { + "component_id": 108, + "starting_quantity": 84 + }, + { + "component_id": 108, + "starting_quantity": 84 + } + ], + "coupons": [ + "coupons4" + ] +} +``` + diff --git a/doc/models/create-on-off-component.md b/doc/models/create-on-off-component.md index b989031b..d73390de 100644 --- a/doc/models/create-on-off-component.md +++ b/doc/models/create-on-off-component.md @@ -1,43 +1,34 @@ - -# Create on Off Component - -## Structure - -`CreateOnOffComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `OnOffComponent` | [`models.OnOffComponent`](../../doc/models/on-off-component.md) | Required | - | - -## Example (as JSON) - -```json -{ - "on_off_component": { - "name": "name6", - "description": "description6", - "handle": "handle2", - "taxable": false, - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ], - "upgrade_charge": "full" - } -} -``` - + +# Create on Off Component + +## Structure + +`CreateOnOffComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `OnOffComponent` | [`models.OnOffComponent`](../../doc/models/on-off-component.md) | Required | - | + +## Example (as JSON) + +```json +{ + "on_off_component": { + "name": "name6", + "description": "description6", + "handle": "handle2", + "taxable": false, + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "upgrade_charge": "full" + } +} +``` + diff --git a/doc/models/create-or-update-coupon.md b/doc/models/create-or-update-coupon.md index d39d5645..db44d89e 100644 --- a/doc/models/create-or-update-coupon.md +++ b/doc/models/create-or-update-coupon.md @@ -1,32 +1,38 @@ - -# Create or Update Coupon - -## Structure - -`CreateOrUpdateCoupon` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Coupon` | `*interface{}` | Optional | - | -| `RestrictedProducts` | `map[string]bool` | Optional | An object where the keys are product_ids and the values are booleans indicating if the coupon should be applicable to the product | -| `RestrictedComponents` | `map[string]bool` | Optional | An object where the keys are component_ids and the values are booleans indicating if the coupon should be applicable to the component | - -## Example (as JSON) - -```json -{ - "coupon": { - "key1": "val1", - "key2": "val2" - }, - "restricted_products": { - "key0": true - }, - "restricted_components": { - "key0": true - } -} -``` - + +# Create or Update Coupon + +## Structure + +`CreateOrUpdateCoupon` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Coupon` | [`*models.CreateOrUpdateCouponCoupon`](../../doc/models/containers/create-or-update-coupon-coupon.md) | Optional | This is a container for one-of cases. | +| `RestrictedProducts` | `map[string]bool` | Optional | An object where the keys are product_ids and the values are booleans indicating if the coupon should be applicable to the product | +| `RestrictedComponents` | `map[string]bool` | Optional | An object where the keys are component_ids and the values are booleans indicating if the coupon should be applicable to the component | + +## Example (as JSON) + +```json +{ + "coupon": { + "name": "name0", + "code": "code8", + "description": "description0", + "percentage": "String9", + "allow_negative_balance": false, + "recurring": false, + "end_date": "2016-03-13T12:52:32.123Z", + "product_family_id": "product_family_id6" + }, + "restricted_products": { + "key0": true + }, + "restricted_components": { + "key0": true + } +} +``` + diff --git a/doc/models/create-or-update-endpoint-request.md b/doc/models/create-or-update-endpoint-request.md index 37268d2b..3dd6cc42 100644 --- a/doc/models/create-or-update-endpoint-request.md +++ b/doc/models/create-or-update-endpoint-request.md @@ -1,28 +1,28 @@ - -# Create or Update Endpoint Request - -Used to Create or Update Endpoint - -## Structure - -`CreateOrUpdateEndpointRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Endpoint` | [`models.CreateOrUpdateEndpoint`](../../doc/models/create-or-update-endpoint.md) | Required | Used to Create or Update Endpoint | - -## Example (as JSON) - -```json -{ - "endpoint": { - "url": "url2", - "webhook_subscriptions": [ - "dunning_step_reached" - ] - } -} -``` - + +# Create or Update Endpoint Request + +Used to Create or Update Endpoint + +## Structure + +`CreateOrUpdateEndpointRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Endpoint` | [`models.CreateOrUpdateEndpoint`](../../doc/models/create-or-update-endpoint.md) | Required | Used to Create or Update Endpoint | + +## Example (as JSON) + +```json +{ + "endpoint": { + "url": "url2", + "webhook_subscriptions": [ + "dunning_step_reached" + ] + } +} +``` + diff --git a/doc/models/create-or-update-endpoint.md b/doc/models/create-or-update-endpoint.md index cc10ed7f..744b892a 100644 --- a/doc/models/create-or-update-endpoint.md +++ b/doc/models/create-or-update-endpoint.md @@ -1,27 +1,27 @@ - -# Create or Update Endpoint - -Used to Create or Update Endpoint - -## Structure - -`CreateOrUpdateEndpoint` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Url` | `string` | Required | - | -| `WebhookSubscriptions` | [`[]models.WebhookSubscription`](../../doc/models/webhook-subscription.md) | Required | - | - -## Example (as JSON) - -```json -{ - "url": "url8", - "webhook_subscriptions": [ - "payment_success" - ] -} -``` - + +# Create or Update Endpoint + +Used to Create or Update Endpoint + +## Structure + +`CreateOrUpdateEndpoint` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Url` | `string` | Required | - | +| `WebhookSubscriptions` | [`[]models.WebhookSubscription`](../../doc/models/webhook-subscription.md) | Required | - | + +## Example (as JSON) + +```json +{ + "url": "url8", + "webhook_subscriptions": [ + "payment_success" + ] +} +``` + diff --git a/doc/models/create-or-update-flat-amount-coupon.md b/doc/models/create-or-update-flat-amount-coupon.md new file mode 100644 index 00000000..90294e59 --- /dev/null +++ b/doc/models/create-or-update-flat-amount-coupon.md @@ -0,0 +1,40 @@ + +# Create or Update Flat Amount Coupon + +## Structure + +`CreateOrUpdateFlatAmountCoupon` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | the name of the coupon | +| `Code` | `string` | Required | may contain uppercase alphanumeric characters and these special characters (which allow for email addresses to be used): “%”, “@”, “+”, “-”, “_”, and “.” | +| `Description` | `*string` | Optional | - | +| `AmountInCents` | `int64` | Required | - | +| `AllowNegativeBalance` | `*bool` | Optional | - | +| `Recurring` | `*bool` | Optional | - | +| `EndDate` | `*time.Time` | Optional | - | +| `ProductFamilyId` | `*string` | Optional | - | +| `Stackable` | `*bool` | Optional | - | +| `CompoundingStrategy` | [`*models.CompoundingStrategy`](../../doc/models/compounding-strategy.md) | Optional | - | +| `ExcludeMidPeriodAllocations` | `*bool` | Optional | - | +| `ApplyOnCancelAtEndOfPeriod` | `*bool` | Optional | - | +| `ApplyOnSubscriptionExpiration` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name0", + "code": "code8", + "description": "description0", + "amount_in_cents": 120, + "allow_negative_balance": false, + "recurring": false, + "end_date": "2016-03-13T12:52:32.123Z", + "product_family_id": "product_family_id4" +} +``` + diff --git a/doc/models/create-or-update-percentage-coupon.md b/doc/models/create-or-update-percentage-coupon.md new file mode 100644 index 00000000..289d7d69 --- /dev/null +++ b/doc/models/create-or-update-percentage-coupon.md @@ -0,0 +1,40 @@ + +# Create or Update Percentage Coupon + +## Structure + +`CreateOrUpdatePercentageCoupon` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | the name of the coupon | +| `Code` | `string` | Required | may contain uppercase alphanumeric characters and these special characters (which allow for email addresses to be used): “%”, “@”, “+”, “-”, “_”, and “.” | +| `Description` | `*string` | Optional | - | +| `Percentage` | [`models.CreateOrUpdatePercentageCouponPercentage`](../../doc/models/containers/create-or-update-percentage-coupon-percentage.md) | Required | This is a container for one-of cases. | +| `AllowNegativeBalance` | `*bool` | Optional | - | +| `Recurring` | `*bool` | Optional | - | +| `EndDate` | `*time.Time` | Optional | - | +| `ProductFamilyId` | `*string` | Optional | - | +| `Stackable` | `*bool` | Optional | - | +| `CompoundingStrategy` | [`*models.CompoundingStrategy`](../../doc/models/compounding-strategy.md) | Optional | - | +| `ExcludeMidPeriodAllocations` | `*bool` | Optional | - | +| `ApplyOnCancelAtEndOfPeriod` | `*bool` | Optional | - | +| `ApplyOnSubscriptionExpiration` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name0", + "code": "code8", + "description": "description0", + "percentage": "String9", + "allow_negative_balance": false, + "recurring": false, + "end_date": "2016-03-13T12:52:32.123Z", + "product_family_id": "product_family_id6" +} +``` + diff --git a/doc/models/create-or-update-product-request.md b/doc/models/create-or-update-product-request.md index 802e6024..ec7edb3a 100644 --- a/doc/models/create-or-update-product-request.md +++ b/doc/models/create-or-update-product-request.md @@ -1,32 +1,32 @@ - -# Create or Update Product Request - -## Structure - -`CreateOrUpdateProductRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Product` | [`models.CreateOrUpdateProduct`](../../doc/models/create-or-update-product.md) | Required | - | - -## Example (as JSON) - -```json -{ - "product": { - "name": "name0", - "handle": "handle6", - "description": "description0", - "accounting_code": "accounting_code6", - "require_credit_card": false, - "price_in_cents": 54, - "interval": 186, - "interval_unit": "day", - "trial_price_in_cents": 34, - "trial_interval": 88 - } -} -``` - + +# Create or Update Product Request + +## Structure + +`CreateOrUpdateProductRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Product` | [`models.CreateOrUpdateProduct`](../../doc/models/create-or-update-product.md) | Required | - | + +## Example (as JSON) + +```json +{ + "product": { + "name": "name0", + "handle": "handle6", + "description": "description0", + "accounting_code": "accounting_code6", + "require_credit_card": false, + "price_in_cents": 54, + "interval": 186, + "interval_unit": "day", + "trial_price_in_cents": 34, + "trial_interval": 88 + } +} +``` + diff --git a/doc/models/create-or-update-product.md b/doc/models/create-or-update-product.md index 1e187897..8bb1a1a4 100644 --- a/doc/models/create-or-update-product.md +++ b/doc/models/create-or-update-product.md @@ -1,45 +1,45 @@ - -# Create or Update Product - -## Structure - -`CreateOrUpdateProduct` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `string` | Required | The product name | -| `Handle` | `*string` | Optional | The product API handle | -| `Description` | `string` | Required | The product description | -| `AccountingCode` | `*string` | Optional | E.g. Internal ID or SKU Number | -| `RequireCreditCard` | `*bool` | Optional | Deprecated value that can be ignored unless you have legacy hosted pages. For Public Signup Page users, please read this attribute from under the signup page. | -| `PriceInCents` | `int64` | Required | The product price, in integer cents | -| `Interval` | `int` | Required | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product would renew every 30 days | -| `IntervalUnit` | [`models.IntervalUnit`](../../doc/models/interval-unit.md) | Required | A string representing the interval unit for this product, either month or day | -| `TrialPriceInCents` | `*int64` | Optional | The product trial price, in integer cents | -| `TrialInterval` | `*int` | Optional | The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product trial would last 30 days. | -| `TrialIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the trial interval unit for this product, either month or day | -| `TrialType` | `*string` | Optional | - | -| `ExpirationInterval` | `*int` | Optional | The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product would expire after 30 days. | -| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the expiration interval unit for this product, either month or day | -| `AutoCreateSignupPage` | `*bool` | Optional | - | -| `TaxCode` | `*string` | Optional | A string representing the tax code related to the product type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters.
**Constraints**: *Maximum Length*: `10` | - -## Example (as JSON) - -```json -{ - "name": "name8", - "handle": "handle4", - "description": "description8", - "accounting_code": "accounting_code4", - "require_credit_card": false, - "price_in_cents": 190, - "interval": 174, - "interval_unit": "day", - "trial_price_in_cents": 22, - "trial_interval": 76 -} -``` - + +# Create or Update Product + +## Structure + +`CreateOrUpdateProduct` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | The product name | +| `Handle` | `*string` | Optional | The product API handle | +| `Description` | `string` | Required | The product description | +| `AccountingCode` | `*string` | Optional | E.g. Internal ID or SKU Number | +| `RequireCreditCard` | `*bool` | Optional | Deprecated value that can be ignored unless you have legacy hosted pages. For Public Signup Page users, please read this attribute from under the signup page. | +| `PriceInCents` | `int64` | Required | The product price, in integer cents | +| `Interval` | `int` | Required | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product would renew every 30 days | +| `IntervalUnit` | [`models.IntervalUnit`](../../doc/models/interval-unit.md) | Required | A string representing the interval unit for this product, either month or day | +| `TrialPriceInCents` | `*int64` | Optional | The product trial price, in integer cents | +| `TrialInterval` | `*int` | Optional | The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product trial would last 30 days. | +| `TrialIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the trial interval unit for this product, either month or day | +| `TrialType` | `*string` | Optional | - | +| `ExpirationInterval` | `*int` | Optional | The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product would expire after 30 days. | +| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the expiration interval unit for this product, either month or day | +| `AutoCreateSignupPage` | `*bool` | Optional | - | +| `TaxCode` | `*string` | Optional | A string representing the tax code related to the product type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters.
**Constraints**: *Maximum Length*: `10` | + +## Example (as JSON) + +```json +{ + "name": "name8", + "handle": "handle4", + "description": "description8", + "accounting_code": "accounting_code4", + "require_credit_card": false, + "price_in_cents": 190, + "interval": 174, + "interval_unit": "day", + "trial_price_in_cents": 22, + "trial_interval": 76 +} +``` + diff --git a/doc/models/create-or-update-segment-price.md b/doc/models/create-or-update-segment-price.md index 08d03844..3701ab62 100644 --- a/doc/models/create-or-update-segment-price.md +++ b/doc/models/create-or-update-segment-price.md @@ -1,28 +1,25 @@ - -# Create or Update Segment Price - -## Structure - -`CreateOrUpdateSegmentPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `StartingQuantity` | `*int` | Optional | - | -| `EndingQuantity` | `*int` | Optional | - | -| `UnitPrice` | `interface{}` | Required | The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 | - -## Example (as JSON) - -```json -{ - "starting_quantity": 78, - "ending_quantity": 52, - "unit_price": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Create or Update Segment Price + +## Structure + +`CreateOrUpdateSegmentPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `StartingQuantity` | `*int` | Optional | - | +| `EndingQuantity` | `*int` | Optional | - | +| `UnitPrice` | [`models.CreateOrUpdateSegmentPriceUnitPrice`](../../doc/models/containers/create-or-update-segment-price-unit-price.md) | Required | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "starting_quantity": 78, + "ending_quantity": 52, + "unit_price": "String7" +} +``` + diff --git a/doc/models/create-payment-profile-request.md b/doc/models/create-payment-profile-request.md index a2e2d299..cf7dfd51 100644 --- a/doc/models/create-payment-profile-request.md +++ b/doc/models/create-payment-profile-request.md @@ -1,28 +1,28 @@ - -# Create Payment Profile Request - -## Structure - -`CreatePaymentProfileRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PaymentProfile` | [`models.CreatePaymentProfile`](../../doc/models/create-payment-profile.md) | Required | - | - -## Example (as JSON) - -```json -{ - "payment_profile": { - "chargify_token": "tok_9g6hw85pnpt6knmskpwp4ttt", - "full_number": "5424000000000015", - "id": 44, - "payment_type": "bank_account", - "first_name": "first_name4", - "last_name": "last_name2" - } -} -``` - + +# Create Payment Profile Request + +## Structure + +`CreatePaymentProfileRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PaymentProfile` | [`models.CreatePaymentProfile`](../../doc/models/create-payment-profile.md) | Required | - | + +## Example (as JSON) + +```json +{ + "payment_profile": { + "chargify_token": "tok_9g6hw85pnpt6knmskpwp4ttt", + "full_number": "5424000000000015", + "id": 44, + "payment_type": "bank_account", + "first_name": "first_name4", + "last_name": "last_name2" + } +} +``` + diff --git a/doc/models/create-payment-profile.md b/doc/models/create-payment-profile.md index e33684b6..780327ae 100644 --- a/doc/models/create-payment-profile.md +++ b/doc/models/create-payment-profile.md @@ -1,57 +1,57 @@ - -# Create Payment Profile - -## Structure - -`CreatePaymentProfile` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ChargifyToken` | `*string` | Optional | Token received after sending billing informations using chargify.js. | -| `Id` | `*int` | Optional | - | -| `PaymentType` | [`*models.PaymentType`](../../doc/models/payment-type.md) | Optional | - | -| `FirstName` | `*string` | Optional | First name on card or bank account. If omitted, the first_name from customer attributes will be used. | -| `LastName` | `*string` | Optional | Last name on card or bank account. If omitted, the last_name from customer attributes will be used. | -| `MaskedCardNumber` | `*string` | Optional | - | -| `FullNumber` | `*string` | Optional | The full credit card number | -| `CardType` | [`*models.CardType`](../../doc/models/card-type.md) | Optional | The type of card used. | -| `ExpirationMonth` | `*interface{}` | Optional | (Optional when performing an Import via vault_token, required otherwise) The 1- or 2-digit credit card expiration month, as an integer or string, i.e. 5 | -| `ExpirationYear` | `*interface{}` | Optional | (Optional when performing a Import via vault_token, required otherwise) The 4-digit credit card expiration year, as an integer or string, i.e. 2012 | -| `BillingAddress` | `*string` | Optional | The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. | -| `BillingAddress2` | `Optional[string]` | Optional | Second line of the customer’s billing address i.e. Apt. 100 | -| `BillingCity` | `*string` | Optional | The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. | -| `BillingState` | `*string` | Optional | The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. | -| `BillingCountry` | `*string` | Optional | The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. | -| `BillingZip` | `*string` | Optional | The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. | -| `CurrentVault` | [`*models.CurrentVault`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | -| `VaultToken` | `*string` | Optional | The “token” provided by your vault storage for an already stored payment profile | -| `CustomerVaultToken` | `*string` | Optional | (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token | -| `CustomerId` | `*int` | Optional | (Required when creating a new payment profile) The Chargify customer id. | -| `PaypalEmail` | `*string` | Optional | used by merchants that implemented BraintreeBlue javaScript libraries on their own. We recommend using Chargify.js instead. | -| `PaymentMethodNonce` | `*string` | Optional | used by merchants that implemented BraintreeBlue javaScript libraries on their own. We recommend using Chargify.js instead. | -| `GatewayHandle` | `*string` | Optional | This attribute is only available if MultiGateway feature is enabled for your Site. This feature is in the Private Beta currently. gateway_handle is used to directly select a gateway where a payment profile will be stored in. Every connected gateway must have a unique gateway handle specified. Read [Multigateway description](https://chargify.zendesk.com/hc/en-us/articles/4407761759643#connecting-with-multiple-gateways) to learn more about new concepts that MultiGateway introduces and the default behavior when this attribute is not passed. | -| `Cvv` | `*string` | Optional | The 3- or 4-digit Card Verification Value. This value is merely passed through to the payment gateway. | -| `BankName` | `*string` | Optional | (Required when creating with ACH or GoCardless, optional with Stripe Direct Debit). The name of the bank where the customerʼs account resides | -| `BankIban` | `*string` | Optional | (Optional when creating with GoCardless, required with Stripe Direct Debit). International Bank Account Number. Alternatively, local bank details can be provided | -| `BankRoutingNumber` | `*string` | Optional | (Required when creating with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API | -| `BankAccountNumber` | `*string` | Optional | (Required when creating with ACH, GoCardless, Stripe BECS Direct Debit and bank_iban is blank) The customerʼs bank account number | -| `BankBranchCode` | `*string` | Optional | (Optional when creating with GoCardless, required with Stripe BECS Direct Debit) Branch code. Alternatively, an IBAN can be provided | -| `BankAccountType` | [`*models.BankAccountType`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking | -| `BankAccountHolderType` | [`*models.BankAccountHolderType`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | -| `LastFour` | `*string` | Optional | (Optional) Used for creating subscription with payment profile imported using vault_token, for proper display in Advanced Billing UI | - -## Example (as JSON) - -```json -{ - "chargify_token": "tok_9g6hw85pnpt6knmskpwp4ttt", - "full_number": "5424000000000015", - "id": 76, - "payment_type": "paypal_account", - "first_name": "first_name8", - "last_name": "last_name6" -} -``` - + +# Create Payment Profile + +## Structure + +`CreatePaymentProfile` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ChargifyToken` | `*string` | Optional | Token received after sending billing informations using chargify.js. | +| `Id` | `*int` | Optional | - | +| `PaymentType` | [`*models.PaymentType`](../../doc/models/payment-type.md) | Optional | - | +| `FirstName` | `*string` | Optional | First name on card or bank account. If omitted, the first_name from customer attributes will be used. | +| `LastName` | `*string` | Optional | Last name on card or bank account. If omitted, the last_name from customer attributes will be used. | +| `MaskedCardNumber` | `*string` | Optional | - | +| `FullNumber` | `*string` | Optional | The full credit card number | +| `CardType` | [`*models.CardType`](../../doc/models/card-type.md) | Optional | The type of card used. | +| `ExpirationMonth` | [`*models.CreatePaymentProfileExpirationMonth`](../../doc/models/containers/create-payment-profile-expiration-month.md) | Optional | This is a container for one-of cases. | +| `ExpirationYear` | [`*models.CreatePaymentProfileExpirationYear`](../../doc/models/containers/create-payment-profile-expiration-year.md) | Optional | This is a container for one-of cases. | +| `BillingAddress` | `*string` | Optional | The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. | +| `BillingAddress2` | `models.Optional[string]` | Optional | Second line of the customer’s billing address i.e. Apt. 100 | +| `BillingCity` | `*string` | Optional | The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. | +| `BillingState` | `*string` | Optional | The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. | +| `BillingCountry` | `*string` | Optional | The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. | +| `BillingZip` | `*string` | Optional | The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. | +| `CurrentVault` | [`*models.CurrentVault`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | +| `VaultToken` | `*string` | Optional | The “token” provided by your vault storage for an already stored payment profile | +| `CustomerVaultToken` | `*string` | Optional | (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token | +| `CustomerId` | `*int` | Optional | (Required when creating a new payment profile) The Chargify customer id. | +| `PaypalEmail` | `*string` | Optional | used by merchants that implemented BraintreeBlue javaScript libraries on their own. We recommend using Chargify.js instead. | +| `PaymentMethodNonce` | `*string` | Optional | used by merchants that implemented BraintreeBlue javaScript libraries on their own. We recommend using Chargify.js instead. | +| `GatewayHandle` | `*string` | Optional | This attribute is only available if MultiGateway feature is enabled for your Site. This feature is in the Private Beta currently. gateway_handle is used to directly select a gateway where a payment profile will be stored in. Every connected gateway must have a unique gateway handle specified. Read [Multigateway description](https://chargify.zendesk.com/hc/en-us/articles/4407761759643#connecting-with-multiple-gateways) to learn more about new concepts that MultiGateway introduces and the default behavior when this attribute is not passed. | +| `Cvv` | `*string` | Optional | The 3- or 4-digit Card Verification Value. This value is merely passed through to the payment gateway. | +| `BankName` | `*string` | Optional | (Required when creating with ACH or GoCardless, optional with Stripe Direct Debit). The name of the bank where the customerʼs account resides | +| `BankIban` | `*string` | Optional | (Optional when creating with GoCardless, required with Stripe Direct Debit). International Bank Account Number. Alternatively, local bank details can be provided | +| `BankRoutingNumber` | `*string` | Optional | (Required when creating with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API | +| `BankAccountNumber` | `*string` | Optional | (Required when creating with ACH, GoCardless, Stripe BECS Direct Debit and bank_iban is blank) The customerʼs bank account number | +| `BankBranchCode` | `*string` | Optional | (Optional when creating with GoCardless, required with Stripe BECS Direct Debit) Branch code. Alternatively, an IBAN can be provided | +| `BankAccountType` | [`*models.BankAccountType`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking | +| `BankAccountHolderType` | [`*models.BankAccountHolderType`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | +| `LastFour` | `*string` | Optional | (Optional) Used for creating subscription with payment profile imported using vault_token, for proper display in Advanced Billing UI | + +## Example (as JSON) + +```json +{ + "chargify_token": "tok_9g6hw85pnpt6knmskpwp4ttt", + "full_number": "5424000000000015", + "id": 76, + "payment_type": "paypal_account", + "first_name": "first_name8", + "last_name": "last_name6" +} +``` + diff --git a/doc/models/create-payment.md b/doc/models/create-payment.md index a03f4cd4..8ba40554 100644 --- a/doc/models/create-payment.md +++ b/doc/models/create-payment.md @@ -1,27 +1,27 @@ - -# Create Payment - -## Structure - -`CreatePayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Amount` | `string` | Required | - | -| `Memo` | `string` | Required | - | -| `PaymentDetails` | `string` | Required | - | -| `PaymentMethod` | [`models.InvoicePaymentMethodType`](../../doc/models/invoice-payment-method-type.md) | Required | The type of payment method used. Defaults to other. | - -## Example (as JSON) - -```json -{ - "amount": "amount6", - "memo": "memo8", - "payment_details": "payment_details4", - "payment_method": "cash" -} -``` - + +# Create Payment + +## Structure + +`CreatePayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Amount` | `string` | Required | - | +| `Memo` | `string` | Required | - | +| `PaymentDetails` | `string` | Required | - | +| `PaymentMethod` | [`models.InvoicePaymentMethodType`](../../doc/models/invoice-payment-method-type.md) | Required | The type of payment method used. Defaults to other. | + +## Example (as JSON) + +```json +{ + "amount": "amount6", + "memo": "memo8", + "payment_details": "payment_details4", + "payment_method": "cash" +} +``` + diff --git a/doc/models/create-prepaid-component.md b/doc/models/create-prepaid-component.md index e13f5a80..1cc3cd74 100644 --- a/doc/models/create-prepaid-component.md +++ b/doc/models/create-prepaid-component.md @@ -1,28 +1,28 @@ - -# Create Prepaid Component - -## Structure - -`CreatePrepaidComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PrepaidUsageComponent` | [`models.PrepaidUsageComponent`](../../doc/models/prepaid-usage-component.md) | Required | - | - -## Example (as JSON) - -```json -{ - "prepaid_usage_component": { - "name": "name2", - "unit_name": "unit_name4", - "description": "description2", - "handle": "handle8", - "taxable": false, - "pricing_scheme": "per_unit" - } -} -``` - + +# Create Prepaid Component + +## Structure + +`CreatePrepaidComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PrepaidUsageComponent` | [`models.PrepaidUsageComponent`](../../doc/models/prepaid-usage-component.md) | Required | - | + +## Example (as JSON) + +```json +{ + "prepaid_usage_component": { + "name": "name2", + "unit_name": "unit_name4", + "description": "description2", + "handle": "handle8", + "taxable": false, + "pricing_scheme": "per_unit" + } +} +``` + diff --git a/doc/models/create-prepaid-usage-component-price-point.md b/doc/models/create-prepaid-usage-component-price-point.md new file mode 100644 index 00000000..afc85011 --- /dev/null +++ b/doc/models/create-prepaid-usage-component-price-point.md @@ -0,0 +1,53 @@ + +# Create Prepaid Usage Component Price Point + +## Structure + +`CreatePrepaidUsageComponentPricePoint` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | - | +| `Handle` | `*string` | Optional | - | +| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Required | - | +| `OveragePricing` | [`models.OveragePricing`](../../doc/models/overage-pricing.md) | Required | - | +| `UseSiteExchangeRate` | `*bool` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site.
**Default**: `true` | +| `RolloverPrepaidRemainder` | `*bool` | Optional | Boolean which controls whether or not remaining units should be rolled over to the next period | +| `RenewPrepaidAllocation` | `*bool` | Optional | Boolean which controls whether or not the allocated quantity should be renewed at the beginning of each period | +| `ExpirationInterval` | `*float64` | Optional | (only for prepaid usage components where rollover_prepaid_remainder is true) The number of `expiration_interval_unit`s after which rollover amounts should expire | +| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name0", + "pricing_scheme": "per_unit", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "overage_pricing": { + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ] + }, + "use_site_exchange_rate": true, + "handle": "handle6", + "rollover_prepaid_remainder": false, + "renew_prepaid_allocation": false, + "expiration_interval": 101.18 +} +``` + diff --git a/doc/models/create-prepayment-method.md b/doc/models/create-prepayment-method.md index 3fc490e8..4632493e 100644 --- a/doc/models/create-prepayment-method.md +++ b/doc/models/create-prepayment-method.md @@ -1,22 +1,22 @@ - -# Create Prepayment Method - -:- When the `method` specified is `"credit_card_on_file"`, the prepayment amount will be collected using the default credit card payment profile and applied to the prepayment account balance. This is especially useful for manual replenishment of prepaid subscriptions. - -## Enumeration - -`CreatePrepaymentMethod` - -## Fields - -| Name | -| --- | -| `CHECK` | -| `CASH` | -| `MONEYORDER` | -| `ACH` | -| `PAYPALACCOUNT` | -| `CREDITCARD` | -| `CREDITCARDONFILE` | -| `OTHER` | - + +# Create Prepayment Method + +:- When the `method` specified is `"credit_card_on_file"`, the prepayment amount will be collected using the default credit card payment profile and applied to the prepayment account balance. This is especially useful for manual replenishment of prepaid subscriptions. + +## Enumeration + +`CreatePrepaymentMethod` + +## Fields + +| Name | +| --- | +| `CHECK` | +| `CASH` | +| `MONEYORDER` | +| `ACH` | +| `PAYPALACCOUNT` | +| `CREDITCARD` | +| `CREDITCARDONFILE` | +| `OTHER` | + diff --git a/doc/models/create-prepayment-request.md b/doc/models/create-prepayment-request.md index 12a27cdf..3f3c9f8f 100644 --- a/doc/models/create-prepayment-request.md +++ b/doc/models/create-prepayment-request.md @@ -1,27 +1,27 @@ - -# Create Prepayment Request - -## Structure - -`CreatePrepaymentRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Prepayment` | [`models.CreatePrepayment`](../../doc/models/create-prepayment.md) | Required | - | - -## Example (as JSON) - -```json -{ - "prepayment": { - "amount": 11.6, - "details": "details8", - "memo": "memo2", - "method": "money_order", - "payment_profile_id": 240 - } -} -``` - + +# Create Prepayment Request + +## Structure + +`CreatePrepaymentRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Prepayment` | [`models.CreatePrepayment`](../../doc/models/create-prepayment.md) | Required | - | + +## Example (as JSON) + +```json +{ + "prepayment": { + "amount": 11.6, + "details": "details8", + "memo": "memo2", + "method": "money_order", + "payment_profile_id": 240 + } +} +``` + diff --git a/doc/models/create-prepayment-response.md b/doc/models/create-prepayment-response.md index c003a71a..b5d13566 100644 --- a/doc/models/create-prepayment-response.md +++ b/doc/models/create-prepayment-response.md @@ -1,27 +1,27 @@ - -# Create Prepayment Response - -## Structure - -`CreatePrepaymentResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Prepayment` | [`models.CreatedPrepayment`](../../doc/models/created-prepayment.md) | Required | - | - -## Example (as JSON) - -```json -{ - "prepayment": { - "id": 38, - "subscription_id": 148, - "amount_in_cents": 124, - "memo": "memo2", - "created_at": "2016-03-13T12:52:32.123Z" - } -} -``` - + +# Create Prepayment Response + +## Structure + +`CreatePrepaymentResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Prepayment` | [`models.CreatedPrepayment`](../../doc/models/created-prepayment.md) | Required | - | + +## Example (as JSON) + +```json +{ + "prepayment": { + "id": 38, + "subscription_id": 148, + "amount_in_cents": 124, + "memo": "memo2", + "created_at": "2016-03-13T12:52:32.123Z" + } +} +``` + diff --git a/doc/models/create-prepayment.md b/doc/models/create-prepayment.md index 20aa8b94..d1dba972 100644 --- a/doc/models/create-prepayment.md +++ b/doc/models/create-prepayment.md @@ -1,29 +1,29 @@ - -# Create Prepayment - -## Structure - -`CreatePrepayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Amount` | `float64` | Required | - | -| `Details` | `string` | Required | - | -| `Memo` | `string` | Required | - | -| `Method` | [`models.CreatePrepaymentMethod`](../../doc/models/create-prepayment-method.md) | Required | :- When the `method` specified is `"credit_card_on_file"`, the prepayment amount will be collected using the default credit card payment profile and applied to the prepayment account balance. This is especially useful for manual replenishment of prepaid subscriptions. | -| `PaymentProfileId` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "amount": 23.92, - "details": "details6", - "memo": "memo0", - "method": "credit_card_on_file", - "payment_profile_id": 240 -} -``` - + +# Create Prepayment + +## Structure + +`CreatePrepayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Amount` | `float64` | Required | - | +| `Details` | `string` | Required | - | +| `Memo` | `string` | Required | - | +| `Method` | [`models.CreatePrepaymentMethod`](../../doc/models/create-prepayment-method.md) | Required | :- When the `method` specified is `"credit_card_on_file"`, the prepayment amount will be collected using the default credit card payment profile and applied to the prepayment account balance. This is especially useful for manual replenishment of prepaid subscriptions. | +| `PaymentProfileId` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "amount": 23.92, + "details": "details6", + "memo": "memo0", + "method": "credit_card_on_file", + "payment_profile_id": 240 +} +``` + diff --git a/doc/models/create-product-currency-price.md b/doc/models/create-product-currency-price.md index 94259240..a0b29d5e 100644 --- a/doc/models/create-product-currency-price.md +++ b/doc/models/create-product-currency-price.md @@ -1,25 +1,25 @@ - -# Create Product Currency Price - -## Structure - -`CreateProductCurrencyPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Currency` | `string` | Required | ISO code for one of the site level currencies. | -| `Price` | `int` | Required | Price for the given role. | -| `Role` | [`models.CurrencyPriceRole`](../../doc/models/currency-price-role.md) | Required | Role for the price. | - -## Example (as JSON) - -```json -{ - "currency": "currency0", - "price": 222, - "role": "baseline" -} -``` - + +# Create Product Currency Price + +## Structure + +`CreateProductCurrencyPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Currency` | `string` | Required | ISO code for one of the site level currencies. | +| `Price` | `int` | Required | Price for the given role. | +| `Role` | [`models.CurrencyPriceRole`](../../doc/models/currency-price-role.md) | Required | Role for the price. | + +## Example (as JSON) + +```json +{ + "currency": "currency0", + "price": 222, + "role": "baseline" +} +``` + diff --git a/doc/models/create-product-currency-prices-request.md b/doc/models/create-product-currency-prices-request.md index 9590cf62..7b9ab481 100644 --- a/doc/models/create-product-currency-prices-request.md +++ b/doc/models/create-product-currency-prices-request.md @@ -1,27 +1,27 @@ - -# Create Product Currency Prices Request - -## Structure - -`CreateProductCurrencyPricesRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CurrencyPrices` | [`[]models.CreateProductCurrencyPrice`](../../doc/models/create-product-currency-price.md) | Required | - | - -## Example (as JSON) - -```json -{ - "currency_prices": [ - { - "currency": "currency8", - "price": 78, - "role": "initial" - } - ] -} -``` - + +# Create Product Currency Prices Request + +## Structure + +`CreateProductCurrencyPricesRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrencyPrices` | [`[]models.CreateProductCurrencyPrice`](../../doc/models/create-product-currency-price.md) | Required | - | + +## Example (as JSON) + +```json +{ + "currency_prices": [ + { + "currency": "currency8", + "price": 78, + "role": "initial" + } + ] +} +``` + diff --git a/doc/models/create-product-family-request.md b/doc/models/create-product-family-request.md index 86b23579..ce26c455 100644 --- a/doc/models/create-product-family-request.md +++ b/doc/models/create-product-family-request.md @@ -1,24 +1,24 @@ - -# Create Product Family Request - -## Structure - -`CreateProductFamilyRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ProductFamily` | [`models.CreateProductFamily`](../../doc/models/create-product-family.md) | Required | - | - -## Example (as JSON) - -```json -{ - "product_family": { - "name": "name0", - "description": "description0" - } -} -``` - + +# Create Product Family Request + +## Structure + +`CreateProductFamilyRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProductFamily` | [`models.CreateProductFamily`](../../doc/models/create-product-family.md) | Required | - | + +## Example (as JSON) + +```json +{ + "product_family": { + "name": "name0", + "description": "description0" + } +} +``` + diff --git a/doc/models/create-product-family.md b/doc/models/create-product-family.md index e6dd615b..c2397892 100644 --- a/doc/models/create-product-family.md +++ b/doc/models/create-product-family.md @@ -1,23 +1,23 @@ - -# Create Product Family - -## Structure - -`CreateProductFamily` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `*string` | Optional | - | -| `Description` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "name": "name6", - "description": "description6" -} -``` - + +# Create Product Family + +## Structure + +`CreateProductFamily` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `*string` | Optional | - | +| `Description` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name6", + "description": "description6" +} +``` + diff --git a/doc/models/create-product-price-point-request.md b/doc/models/create-product-price-point-request.md index 6afe2a60..a4d8de9b 100644 --- a/doc/models/create-product-price-point-request.md +++ b/doc/models/create-product-price-point-request.md @@ -1,32 +1,32 @@ - -# Create Product Price Point Request - -## Structure - -`CreateProductPricePointRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoint` | [`models.CreateProductPricePoint`](../../doc/models/create-product-price-point.md) | Required | - | - -## Example (as JSON) - -```json -{ - "price_point": { - "name": "name0", - "price_in_cents": 196, - "interval": 44, - "interval_unit": "day", - "use_site_exchange_rate": true, - "handle": "handle6", - "trial_price_in_cents": 108, - "trial_interval": 202, - "trial_interval_unit": "day", - "trial_type": "trial_type4" - } -} -``` - + +# Create Product Price Point Request + +## Structure + +`CreateProductPricePointRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoint` | [`models.CreateProductPricePoint`](../../doc/models/create-product-price-point.md) | Required | - | + +## Example (as JSON) + +```json +{ + "price_point": { + "name": "name0", + "price_in_cents": 196, + "interval": 44, + "interval_unit": "day", + "use_site_exchange_rate": true, + "handle": "handle6", + "trial_price_in_cents": 108, + "trial_interval": 202, + "trial_interval_unit": "day", + "trial_type": "trial_type4" + } +} +``` + diff --git a/doc/models/create-product-price-point.md b/doc/models/create-product-price-point.md index c21b2864..d615b05d 100644 --- a/doc/models/create-product-price-point.md +++ b/doc/models/create-product-price-point.md @@ -1,43 +1,43 @@ - -# Create Product Price Point - -## Structure - -`CreateProductPricePoint` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `string` | Required | The product price point name | -| `Handle` | `*string` | Optional | The product price point API handle | -| `PriceInCents` | `int64` | Required | The product price point price, in integer cents | -| `Interval` | `int` | Required | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product price point would renew every 30 days | -| `IntervalUnit` | [`models.IntervalUnit`](../../doc/models/interval-unit.md) | Required | A string representing the interval unit for this product price point, either month or day | -| `TrialPriceInCents` | `*int64` | Optional | The product price point trial price, in integer cents | -| `TrialInterval` | `*int` | Optional | The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product price point trial would last 30 days. | -| `TrialIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the trial interval unit for this product price point, either month or day | -| `TrialType` | `*string` | Optional | - | -| `InitialChargeInCents` | `*int64` | Optional | The product price point initial charge, in integer cents | -| `InitialChargeAfterTrial` | `*bool` | Optional | - | -| `ExpirationInterval` | `*int` | Optional | The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product price point would expire after 30 days. | -| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the expiration interval unit for this product price point, either month or day | -| `UseSiteExchangeRate` | `*bool` | Optional | Whether or not to use the site's exchange rate or define your own pricing when your site has multiple currencies defined.
**Default**: `true` | - -## Example (as JSON) - -```json -{ - "name": "name6", - "price_in_cents": 216, - "interval": 200, - "interval_unit": "day", - "use_site_exchange_rate": true, - "handle": "handle2", - "trial_price_in_cents": 48, - "trial_interval": 102, - "trial_interval_unit": "day", - "trial_type": "trial_type0" -} -``` - + +# Create Product Price Point + +## Structure + +`CreateProductPricePoint` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | The product price point name | +| `Handle` | `*string` | Optional | The product price point API handle | +| `PriceInCents` | `int64` | Required | The product price point price, in integer cents | +| `Interval` | `int` | Required | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product price point would renew every 30 days | +| `IntervalUnit` | [`models.IntervalUnit`](../../doc/models/interval-unit.md) | Required | A string representing the interval unit for this product price point, either month or day | +| `TrialPriceInCents` | `*int64` | Optional | The product price point trial price, in integer cents | +| `TrialInterval` | `*int` | Optional | The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product price point trial would last 30 days. | +| `TrialIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the trial interval unit for this product price point, either month or day | +| `TrialType` | `*string` | Optional | - | +| `InitialChargeInCents` | `*int64` | Optional | The product price point initial charge, in integer cents | +| `InitialChargeAfterTrial` | `*bool` | Optional | - | +| `ExpirationInterval` | `*int` | Optional | The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product price point would expire after 30 days. | +| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the expiration interval unit for this product price point, either month or day | +| `UseSiteExchangeRate` | `*bool` | Optional | Whether or not to use the site's exchange rate or define your own pricing when your site has multiple currencies defined.
**Default**: `true` | + +## Example (as JSON) + +```json +{ + "name": "name6", + "price_in_cents": 216, + "interval": 200, + "interval_unit": "day", + "use_site_exchange_rate": true, + "handle": "handle2", + "trial_price_in_cents": 48, + "trial_interval": 102, + "trial_interval_unit": "day", + "trial_type": "trial_type0" +} +``` + diff --git a/doc/models/create-quantity-based-component.md b/doc/models/create-quantity-based-component.md index 6e4fb9ba..7826e97c 100644 --- a/doc/models/create-quantity-based-component.md +++ b/doc/models/create-quantity-based-component.md @@ -1,59 +1,41 @@ - -# Create Quantity Based Component - -## Structure - -`CreateQuantityBasedComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `QuantityBasedComponent` | [`models.QuantityBasedComponent`](../../doc/models/quantity-based-component.md) | Required | - | - -## Example (as JSON) - -```json -{ - "quantity_based_component": { - "name": "name0", - "unit_name": "unit_name2", - "description": "description0", - "handle": "handle6", - "taxable": false, - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ], - "upgrade_charge": "prorated" - } -} -``` - + +# Create Quantity Based Component + +## Structure + +`CreateQuantityBasedComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `QuantityBasedComponent` | [`models.QuantityBasedComponent`](../../doc/models/quantity-based-component.md) | Required | - | + +## Example (as JSON) + +```json +{ + "quantity_based_component": { + "name": "name0", + "unit_name": "unit_name2", + "description": "description0", + "handle": "handle6", + "taxable": false, + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "upgrade_charge": "prorated" + } +} +``` + diff --git a/doc/models/create-reason-code-request.md b/doc/models/create-reason-code-request.md index cea73d8c..6f999969 100644 --- a/doc/models/create-reason-code-request.md +++ b/doc/models/create-reason-code-request.md @@ -1,25 +1,25 @@ - -# Create Reason Code Request - -## Structure - -`CreateReasonCodeRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ReasonCode` | [`models.CreateReasonCode`](../../doc/models/create-reason-code.md) | Required | - | - -## Example (as JSON) - -```json -{ - "reason_code": { - "code": "code4", - "description": "description6", - "position": 14 - } -} -``` - + +# Create Reason Code Request + +## Structure + +`CreateReasonCodeRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ReasonCode` | [`models.CreateReasonCode`](../../doc/models/create-reason-code.md) | Required | - | + +## Example (as JSON) + +```json +{ + "reason_code": { + "code": "code4", + "description": "description6", + "position": 14 + } +} +``` + diff --git a/doc/models/create-reason-code.md b/doc/models/create-reason-code.md index c86e0f84..172da004 100644 --- a/doc/models/create-reason-code.md +++ b/doc/models/create-reason-code.md @@ -1,25 +1,25 @@ - -# Create Reason Code - -## Structure - -`CreateReasonCode` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Code` | `string` | Required | The unique identifier for the ReasonCode | -| `Description` | `string` | Required | The friendly summary of what the code signifies | -| `Position` | `*int` | Optional | The order that code appears in lists | - -## Example (as JSON) - -```json -{ - "code": "code4", - "description": "description6", - "position": 86 -} -``` - + +# Create Reason Code + +## Structure + +`CreateReasonCode` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Code` | `string` | Required | The unique identifier for the ReasonCode | +| `Description` | `string` | Required | The friendly summary of what the code signifies | +| `Position` | `*int` | Optional | The order that code appears in lists | + +## Example (as JSON) + +```json +{ + "code": "code4", + "description": "description6", + "position": 86 +} +``` + diff --git a/doc/models/create-segment-request.md b/doc/models/create-segment-request.md index 03dbea09..33e84bec 100644 --- a/doc/models/create-segment-request.md +++ b/doc/models/create-segment-request.md @@ -1,65 +1,44 @@ - -# Create Segment Request - -## Structure - -`CreateSegmentRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Segment` | [`models.CreateSegment`](../../doc/models/create-segment.md) | Required | - | - -## Example (as JSON) - -```json -{ - "segment": { - "segment_property_1_value": { - "key1": "val1", - "key2": "val2" - }, - "segment_property_2_value": { - "key1": "val1", - "key2": "val2" - }, - "segment_property_3_value": { - "key1": "val1", - "key2": "val2" - }, - "segment_property_4_value": { - "key1": "val1", - "key2": "val2" - }, - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - } -} -``` - + +# Create Segment Request + +## Structure + +`CreateSegmentRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Segment` | [`models.CreateSegment`](../../doc/models/create-segment.md) | Required | - | + +## Example (as JSON) + +```json +{ + "segment": { + "segment_property_1_value": "String1", + "segment_property_2_value": "String3", + "segment_property_3_value": "String1", + "segment_property_4_value": "String5", + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + } + ] + } +} +``` + diff --git a/doc/models/create-segment.md b/doc/models/create-segment.md index bc21bdf6..236e72a0 100644 --- a/doc/models/create-segment.md +++ b/doc/models/create-segment.md @@ -1,68 +1,47 @@ - -# Create Segment - -## Structure - -`CreateSegment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SegmentProperty1Value` | `*interface{}` | Optional | A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. | -| `SegmentProperty2Value` | `*interface{}` | Optional | A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. | -| `SegmentProperty3Value` | `*interface{}` | Optional | A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. | -| `SegmentProperty4Value` | `*interface{}` | Optional | A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. | -| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Prices` | [`[]models.CreateOrUpdateSegmentPrice`](../../doc/models/create-or-update-segment-price.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "segment_property_1_value": { - "key1": "val1", - "key2": "val2" - }, - "segment_property_2_value": { - "key1": "val1", - "key2": "val2" - }, - "segment_property_3_value": { - "key1": "val1", - "key2": "val2" - }, - "segment_property_4_value": { - "key1": "val1", - "key2": "val2" - }, - "pricing_scheme": "per_unit", - "prices": [ - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] -} -``` - + +# Create Segment + +## Structure + +`CreateSegment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SegmentProperty1Value` | [`*models.CreateSegmentSegmentProperty1Value`](../../doc/models/containers/create-segment-segment-property-1-value.md) | Optional | This is a container for one-of cases. | +| `SegmentProperty2Value` | [`*models.CreateSegmentSegmentProperty2Value`](../../doc/models/containers/create-segment-segment-property-2-value.md) | Optional | This is a container for one-of cases. | +| `SegmentProperty3Value` | [`*models.CreateSegmentSegmentProperty3Value`](../../doc/models/containers/create-segment-segment-property-3-value.md) | Optional | This is a container for one-of cases. | +| `SegmentProperty4Value` | [`*models.CreateSegmentSegmentProperty4Value`](../../doc/models/containers/create-segment-segment-property-4-value.md) | Optional | This is a container for one-of cases. | +| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.CreateOrUpdateSegmentPrice`](../../doc/models/create-or-update-segment-price.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "segment_property_1_value": "String9", + "segment_property_2_value": "String1", + "segment_property_3_value": "String3", + "segment_property_4_value": "String3", + "pricing_scheme": "per_unit", + "prices": [ + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + } + ] +} +``` + diff --git a/doc/models/create-signup-proforma-preview-include.md b/doc/models/create-signup-proforma-preview-include.md index 01c0290e..d2c6892e 100644 --- a/doc/models/create-signup-proforma-preview-include.md +++ b/doc/models/create-signup-proforma-preview-include.md @@ -1,19 +1,19 @@ - -# Create Signup Proforma Preview Include - -## Enumeration - -`CreateSignupProformaPreviewInclude` - -## Fields - -| Name | -| --- | -| `NEXTPROFORMAINVOICE` | - -## Example - -``` -next_proforma_invoice -``` - + +# Create Signup Proforma Preview Include + +## Enumeration + +`CreateSignupProformaPreviewInclude` + +## Fields + +| Name | +| --- | +| `NEXTPROFORMAINVOICE` | + +## Example + +``` +next_proforma_invoice +``` + diff --git a/doc/models/create-subscription-component.md b/doc/models/create-subscription-component.md index b59cb2ba..7b9426fa 100644 --- a/doc/models/create-subscription-component.md +++ b/doc/models/create-subscription-component.md @@ -1,37 +1,31 @@ - -# Create Subscription Component - -## Structure - -`CreateSubscriptionComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ComponentId` | `*interface{}` | Optional | - | -| `Enabled` | `*bool` | Optional | Used for on/off components only. | -| `UnitBalance` | `*int` | Optional | Used for metered and events based components. | -| `AllocatedQuantity` | `*interface{}` | Optional | Used for quantity based components. | -| `Quantity` | `*int` | Optional | Deprecated. Use `allocated_quantity` instead. | -| `PricePointId` | `*interface{}` | Optional | - | -| `CustomPrice` | [`*models.ComponentCustomPrice`](../../doc/models/component-custom-price.md) | Optional | Create or update custom pricing unique to the subscription. Used in place of `price_point_id`. | - -## Example (as JSON) - -```json -{ - "component_id": { - "key1": "val1", - "key2": "val2" - }, - "enabled": false, - "unit_balance": 144, - "allocated_quantity": { - "key1": "val1", - "key2": "val2" - }, - "quantity": 188 -} -``` - + +# Create Subscription Component + +## Structure + +`CreateSubscriptionComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ComponentId` | [`*models.CreateSubscriptionComponentComponentId`](../../doc/models/containers/create-subscription-component-component-id.md) | Optional | This is a container for one-of cases. | +| `Enabled` | `*bool` | Optional | Used for on/off components only. | +| `UnitBalance` | `*int` | Optional | Used for metered and events based components. | +| `AllocatedQuantity` | [`*models.CreateSubscriptionComponentAllocatedQuantity`](../../doc/models/containers/create-subscription-component-allocated-quantity.md) | Optional | This is a container for one-of cases. | +| `Quantity` | `*int` | Optional | Deprecated. Use `allocated_quantity` instead. | +| `PricePointId` | [`*models.CreateSubscriptionComponentPricePointId`](../../doc/models/containers/create-subscription-component-price-point-id.md) | Optional | This is a container for one-of cases. | +| `CustomPrice` | [`*models.ComponentCustomPrice`](../../doc/models/component-custom-price.md) | Optional | Create or update custom pricing unique to the subscription. Used in place of `price_point_id`. | + +## Example (as JSON) + +```json +{ + "component_id": 8, + "enabled": false, + "unit_balance": 144, + "allocated_quantity": 102, + "quantity": 188 +} +``` + diff --git a/doc/models/create-subscription-group-request.md b/doc/models/create-subscription-group-request.md index a302c937..2dc1c997 100644 --- a/doc/models/create-subscription-group-request.md +++ b/doc/models/create-subscription-group-request.md @@ -1,30 +1,27 @@ - -# Create Subscription Group Request - -## Structure - -`CreateSubscriptionGroupRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SubscriptionGroup` | [`models.CreateSubscriptionGroup`](../../doc/models/create-subscription-group.md) | Required | - | - -## Example (as JSON) - -```json -{ - "subscription_group": { - "subscription_id": { - "key1": "val1", - "key2": "val2" - }, - "member_ids": [ - 164, - 165 - ] - } -} -``` - + +# Create Subscription Group Request + +## Structure + +`CreateSubscriptionGroupRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionGroup` | [`models.CreateSubscriptionGroup`](../../doc/models/create-subscription-group.md) | Required | - | + +## Example (as JSON) + +```json +{ + "subscription_group": { + "subscription_id": 36, + "member_ids": [ + 164, + 165 + ] + } +} +``` + diff --git a/doc/models/create-subscription-group.md b/doc/models/create-subscription-group.md index 98c9ffbe..3ab5536a 100644 --- a/doc/models/create-subscription-group.md +++ b/doc/models/create-subscription-group.md @@ -1,28 +1,25 @@ - -# Create Subscription Group - -## Structure - -`CreateSubscriptionGroup` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SubscriptionId` | `interface{}` | Required | - | -| `MemberIds` | `[]int` | Optional | - | - -## Example (as JSON) - -```json -{ - "subscription_id": { - "key1": "val1", - "key2": "val2" - }, - "member_ids": [ - 162 - ] -} -``` - + +# Create Subscription Group + +## Structure + +`CreateSubscriptionGroup` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionId` | `int` | Required | - | +| `MemberIds` | `[]int` | Optional | - | + +## Example (as JSON) + +```json +{ + "subscription_id": 38, + "member_ids": [ + 162 + ] +} +``` + diff --git a/doc/models/create-subscription-request.md b/doc/models/create-subscription-request.md index aa9787fa..ef2372cb 100644 --- a/doc/models/create-subscription-request.md +++ b/doc/models/create-subscription-request.md @@ -1,56 +1,44 @@ - -# Create Subscription Request - -## Structure - -`CreateSubscriptionRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Subscription` | [`models.CreateSubscription`](../../doc/models/create-subscription.md) | Required | - | - -## Example (as JSON) - -```json -{ - "subscription": { - "payment_collection_method": "automatic", - "metafields": { - "custom_field_name_1": "custom_field_value_1", - "custom_field_name_2": "custom_field_value_2" - }, - "dunning_communication_delay_enabled": false, - "dunning_communication_delay_time_zone": "\"Eastern Time (US & Canada)\"", - "skip_billing_manifest_taxes": false, - "product_handle": "product_handle6", - "product_id": 206, - "product_price_point_handle": "product_price_point_handle2", - "product_price_point_id": 130, - "custom_price": { - "name": "name4", - "handle": "handle0", - "price_in_cents": { - "key1": "val1", - "key2": "val2" - }, - "interval": { - "key1": "val1", - "key2": "val2" - }, - "interval_unit": "day", - "trial_price_in_cents": { - "key1": "val1", - "key2": "val2" - }, - "trial_interval": { - "key1": "val1", - "key2": "val2" - }, - "trial_interval_unit": "day" - } - } -} -``` - + +# Create Subscription Request + +## Structure + +`CreateSubscriptionRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Subscription` | [`models.CreateSubscription`](../../doc/models/create-subscription.md) | Required | - | + +## Example (as JSON) + +```json +{ + "subscription": { + "payment_collection_method": "automatic", + "metafields": { + "custom_field_name_1": "custom_field_value_1", + "custom_field_name_2": "custom_field_value_2" + }, + "dunning_communication_delay_enabled": false, + "dunning_communication_delay_time_zone": "\"Eastern Time (US & Canada)\"", + "skip_billing_manifest_taxes": false, + "product_handle": "product_handle6", + "product_id": 206, + "product_price_point_handle": "product_price_point_handle2", + "product_price_point_id": 130, + "custom_price": { + "name": "name4", + "handle": "handle0", + "price_in_cents": "String3", + "interval": "String3", + "interval_unit": "day", + "trial_price_in_cents": "String3", + "trial_interval": "String5", + "trial_interval_unit": "day" + } + } +} +``` + diff --git a/doc/models/create-subscription.md b/doc/models/create-subscription.md index 9fe61526..7aa91419 100644 --- a/doc/models/create-subscription.md +++ b/doc/models/create-subscription.md @@ -1,102 +1,90 @@ - -# Create Subscription - -## Structure - -`CreateSubscription` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ProductHandle` | `*string` | Optional | The API Handle of the product for which you are creating a subscription. Required, unless a `product_id` is given instead. | -| `ProductId` | `*int` | Optional | The Product ID of the product for which you are creating a subscription. The product ID is not currently published, so we recommend using the API Handle instead. | -| `ProductPricePointHandle` | `*string` | Optional | The user-friendly API handle of a product's particular price point. | -| `ProductPricePointId` | `*int` | Optional | The ID of the particular price point on the product. | -| `CustomPrice` | [`*models.SubscriptionCustomPrice`](../../doc/models/subscription-custom-price.md) | Optional | (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription | -| `CouponCode` | `*string` | Optional | (deprecated) The coupon code of the single coupon currently applied to the subscription. See coupon_codes instead as subscriptions can now have more than one coupon. | -| `CouponCodes` | `[]string` | Optional | An array for all the coupons attached to the subscription. | -| `PaymentCollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | -| `ReceivesInvoiceEmails` | `*string` | Optional | (Optional) Default: True - Whether or not this subscription is set to receive emails related to this subscription. | -| `NetTerms` | `*string` | Optional | (Optional) Default: null The number of days after renewal (on invoice billing) that a subscription is due. A value between 0 (due immediately) and 180. | -| `CustomerId` | `*int` | Optional | The ID of an existing customer within Chargify. Required, unless a `customer_reference` or a set of `customer_attributes` is given. | -| `NextBillingAt` | `*time.Time` | Optional | (Optional) Set this attribute to a future date/time to sync imported subscriptions to your existing renewal schedule. See the notes on “Date/Time Format” in our [subscription import documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#date-format). If you provide a next_billing_at timestamp that is in the future, no trial or initial charges will be applied when you create the subscription. In fact, no payment will be captured at all. The first payment will be captured, according to the prices defined by the product, near the time specified by next_billing_at. If you do not provide a value for next_billing_at, any trial and/or initial charges will be assessed and charged at the time of subscription creation. If the card cannot be successfully charged, the subscription will not be created. See further notes in the section on Importing Subscriptions. | -| `InitialBillingAt` | `*time.Time` | Optional | (Optional) Set this attribute to a future date/time to create a subscription in the "Awaiting Signup" state, rather than "Active" or "Trialing". See the notes on “Date/Time Format” in our [subscription import documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#date-format). In the "Awaiting Signup" state, a subscription behaves like any other. It can be canceled, allocated to, had its billing date changed. etc. When the initial_billing_at date hits, the subscription will transition to the expected state. If the product has a trial, the subscription will enter a trial, otherwise it will go active. Setup fees will be respected either before or after the trial, as configured on the price point. If the payment is due at the initial_billing_at and it fails the subscription will be immediately canceled. See further notes in the section on Delayed Signups. | -| `StoredCredentialTransactionId` | `*int` | Optional | For European sites subject to PSD2 and using 3D Secure, this can be used to reference a previous transaction for the customer. This will ensure the card will be charged successfully at renewal. | -| `SalesRepId` | `*int` | Optional | - | -| `PaymentProfileId` | `*int` | Optional | The Payment Profile ID of an existing card or bank account, which belongs to an existing customer to use for payment for this subscription. If the card, bank account, or customer does not exist already, or if you want to use a new (unstored) card or bank account for the subscription, use `payment_profile_attributes` instead to create a new payment profile along with the subscription. (This value is available on an existing subscription via the API as `credit_card` > id or `bank_account` > id) | -| `Reference` | `*string` | Optional | The reference value (provided by your app) for the subscription itelf. | -| `CustomerAttributes` | [`*models.CustomerAttributes`](../../doc/models/customer-attributes.md) | Optional | - | -| `PaymentProfileAttributes` | [`*models.PaymentProfileAttributes`](../../doc/models/payment-profile-attributes.md) | Optional | alias to credit_card_attributes | -| `CreditCardAttributes` | [`*models.PaymentProfileAttributes`](../../doc/models/payment-profile-attributes.md) | Optional | Credit Card data to create a new Subscription. Interchangeable with `payment_profile_attributes` property. | -| `BankAccountAttributes` | [`*models.BankAccountAttributes`](../../doc/models/bank-account-attributes.md) | Optional | - | -| `Components` | [`[]models.CreateSubscriptionComponent`](../../doc/models/create-subscription-component.md) | Optional | (Optional) An array of component ids and quantities to be added to the subscription. See [Components](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677) for more information. | -| `CalendarBilling` | [`*models.CalendarBilling`](../../doc/models/calendar-billing.md) | Optional | (Optional). Cannot be used when also specifying next_billing_at | -| `Metafields` | `map[string]string` | Optional | (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. | -| `CustomerReference` | `*string` | Optional | The reference value (provided by your app) of an existing customer within Chargify. Required, unless a `customer_id` or a set of `customer_attributes` is given. | -| `Group` | [`*models.GroupSettings`](../../doc/models/group-settings.md) | Optional | - | -| `Ref` | `*string` | Optional | A valid referral code. (optional, see [Referrals](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405420204045-Referrals-Reference#how-to-obtain-referral-codes) for more details). If supplied, must be valid, or else subscription creation will fail. | -| `CancellationMessage` | `*string` | Optional | (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to make a note about the reason for cancellation. | -| `CancellationMethod` | `*string` | Optional | (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to make a note about how the subscription was canceled. | -| `Currency` | `*string` | Optional | (Optional) If Multi-Currency is enabled and the currency is configured in Chargify, pass it at signup to create a subscription on a non-default currency. Note that you cannot update the currency of an existing subscription. | -| `ExpiresAt` | `*time.Time` | Optional | Timestamp giving the expiration date of this subscription (if any). You may manually change the expiration date at any point during a subscription period. | -| `ExpirationTracksNextBillingChange` | `*string` | Optional | (Optional, default false) When set to true, and when next_billing_at is present, if the subscription expires, the expires_at will be shifted by the same amount of time as the difference between the old and new “next billing” dates. | -| `AgreementTerms` | `*string` | Optional | (Optional) The ACH authorization agreement terms. If enabled, an email will be sent to the customer with a copy of the terms. | -| `AuthorizerFirstName` | `*string` | Optional | (Optional) The first name of the person authorizing the ACH agreement. | -| `AuthorizerLastName` | `*string` | Optional | (Optional) The last name of the person authorizing the ACH agreement. | -| `CalendarBillingFirstCharge` | `*string` | Optional | (Optional) One of “prorated” (the default – the prorated product price will be charged immediately), “immediate” (the full product price will be charged immediately), or “delayed” (the full product price will be charged with the first scheduled renewal). | -| `ReasonCode` | `*string` | Optional | (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to indicate why a subscription was canceled. | -| `ProductChangeDelayed` | `*bool` | Optional | (Optional, used only for Delayed Product Change When set to true, indicates that a changed value for product_handle should schedule the product change to the next subscription renewal. | -| `OfferId` | `*interface{}` | Optional | Use in place of passing product and component information to set up the subscription with an existing offer. May be either the Chargify id of the offer or its handle prefixed with `handle:`.er | -| `PrepaidConfiguration` | [`*models.UpsertPrepaidConfiguration`](../../doc/models/upsert-prepaid-configuration.md) | Optional | - | -| `PreviousBillingAt` | `*time.Time` | Optional | Providing a previous_billing_at that is in the past will set the current_period_starts_at when the subscription is created. It will also set activated_at if not explicitly passed during the subscription import. Can only be used if next_billing_at is also passed. Using this option will allow you to set the period start for the subscription so mid period component allocations have the correct prorated amount. | -| `ImportMrr` | `*bool` | Optional | Setting this attribute to true will cause the subscription's MRR to be added to your MRR analytics immediately. For this value to be honored, a next_billing_at must be present and set to a future date. This key/value will not be returned in the subscription response body. | -| `CanceledAt` | `*time.Time` | Optional | - | -| `ActivatedAt` | `*time.Time` | Optional | - | -| `AgreementAcceptance` | [`*models.AgreementAcceptance`](../../doc/models/agreement-acceptance.md) | Optional | Required when creating a subscription with Maxio Payments. | -| `AchAgreement` | [`*models.ACHAgreement`](../../doc/models/ach-agreement.md) | Optional | (Optional) If passed, the proof of the authorized ACH agreement terms will be persisted. | -| `DunningCommunicationDelayEnabled` | `Optional[bool]` | Optional | Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute.
**Default**: `false` | -| `DunningCommunicationDelayTimeZone` | `Optional[string]` | Optional | Time zone for the Dunning Communication Delay feature. | -| `SkipBillingManifestTaxes` | `*bool` | Optional | Valid only for the Subscription Preview endpoint. When set to `true` it skips calculating taxes for the current and next billing manifests.
**Default**: `false` | - -## Example (as JSON) - -```json -{ - "payment_collection_method": "automatic", - "metafields": { - "custom_field_name_1": "custom_field_value_1", - "custom_field_name_2": "custom_field_value_2" - }, - "dunning_communication_delay_enabled": false, - "dunning_communication_delay_time_zone": "\"Eastern Time (US & Canada)\"", - "skip_billing_manifest_taxes": false, - "product_handle": "product_handle6", - "product_id": 212, - "product_price_point_handle": "product_price_point_handle0", - "product_price_point_id": 136, - "custom_price": { - "name": "name4", - "handle": "handle0", - "price_in_cents": { - "key1": "val1", - "key2": "val2" - }, - "interval": { - "key1": "val1", - "key2": "val2" - }, - "interval_unit": "day", - "trial_price_in_cents": { - "key1": "val1", - "key2": "val2" - }, - "trial_interval": { - "key1": "val1", - "key2": "val2" - }, - "trial_interval_unit": "day" - } -} -``` - + +# Create Subscription + +## Structure + +`CreateSubscription` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProductHandle` | `*string` | Optional | The API Handle of the product for which you are creating a subscription. Required, unless a `product_id` is given instead. | +| `ProductId` | `*int` | Optional | The Product ID of the product for which you are creating a subscription. The product ID is not currently published, so we recommend using the API Handle instead. | +| `ProductPricePointHandle` | `*string` | Optional | The user-friendly API handle of a product's particular price point. | +| `ProductPricePointId` | `*int` | Optional | The ID of the particular price point on the product. | +| `CustomPrice` | [`*models.SubscriptionCustomPrice`](../../doc/models/subscription-custom-price.md) | Optional | (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription | +| `CouponCode` | `*string` | Optional | (deprecated) The coupon code of the single coupon currently applied to the subscription. See coupon_codes instead as subscriptions can now have more than one coupon. | +| `CouponCodes` | `[]string` | Optional | An array for all the coupons attached to the subscription. | +| `PaymentCollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | +| `ReceivesInvoiceEmails` | `*string` | Optional | (Optional) Default: True - Whether or not this subscription is set to receive emails related to this subscription. | +| `NetTerms` | `*string` | Optional | (Optional) Default: null The number of days after renewal (on invoice billing) that a subscription is due. A value between 0 (due immediately) and 180. | +| `CustomerId` | `*int` | Optional | The ID of an existing customer within Chargify. Required, unless a `customer_reference` or a set of `customer_attributes` is given. | +| `NextBillingAt` | `*time.Time` | Optional | (Optional) Set this attribute to a future date/time to sync imported subscriptions to your existing renewal schedule. See the notes on “Date/Time Format” in our [subscription import documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#date-format). If you provide a next_billing_at timestamp that is in the future, no trial or initial charges will be applied when you create the subscription. In fact, no payment will be captured at all. The first payment will be captured, according to the prices defined by the product, near the time specified by next_billing_at. If you do not provide a value for next_billing_at, any trial and/or initial charges will be assessed and charged at the time of subscription creation. If the card cannot be successfully charged, the subscription will not be created. See further notes in the section on Importing Subscriptions. | +| `InitialBillingAt` | `*time.Time` | Optional | (Optional) Set this attribute to a future date/time to create a subscription in the "Awaiting Signup" state, rather than "Active" or "Trialing". See the notes on “Date/Time Format” in our [subscription import documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#date-format). In the "Awaiting Signup" state, a subscription behaves like any other. It can be canceled, allocated to, had its billing date changed. etc. When the initial_billing_at date hits, the subscription will transition to the expected state. If the product has a trial, the subscription will enter a trial, otherwise it will go active. Setup fees will be respected either before or after the trial, as configured on the price point. If the payment is due at the initial_billing_at and it fails the subscription will be immediately canceled. See further notes in the section on Delayed Signups. | +| `StoredCredentialTransactionId` | `*int` | Optional | For European sites subject to PSD2 and using 3D Secure, this can be used to reference a previous transaction for the customer. This will ensure the card will be charged successfully at renewal. | +| `SalesRepId` | `*int` | Optional | - | +| `PaymentProfileId` | `*int` | Optional | The Payment Profile ID of an existing card or bank account, which belongs to an existing customer to use for payment for this subscription. If the card, bank account, or customer does not exist already, or if you want to use a new (unstored) card or bank account for the subscription, use `payment_profile_attributes` instead to create a new payment profile along with the subscription. (This value is available on an existing subscription via the API as `credit_card` > id or `bank_account` > id) | +| `Reference` | `*string` | Optional | The reference value (provided by your app) for the subscription itelf. | +| `CustomerAttributes` | [`*models.CustomerAttributes`](../../doc/models/customer-attributes.md) | Optional | - | +| `PaymentProfileAttributes` | [`*models.PaymentProfileAttributes`](../../doc/models/payment-profile-attributes.md) | Optional | alias to credit_card_attributes | +| `CreditCardAttributes` | [`*models.PaymentProfileAttributes`](../../doc/models/payment-profile-attributes.md) | Optional | Credit Card data to create a new Subscription. Interchangeable with `payment_profile_attributes` property. | +| `BankAccountAttributes` | [`*models.BankAccountAttributes`](../../doc/models/bank-account-attributes.md) | Optional | - | +| `Components` | [`[]models.CreateSubscriptionComponent`](../../doc/models/create-subscription-component.md) | Optional | (Optional) An array of component ids and quantities to be added to the subscription. See [Components](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677) for more information. | +| `CalendarBilling` | [`*models.CalendarBilling`](../../doc/models/calendar-billing.md) | Optional | (Optional). Cannot be used when also specifying next_billing_at | +| `Metafields` | `map[string]string` | Optional | (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. | +| `CustomerReference` | `*string` | Optional | The reference value (provided by your app) of an existing customer within Chargify. Required, unless a `customer_id` or a set of `customer_attributes` is given. | +| `Group` | [`*models.GroupSettings`](../../doc/models/group-settings.md) | Optional | - | +| `Ref` | `*string` | Optional | A valid referral code. (optional, see [Referrals](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405420204045-Referrals-Reference#how-to-obtain-referral-codes) for more details). If supplied, must be valid, or else subscription creation will fail. | +| `CancellationMessage` | `*string` | Optional | (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to make a note about the reason for cancellation. | +| `CancellationMethod` | `*string` | Optional | (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to make a note about how the subscription was canceled. | +| `Currency` | `*string` | Optional | (Optional) If Multi-Currency is enabled and the currency is configured in Chargify, pass it at signup to create a subscription on a non-default currency. Note that you cannot update the currency of an existing subscription. | +| `ExpiresAt` | `*time.Time` | Optional | Timestamp giving the expiration date of this subscription (if any). You may manually change the expiration date at any point during a subscription period. | +| `ExpirationTracksNextBillingChange` | `*string` | Optional | (Optional, default false) When set to true, and when next_billing_at is present, if the subscription expires, the expires_at will be shifted by the same amount of time as the difference between the old and new “next billing” dates. | +| `AgreementTerms` | `*string` | Optional | (Optional) The ACH authorization agreement terms. If enabled, an email will be sent to the customer with a copy of the terms. | +| `AuthorizerFirstName` | `*string` | Optional | (Optional) The first name of the person authorizing the ACH agreement. | +| `AuthorizerLastName` | `*string` | Optional | (Optional) The last name of the person authorizing the ACH agreement. | +| `CalendarBillingFirstCharge` | `*string` | Optional | (Optional) One of “prorated” (the default – the prorated product price will be charged immediately), “immediate” (the full product price will be charged immediately), or “delayed” (the full product price will be charged with the first scheduled renewal). | +| `ReasonCode` | `*string` | Optional | (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to indicate why a subscription was canceled. | +| `ProductChangeDelayed` | `*bool` | Optional | (Optional, used only for Delayed Product Change When set to true, indicates that a changed value for product_handle should schedule the product change to the next subscription renewal. | +| `OfferId` | [`*models.CreateSubscriptionOfferId`](../../doc/models/containers/create-subscription-offer-id.md) | Optional | This is a container for one-of cases. | +| `PrepaidConfiguration` | [`*models.UpsertPrepaidConfiguration`](../../doc/models/upsert-prepaid-configuration.md) | Optional | - | +| `PreviousBillingAt` | `*time.Time` | Optional | Providing a previous_billing_at that is in the past will set the current_period_starts_at when the subscription is created. It will also set activated_at if not explicitly passed during the subscription import. Can only be used if next_billing_at is also passed. Using this option will allow you to set the period start for the subscription so mid period component allocations have the correct prorated amount. | +| `ImportMrr` | `*bool` | Optional | Setting this attribute to true will cause the subscription's MRR to be added to your MRR analytics immediately. For this value to be honored, a next_billing_at must be present and set to a future date. This key/value will not be returned in the subscription response body. | +| `CanceledAt` | `*time.Time` | Optional | - | +| `ActivatedAt` | `*time.Time` | Optional | - | +| `AgreementAcceptance` | [`*models.AgreementAcceptance`](../../doc/models/agreement-acceptance.md) | Optional | Required when creating a subscription with Maxio Payments. | +| `AchAgreement` | [`*models.ACHAgreement`](../../doc/models/ach-agreement.md) | Optional | (Optional) If passed, the proof of the authorized ACH agreement terms will be persisted. | +| `DunningCommunicationDelayEnabled` | `models.Optional[bool]` | Optional | Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute.
**Default**: `false` | +| `DunningCommunicationDelayTimeZone` | `models.Optional[string]` | Optional | Time zone for the Dunning Communication Delay feature. | +| `SkipBillingManifestTaxes` | `*bool` | Optional | Valid only for the Subscription Preview endpoint. When set to `true` it skips calculating taxes for the current and next billing manifests.
**Default**: `false` | + +## Example (as JSON) + +```json +{ + "payment_collection_method": "automatic", + "metafields": { + "custom_field_name_1": "custom_field_value_1", + "custom_field_name_2": "custom_field_value_2" + }, + "dunning_communication_delay_enabled": false, + "dunning_communication_delay_time_zone": "\"Eastern Time (US & Canada)\"", + "skip_billing_manifest_taxes": false, + "product_handle": "product_handle6", + "product_id": 212, + "product_price_point_handle": "product_price_point_handle0", + "product_price_point_id": 136, + "custom_price": { + "name": "name4", + "handle": "handle0", + "price_in_cents": "String3", + "interval": "String3", + "interval_unit": "day", + "trial_price_in_cents": "String3", + "trial_interval": "String5", + "trial_interval_unit": "day" + } +} +``` + diff --git a/doc/models/create-usage-request.md b/doc/models/create-usage-request.md index a2101543..97930a87 100644 --- a/doc/models/create-usage-request.md +++ b/doc/models/create-usage-request.md @@ -1,28 +1,28 @@ - -# Create Usage Request - -## Structure - -`CreateUsageRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Usage` | [`models.CreateUsage`](../../doc/models/create-usage.md) | Required | - | - -## Example (as JSON) - -```json -{ - "usage": { - "quantity": 162.34, - "price_point_id": "price_point_id0", - "memo": "memo2", - "billing_schedule": { - "initial_billing_at": "2016-03-13T12:52:32.123Z" - } - } -} -``` - + +# Create Usage Request + +## Structure + +`CreateUsageRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Usage` | [`models.CreateUsage`](../../doc/models/create-usage.md) | Required | - | + +## Example (as JSON) + +```json +{ + "usage": { + "quantity": 162.34, + "price_point_id": "price_point_id0", + "memo": "memo2", + "billing_schedule": { + "initial_billing_at": "2016-03-13T12:52:32.123Z" + } + } +} +``` + diff --git a/doc/models/create-usage.md b/doc/models/create-usage.md index c4602724..9ec044f9 100644 --- a/doc/models/create-usage.md +++ b/doc/models/create-usage.md @@ -1,29 +1,29 @@ - -# Create Usage - -## Structure - -`CreateUsage` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Quantity` | `*float64` | Optional | integer by default or decimal number if fractional quantities are enabled for the component | -| `PricePointId` | `*string` | Optional | - | -| `Memo` | `*string` | Optional | - | -| `BillingSchedule` | [`*models.BillingSchedule`](../../doc/models/billing-schedule.md) | Optional | This attribute is particularly useful when you need to align billing events for different components on distinct schedules within a subscription. Please note this only works for site with Multifrequency enabled | - -## Example (as JSON) - -```json -{ - "quantity": 23.44, - "price_point_id": "price_point_id0", - "memo": "memo2", - "billing_schedule": { - "initial_billing_at": "2016-03-13T12:52:32.123Z" - } -} -``` - + +# Create Usage + +## Structure + +`CreateUsage` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Quantity` | `*float64` | Optional | integer by default or decimal number if fractional quantities are enabled for the component | +| `PricePointId` | `*string` | Optional | - | +| `Memo` | `*string` | Optional | - | +| `BillingSchedule` | [`*models.BillingSchedule`](../../doc/models/billing-schedule.md) | Optional | This attribute is particularly useful when you need to align billing events for different components on distinct schedules within a subscription. Please note this only works for site with Multifrequency enabled | + +## Example (as JSON) + +```json +{ + "quantity": 23.44, + "price_point_id": "price_point_id0", + "memo": "memo2", + "billing_schedule": { + "initial_billing_at": "2016-03-13T12:52:32.123Z" + } +} +``` + diff --git a/doc/models/created-prepayment.md b/doc/models/created-prepayment.md index 3ab4a1ea..ec20a0e4 100644 --- a/doc/models/created-prepayment.md +++ b/doc/models/created-prepayment.md @@ -1,31 +1,31 @@ - -# Created Prepayment - -## Structure - -`CreatedPrepayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `SubscriptionId` | `*int` | Optional | - | -| `AmountInCents` | `*int64` | Optional | - | -| `Memo` | `*string` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `StartingBalanceInCents` | `*int64` | Optional | - | -| `EndingBalanceInCents` | `*int64` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 110, - "subscription_id": 220, - "amount_in_cents": 196, - "memo": "memo6", - "created_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Created Prepayment + +## Structure + +`CreatedPrepayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int64` | Optional | **Constraints**: `>= 1` | +| `SubscriptionId` | `*int` | Optional | **Constraints**: `>= 1` | +| `AmountInCents` | `*int64` | Optional | **Constraints**: `>= 0.01` | +| `Memo` | `*string` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `StartingBalanceInCents` | `*int64` | Optional | **Constraints**: `>= 0` | +| `EndingBalanceInCents` | `*int64` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 110, + "subscription_id": 220, + "amount_in_cents": 196, + "memo": "memo6", + "created_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/credit-account-balance-changed.md b/doc/models/credit-account-balance-changed.md new file mode 100644 index 00000000..ac90f38e --- /dev/null +++ b/doc/models/credit-account-balance-changed.md @@ -0,0 +1,29 @@ + +# Credit Account Balance Changed + +## Structure + +`CreditAccountBalanceChanged` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Reason` | `string` | Required | - | +| `ServiceCreditAccountBalanceInCents` | `int64` | Required | - | +| `ServiceCreditBalanceChangeInCents` | `int64` | Required | - | +| `CurrencyCode` | `string` | Required | - | +| `AtTime` | `time.Time` | Required | - | + +## Example (as JSON) + +```json +{ + "reason": "reason8", + "service_credit_account_balance_in_cents": 10, + "service_credit_balance_change_in_cents": 116, + "currency_code": "currency_code8", + "at_time": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/credit-card-attributes.md b/doc/models/credit-card-attributes.md index c06a2236..16ab33e5 100644 --- a/doc/models/credit-card-attributes.md +++ b/doc/models/credit-card-attributes.md @@ -1,25 +1,25 @@ - -# Credit Card Attributes - -## Structure - -`CreditCardAttributes` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `FullNumber` | `*string` | Optional | - | -| `ExpirationMonth` | `*string` | Optional | - | -| `ExpirationYear` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "full_number": "full_number0", - "expiration_month": "expiration_month6", - "expiration_year": "expiration_year0" -} -``` - + +# Credit Card Attributes + +## Structure + +`CreditCardAttributes` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FullNumber` | `*string` | Optional | - | +| `ExpirationMonth` | `*string` | Optional | - | +| `ExpirationYear` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "full_number": "full_number0", + "expiration_month": "expiration_month6", + "expiration_year": "expiration_year0" +} +``` + diff --git a/doc/models/credit-card-payment-profile.md b/doc/models/credit-card-payment-profile.md index 2edcd9ad..132825eb 100644 --- a/doc/models/credit-card-payment-profile.md +++ b/doc/models/credit-card-payment-profile.md @@ -1,61 +1,61 @@ - -# Credit Card Payment Profile - -## Structure - -`CreditCardPaymentProfile` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | The Chargify-assigned ID of the stored card. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer. | -| `FirstName` | `*string` | Optional | The first name of the card holder. | -| `LastName` | `*string` | Optional | The last name of the card holder. | -| `MaskedCardNumber` | `string` | Required | A string representation of the credit card number with all but the last 4 digits masked with X’s (i.e. ‘XXXX-XXXX-XXXX-1234’). | -| `CardType` | [`*models.CardType`](../../doc/models/card-type.md) | Optional | The type of card used. | -| `ExpirationMonth` | `*int` | Optional | An integer representing the expiration month of the card(1 – 12). | -| `ExpirationYear` | `*int` | Optional | An integer representing the 4-digit expiration year of the card(i.e. ‘2012’). | -| `CustomerId` | `*int` | Optional | The Chargify-assigned id for the customer record to which the card belongs. | -| `CurrentVault` | [`*models.CurrentVault`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | -| `VaultToken` | `Optional[string]` | Optional | The “token” provided by your vault storage for an already stored payment profile. | -| `BillingAddress` | `Optional[string]` | Optional | The current billing street address for the card. | -| `BillingCity` | `Optional[string]` | Optional | The current billing address city for the card. | -| `BillingState` | `Optional[string]` | Optional | The current billing address state for the card. | -| `BillingZip` | `Optional[string]` | Optional | The current billing address zip code for the card. | -| `BillingCountry` | `Optional[string]` | Optional | The current billing address country for the card. | -| `CustomerVaultToken` | `Optional[string]` | Optional | (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. | -| `BillingAddress2` | `Optional[string]` | Optional | The current billing street address, second line, for the card. | -| `PaymentType` | [`*models.PaymentType`](../../doc/models/payment-type.md) | Optional | - | -| `Disabled` | `*bool` | Optional | - | -| `ChargifyToken` | `*string` | Optional | Token received after sending billing information using chargify.js. This token will only be received if passed as a sole attribute of credit_card_attributes (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) | -| `SiteGatewaySettingId` | `Optional[int]` | Optional | - | -| `GatewayHandle` | `Optional[string]` | Optional | An identifier of connected gateway. | - -## Example (as JSON) - -```json -{ - "id": 10088716, - "first_name": "Test", - "last_name": "Subscription", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2022, - "customer_id": 14543792, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "123 Montana Way", - "billing_city": "Billings", - "billing_state": "MT", - "billing_zip": "59101", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": "", - "payment_type": "credit_card", - "site_gateway_setting_id": 1, - "gateway_handle": null -} -``` - + +# Credit Card Payment Profile + +## Structure + +`CreditCardPaymentProfile` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | The Chargify-assigned ID of the stored card. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer. | +| `FirstName` | `*string` | Optional | The first name of the card holder. | +| `LastName` | `*string` | Optional | The last name of the card holder. | +| `MaskedCardNumber` | `string` | Required | A string representation of the credit card number with all but the last 4 digits masked with X’s (i.e. ‘XXXX-XXXX-XXXX-1234’). | +| `CardType` | [`*models.CardType`](../../doc/models/card-type.md) | Optional | The type of card used. | +| `ExpirationMonth` | `*int` | Optional | An integer representing the expiration month of the card(1 – 12). | +| `ExpirationYear` | `*int` | Optional | An integer representing the 4-digit expiration year of the card(i.e. ‘2012’). | +| `CustomerId` | `*int` | Optional | The Chargify-assigned id for the customer record to which the card belongs. | +| `CurrentVault` | [`*models.CurrentVault`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | +| `VaultToken` | `models.Optional[string]` | Optional | The “token” provided by your vault storage for an already stored payment profile. | +| `BillingAddress` | `models.Optional[string]` | Optional | The current billing street address for the card. | +| `BillingCity` | `models.Optional[string]` | Optional | The current billing address city for the card. | +| `BillingState` | `models.Optional[string]` | Optional | The current billing address state for the card. | +| `BillingZip` | `models.Optional[string]` | Optional | The current billing address zip code for the card. | +| `BillingCountry` | `models.Optional[string]` | Optional | The current billing address country for the card. | +| `CustomerVaultToken` | `models.Optional[string]` | Optional | (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. | +| `BillingAddress2` | `models.Optional[string]` | Optional | The current billing street address, second line, for the card. | +| `PaymentType` | [`*models.PaymentType`](../../doc/models/payment-type.md) | Optional | - | +| `Disabled` | `*bool` | Optional | - | +| `ChargifyToken` | `*string` | Optional | Token received after sending billing information using chargify.js. This token will only be received if passed as a sole attribute of credit_card_attributes (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) | +| `SiteGatewaySettingId` | `models.Optional[int]` | Optional | - | +| `GatewayHandle` | `models.Optional[string]` | Optional | An identifier of connected gateway. | + +## Example (as JSON) + +```json +{ + "id": 10088716, + "first_name": "Test", + "last_name": "Subscription", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2022, + "customer_id": 14543792, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": "123 Montana Way", + "billing_city": "Billings", + "billing_state": "MT", + "billing_zip": "59101", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": "", + "payment_type": "credit_card", + "site_gateway_setting_id": 1, + "gateway_handle": null +} +``` + diff --git a/doc/models/credit-note-1.md b/doc/models/credit-note-1.md index e2c86dc1..707c73dc 100644 --- a/doc/models/credit-note-1.md +++ b/doc/models/credit-note-1.md @@ -1,51 +1,51 @@ - -# Credit Note 1 - -## Structure - -`CreditNote1` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. | -| `SiteId` | `*int` | Optional | ID of the site to which the credit note belongs. | -| `CustomerId` | `*int` | Optional | ID of the customer to which the credit note belongs. | -| `SubscriptionId` | `*int` | Optional | ID of the subscription that generated the credit note. | -| `Number` | `*string` | Optional | A unique, identifying string that appears on the credit note and in places it is referenced.

While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. | -| `SequenceNumber` | `*int` | Optional | A monotonically increasing number assigned to credit notes as they are created. This number is unique within a site and can be used to sort and order credit notes. | -| `IssueDate` | `*time.Time` | Optional | Date the credit note was issued to the customer. This is the date that the credit was made available for application, and may come before it is fully applied.

The format is `"YYYY-MM-DD"`. | -| `AppliedDate` | `*time.Time` | Optional | Credit notes are applied to invoices to offset invoiced amounts - they reduce the amount due. This field is the date the credit note became fully applied to invoices.

If the credit note has been partially applied, this field will not have a value until it has been fully applied.

The format is `"YYYY-MM-DD"`. | -| `Status` | [`*models.CreditNoteStatus`](../../doc/models/credit-note-status.md) | Optional | Current status of the credit note. | -| `Currency` | `*string` | Optional | The ISO 4217 currency code (3 character string) representing the currency of the credit note amount fields. | -| `Memo` | `*string` | Optional | The memo printed on credit note, which is a description of the reason for the credit. | -| `Seller` | [`*models.Seller`](../../doc/models/seller.md) | Optional | - | -| `Customer` | [`*models.Customer1`](../../doc/models/customer-1.md) | Optional | - | -| `BillingAddress` | [`*models.BillingAddress`](../../doc/models/billing-address.md) | Optional | - | -| `ShippingAddress` | [`*models.ShippingAddress`](../../doc/models/shipping-address.md) | Optional | - | -| `SubtotalAmount` | `*string` | Optional | Subtotal of the credit note, which is the sum of all line items before discounts or taxes. Note that this is a positive amount representing the credit back to the customer. | -| `DiscountAmount` | `*string` | Optional | Total discount applied to the credit note. Note that this is a positive amount representing the discount amount being credited back to the customer (i.e. a credit on an earlier discount). For example, if the original purchase was $1.00 and the original discount was $0.10, a credit of $0.50 of the original purchase (half) would have a discount credit of $0.05 (also half). | -| `TaxAmount` | `*string` | Optional | Total tax of the credit note. Note that this is a positive amount representing a previously taxex amount being credited back to the customer (i.e. a credit of an earlier tax). For example, if the original purchase was $1.00 and the original tax was $0.10, a credit of $0.50 of the original purchase (half) would also have a tax credit of $0.05 (also half). | -| `TotalAmount` | `*string` | Optional | The credit note total, which is `subtotal_amount - discount_amount + tax_amount`.' | -| `AppliedAmount` | `*string` | Optional | The amount of the credit note that has already been applied to invoices. | -| `RemainingAmount` | `*string` | Optional | The amount of the credit note remaining to be applied to invoices, which is `total_amount - applied_amount`. | -| `LineItems` | [`[]models.CreditNoteLineItem`](../../doc/models/credit-note-line-item.md) | Optional | Line items on the credit note. | -| `Discounts` | [`[]models.InvoiceDiscount`](../../doc/models/invoice-discount.md) | Optional | - | -| `Taxes` | [`[]models.InvoiceTax`](../../doc/models/invoice-tax.md) | Optional | - | -| `Applications` | [`[]models.CreditNoteApplication`](../../doc/models/credit-note-application.md) | Optional | - | -| `Refunds` | [`[]models.InvoiceRefund`](../../doc/models/invoice-refund.md) | Optional | - | -| `OriginInvoices` | [`[]models.OriginInvoice`](../../doc/models/origin-invoice.md) | Optional | An array of origin invoices for the credit note. Learn more about [Origin Invoice from our docs](https://chargify.zendesk.com/hc/en-us/articles/4407753036699#origin-invoices) | - -## Example (as JSON) - -```json -{ - "uid": "uid8", - "site_id": 120, - "customer_id": 232, - "subscription_id": 48, - "number": "number6" -} -``` - + +# Credit Note 1 + +## Structure + +`CreditNote1` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. | +| `SiteId` | `*int` | Optional | ID of the site to which the credit note belongs. | +| `CustomerId` | `*int` | Optional | ID of the customer to which the credit note belongs. | +| `SubscriptionId` | `*int` | Optional | ID of the subscription that generated the credit note. | +| `Number` | `*string` | Optional | A unique, identifying string that appears on the credit note and in places it is referenced.

While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. | +| `SequenceNumber` | `*int` | Optional | A monotonically increasing number assigned to credit notes as they are created. This number is unique within a site and can be used to sort and order credit notes. | +| `IssueDate` | `*time.Time` | Optional | Date the credit note was issued to the customer. This is the date that the credit was made available for application, and may come before it is fully applied.

The format is `"YYYY-MM-DD"`. | +| `AppliedDate` | `*time.Time` | Optional | Credit notes are applied to invoices to offset invoiced amounts - they reduce the amount due. This field is the date the credit note became fully applied to invoices.

If the credit note has been partially applied, this field will not have a value until it has been fully applied.

The format is `"YYYY-MM-DD"`. | +| `Status` | [`*models.CreditNoteStatus`](../../doc/models/credit-note-status.md) | Optional | Current status of the credit note. | +| `Currency` | `*string` | Optional | The ISO 4217 currency code (3 character string) representing the currency of the credit note amount fields. | +| `Memo` | `*string` | Optional | The memo printed on credit note, which is a description of the reason for the credit. | +| `Seller` | [`*models.Seller`](../../doc/models/seller.md) | Optional | - | +| `Customer` | [`*models.Customer1`](../../doc/models/customer-1.md) | Optional | - | +| `BillingAddress` | [`*models.BillingAddress`](../../doc/models/billing-address.md) | Optional | - | +| `ShippingAddress` | [`*models.ShippingAddress`](../../doc/models/shipping-address.md) | Optional | - | +| `SubtotalAmount` | `*string` | Optional | Subtotal of the credit note, which is the sum of all line items before discounts or taxes. Note that this is a positive amount representing the credit back to the customer. | +| `DiscountAmount` | `*string` | Optional | Total discount applied to the credit note. Note that this is a positive amount representing the discount amount being credited back to the customer (i.e. a credit on an earlier discount). For example, if the original purchase was $1.00 and the original discount was $0.10, a credit of $0.50 of the original purchase (half) would have a discount credit of $0.05 (also half). | +| `TaxAmount` | `*string` | Optional | Total tax of the credit note. Note that this is a positive amount representing a previously taxex amount being credited back to the customer (i.e. a credit of an earlier tax). For example, if the original purchase was $1.00 and the original tax was $0.10, a credit of $0.50 of the original purchase (half) would also have a tax credit of $0.05 (also half). | +| `TotalAmount` | `*string` | Optional | The credit note total, which is `subtotal_amount - discount_amount + tax_amount`.' | +| `AppliedAmount` | `*string` | Optional | The amount of the credit note that has already been applied to invoices. | +| `RemainingAmount` | `*string` | Optional | The amount of the credit note remaining to be applied to invoices, which is `total_amount - applied_amount`. | +| `LineItems` | [`[]models.CreditNoteLineItem`](../../doc/models/credit-note-line-item.md) | Optional | Line items on the credit note. | +| `Discounts` | [`[]models.InvoiceDiscount`](../../doc/models/invoice-discount.md) | Optional | - | +| `Taxes` | [`[]models.InvoiceTax`](../../doc/models/invoice-tax.md) | Optional | - | +| `Applications` | [`[]models.CreditNoteApplication`](../../doc/models/credit-note-application.md) | Optional | - | +| `Refunds` | [`[]models.InvoiceRefund`](../../doc/models/invoice-refund.md) | Optional | - | +| `OriginInvoices` | [`[]models.OriginInvoice`](../../doc/models/origin-invoice.md) | Optional | An array of origin invoices for the credit note. Learn more about [Origin Invoice from our docs](https://chargify.zendesk.com/hc/en-us/articles/4407753036699#origin-invoices) | + +## Example (as JSON) + +```json +{ + "uid": "uid8", + "site_id": 120, + "customer_id": 232, + "subscription_id": 48, + "number": "number6" +} +``` + diff --git a/doc/models/credit-note-application.md b/doc/models/credit-note-application.md index 593d52d1..161f4629 100644 --- a/doc/models/credit-note-application.md +++ b/doc/models/credit-note-application.md @@ -1,29 +1,29 @@ - -# Credit Note Application - -## Structure - -`CreditNoteApplication` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `TransactionTime` | `*time.Time` | Optional | - | -| `InvoiceUid` | `*string` | Optional | - | -| `Memo` | `*string` | Optional | - | -| `AppliedAmount` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid0", - "transaction_time": "2016-03-13T12:52:32.123Z", - "invoice_uid": "invoice_uid0", - "memo": "memo4", - "applied_amount": "applied_amount8" -} -``` - + +# Credit Note Application + +## Structure + +`CreditNoteApplication` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `TransactionTime` | `*time.Time` | Optional | - | +| `InvoiceUid` | `*string` | Optional | - | +| `Memo` | `*string` | Optional | - | +| `AppliedAmount` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid0", + "transaction_time": "2016-03-13T12:52:32.123Z", + "invoice_uid": "invoice_uid0", + "memo": "memo4", + "applied_amount": "applied_amount8" +} +``` + diff --git a/doc/models/credit-note-line-item.md b/doc/models/credit-note-line-item.md index 1d7e7da9..28c1ce10 100644 --- a/doc/models/credit-note-line-item.md +++ b/doc/models/credit-note-line-item.md @@ -1,42 +1,42 @@ - -# Credit Note Line Item - -## Structure - -`CreditNoteLineItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | Unique identifier for the line item. Useful when cross-referencing the line against individual discounts in the `discounts` or `taxes` lists. | -| `Title` | `*string` | Optional | A short descriptor for the credit given by this line. | -| `Description` | `*string` | Optional | Detailed description for the credit given by this line. May include proration details in plain text.

Note: this string may contain line breaks that are hints for the best display format on the credit note. | -| `Quantity` | `*string` | Optional | The quantity or count of units credited by the line item.

This is a decimal number represented as a string. (See "About Decimal Numbers".) | -| `UnitPrice` | `*string` | Optional | The price per unit for the line item.

When tiered pricing was used (i.e. not every unit was actually priced at the same price) this will be the blended average cost per unit and the `tiered_unit_price` field will be set to `true`. | -| `SubtotalAmount` | `*string` | Optional | The line subtotal, generally calculated as `quantity * unit_price`. This is the canonical amount of record for the line - when rounding differences are in play, `subtotal_amount` takes precedence over the value derived from `quantity * unit_price` (which may not have the proper precision to exactly equal this amount). | -| `DiscountAmount` | `*string` | Optional | The approximate discount of just this line.

The value is approximated in cases where rounding errors make it difficult to apportion exactly a total discount among many lines. Several lines may have been summed prior to applying the discount to arrive at `discount_amount` for the invoice - backing that out to the discount on a single line may introduce rounding or precision errors. | -| `TaxAmount` | `*string` | Optional | The approximate tax of just this line.

The value is approximated in cases where rounding errors make it difficult to apportion exactly a total tax among many lines. Several lines may have been summed prior to applying the tax rate to arrive at `tax_amount` for the invoice - backing that out to the tax on a single line may introduce rounding or precision errors. | -| `TotalAmount` | `*string` | Optional | The non-canonical total amount for the line.

`subtotal_amount` is the canonical amount for a line. The invoice `total_amount` is derived from the sum of the line `subtotal_amount`s and discounts or taxes applied thereafter. Therefore, due to rounding or precision errors, the sum of line `total_amount`s may not equal the invoice `total_amount`. | -| `TieredUnitPrice` | `*bool` | Optional | When `true`, indicates that the actual pricing scheme for the line was tiered, so the `unit_price` shown is the blended average for all units. | -| `PeriodRangeStart` | `*time.Time` | Optional | Start date for the period credited by this line. The format is `"YYYY-MM-DD"`. | -| `PeriodRangeEnd` | `*time.Time` | Optional | End date for the period credited by this line. The format is `"YYYY-MM-DD"`. | -| `ProductId` | `*int` | Optional | The ID of the product being credited.

This may be set even for component credits, so true product-only (non-component) credits will also have a nil `component_id`. | -| `ProductVersion` | `*int` | Optional | The version of the product being credited. | -| `ComponentId` | `Optional[int]` | Optional | The ID of the component being credited. Will be `nil` for non-component credits. | -| `PricePointId` | `Optional[int]` | Optional | The price point ID of the component being credited. Will be `nil` for non-component credits. | -| `BillingScheduleItemId` | `Optional[int]` | Optional | - | -| `CustomItem` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid4", - "title": "title0", - "description": "description6", - "quantity": "quantity0", - "unit_price": "unit_price2" -} -``` - + +# Credit Note Line Item + +## Structure + +`CreditNoteLineItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | Unique identifier for the line item. Useful when cross-referencing the line against individual discounts in the `discounts` or `taxes` lists. | +| `Title` | `*string` | Optional | A short descriptor for the credit given by this line. | +| `Description` | `*string` | Optional | Detailed description for the credit given by this line. May include proration details in plain text.

Note: this string may contain line breaks that are hints for the best display format on the credit note. | +| `Quantity` | `*string` | Optional | The quantity or count of units credited by the line item.

This is a decimal number represented as a string. (See "About Decimal Numbers".) | +| `UnitPrice` | `*string` | Optional | The price per unit for the line item.

When tiered pricing was used (i.e. not every unit was actually priced at the same price) this will be the blended average cost per unit and the `tiered_unit_price` field will be set to `true`. | +| `SubtotalAmount` | `*string` | Optional | The line subtotal, generally calculated as `quantity * unit_price`. This is the canonical amount of record for the line - when rounding differences are in play, `subtotal_amount` takes precedence over the value derived from `quantity * unit_price` (which may not have the proper precision to exactly equal this amount). | +| `DiscountAmount` | `*string` | Optional | The approximate discount of just this line.

The value is approximated in cases where rounding errors make it difficult to apportion exactly a total discount among many lines. Several lines may have been summed prior to applying the discount to arrive at `discount_amount` for the invoice - backing that out to the discount on a single line may introduce rounding or precision errors. | +| `TaxAmount` | `*string` | Optional | The approximate tax of just this line.

The value is approximated in cases where rounding errors make it difficult to apportion exactly a total tax among many lines. Several lines may have been summed prior to applying the tax rate to arrive at `tax_amount` for the invoice - backing that out to the tax on a single line may introduce rounding or precision errors. | +| `TotalAmount` | `*string` | Optional | The non-canonical total amount for the line.

`subtotal_amount` is the canonical amount for a line. The invoice `total_amount` is derived from the sum of the line `subtotal_amount`s and discounts or taxes applied thereafter. Therefore, due to rounding or precision errors, the sum of line `total_amount`s may not equal the invoice `total_amount`. | +| `TieredUnitPrice` | `*bool` | Optional | When `true`, indicates that the actual pricing scheme for the line was tiered, so the `unit_price` shown is the blended average for all units. | +| `PeriodRangeStart` | `*time.Time` | Optional | Start date for the period credited by this line. The format is `"YYYY-MM-DD"`. | +| `PeriodRangeEnd` | `*time.Time` | Optional | End date for the period credited by this line. The format is `"YYYY-MM-DD"`. | +| `ProductId` | `*int` | Optional | The ID of the product being credited.

This may be set even for component credits, so true product-only (non-component) credits will also have a nil `component_id`. | +| `ProductVersion` | `*int` | Optional | The version of the product being credited. | +| `ComponentId` | `models.Optional[int]` | Optional | The ID of the component being credited. Will be `nil` for non-component credits. | +| `PricePointId` | `models.Optional[int]` | Optional | The price point ID of the component being credited. Will be `nil` for non-component credits. | +| `BillingScheduleItemId` | `models.Optional[int]` | Optional | - | +| `CustomItem` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid4", + "title": "title0", + "description": "description6", + "quantity": "quantity0", + "unit_price": "unit_price2" +} +``` + diff --git a/doc/models/credit-note-status.md b/doc/models/credit-note-status.md index 91494c0f..1b4271a3 100644 --- a/doc/models/credit-note-status.md +++ b/doc/models/credit-note-status.md @@ -1,16 +1,16 @@ - -# Credit Note Status - -Current status of the credit note. - -## Enumeration - -`CreditNoteStatus` - -## Fields - -| Name | -| --- | -| `OPEN` | -| `APPLIED` | - + +# Credit Note Status + +Current status of the credit note. + +## Enumeration + +`CreditNoteStatus` + +## Fields + +| Name | +| --- | +| `OPEN` | +| `APPLIED` | + diff --git a/doc/models/credit-note.md b/doc/models/credit-note.md index 2444b2ab..5adae5f8 100644 --- a/doc/models/credit-note.md +++ b/doc/models/credit-note.md @@ -1,51 +1,51 @@ - -# Credit Note - -## Structure - -`CreditNote` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. | -| `SiteId` | `*int` | Optional | ID of the site to which the credit note belongs. | -| `CustomerId` | `*int` | Optional | ID of the customer to which the credit note belongs. | -| `SubscriptionId` | `*int` | Optional | ID of the subscription that generated the credit note. | -| `Number` | `*string` | Optional | A unique, identifying string that appears on the credit note and in places it is referenced.

While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. | -| `SequenceNumber` | `*int` | Optional | A monotonically increasing number assigned to credit notes as they are created. This number is unique within a site and can be used to sort and order credit notes. | -| `IssueDate` | `*time.Time` | Optional | Date the credit note was issued to the customer. This is the date that the credit was made available for application, and may come before it is fully applied.

The format is `"YYYY-MM-DD"`. | -| `AppliedDate` | `*time.Time` | Optional | Credit notes are applied to invoices to offset invoiced amounts - they reduce the amount due. This field is the date the credit note became fully applied to invoices.

If the credit note has been partially applied, this field will not have a value until it has been fully applied.

The format is `"YYYY-MM-DD"`. | -| `Status` | [`*models.CreditNoteStatus`](../../doc/models/credit-note-status.md) | Optional | Current status of the credit note. | -| `Currency` | `*string` | Optional | The ISO 4217 currency code (3 character string) representing the currency of the credit note amount fields. | -| `Memo` | `*string` | Optional | The memo printed on credit note, which is a description of the reason for the credit. | -| `Seller` | [`*models.InvoiceSeller`](../../doc/models/invoice-seller.md) | Optional | Information about the seller (merchant) listed on the masthead of the credit note. | -| `Customer` | [`*models.InvoiceCustomer`](../../doc/models/invoice-customer.md) | Optional | Information about the customer who is owner or recipient the credited subscription. | -| `BillingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | The billing address of the credit subscription. | -| `ShippingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | The shipping address of the credited subscription. | -| `SubtotalAmount` | `*string` | Optional | Subtotal of the credit note, which is the sum of all line items before discounts or taxes. Note that this is a positive amount representing the credit back to the customer. | -| `DiscountAmount` | `*string` | Optional | Total discount applied to the credit note. Note that this is a positive amount representing the discount amount being credited back to the customer (i.e. a credit on an earlier discount). For example, if the original purchase was $1.00 and the original discount was $0.10, a credit of $0.50 of the original purchase (half) would have a discount credit of $0.05 (also half). | -| `TaxAmount` | `*string` | Optional | Total tax of the credit note. Note that this is a positive amount representing a previously taxex amount being credited back to the customer (i.e. a credit of an earlier tax). For example, if the original purchase was $1.00 and the original tax was $0.10, a credit of $0.50 of the original purchase (half) would also have a tax credit of $0.05 (also half). | -| `TotalAmount` | `*string` | Optional | The credit note total, which is `subtotal_amount - discount_amount + tax_amount`.' | -| `AppliedAmount` | `*string` | Optional | The amount of the credit note that has already been applied to invoices. | -| `RemainingAmount` | `*string` | Optional | The amount of the credit note remaining to be applied to invoices, which is `total_amount - applied_amount`. | -| `LineItems` | [`[]models.CreditNoteLineItem`](../../doc/models/credit-note-line-item.md) | Optional | Line items on the credit note. | -| `Discounts` | [`[]models.InvoiceDiscount`](../../doc/models/invoice-discount.md) | Optional | - | -| `Taxes` | [`[]models.InvoiceTax`](../../doc/models/invoice-tax.md) | Optional | - | -| `Applications` | [`[]models.CreditNoteApplication`](../../doc/models/credit-note-application.md) | Optional | - | -| `Refunds` | [`[]models.InvoiceRefund`](../../doc/models/invoice-refund.md) | Optional | - | -| `OriginInvoices` | [`[]models.OriginInvoice`](../../doc/models/origin-invoice.md) | Optional | An array of origin invoices for the credit note. Learn more about [Origin Invoice from our docs](https://chargify.zendesk.com/hc/en-us/articles/4407753036699#origin-invoices) | - -## Example (as JSON) - -```json -{ - "uid": "uid2", - "site_id": 218, - "customer_id": 74, - "subscription_id": 146, - "number": "number0" -} -``` - + +# Credit Note + +## Structure + +`CreditNote` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. | +| `SiteId` | `*int` | Optional | ID of the site to which the credit note belongs. | +| `CustomerId` | `*int` | Optional | ID of the customer to which the credit note belongs. | +| `SubscriptionId` | `*int` | Optional | ID of the subscription that generated the credit note. | +| `Number` | `*string` | Optional | A unique, identifying string that appears on the credit note and in places it is referenced.

While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. | +| `SequenceNumber` | `*int` | Optional | A monotonically increasing number assigned to credit notes as they are created. This number is unique within a site and can be used to sort and order credit notes. | +| `IssueDate` | `*time.Time` | Optional | Date the credit note was issued to the customer. This is the date that the credit was made available for application, and may come before it is fully applied.

The format is `"YYYY-MM-DD"`. | +| `AppliedDate` | `*time.Time` | Optional | Credit notes are applied to invoices to offset invoiced amounts - they reduce the amount due. This field is the date the credit note became fully applied to invoices.

If the credit note has been partially applied, this field will not have a value until it has been fully applied.

The format is `"YYYY-MM-DD"`. | +| `Status` | [`*models.CreditNoteStatus`](../../doc/models/credit-note-status.md) | Optional | Current status of the credit note. | +| `Currency` | `*string` | Optional | The ISO 4217 currency code (3 character string) representing the currency of the credit note amount fields. | +| `Memo` | `*string` | Optional | The memo printed on credit note, which is a description of the reason for the credit. | +| `Seller` | [`*models.InvoiceSeller`](../../doc/models/invoice-seller.md) | Optional | Information about the seller (merchant) listed on the masthead of the credit note. | +| `Customer` | [`*models.InvoiceCustomer`](../../doc/models/invoice-customer.md) | Optional | Information about the customer who is owner or recipient the credited subscription. | +| `BillingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | The billing address of the credit subscription. | +| `ShippingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | The shipping address of the credited subscription. | +| `SubtotalAmount` | `*string` | Optional | Subtotal of the credit note, which is the sum of all line items before discounts or taxes. Note that this is a positive amount representing the credit back to the customer. | +| `DiscountAmount` | `*string` | Optional | Total discount applied to the credit note. Note that this is a positive amount representing the discount amount being credited back to the customer (i.e. a credit on an earlier discount). For example, if the original purchase was $1.00 and the original discount was $0.10, a credit of $0.50 of the original purchase (half) would have a discount credit of $0.05 (also half). | +| `TaxAmount` | `*string` | Optional | Total tax of the credit note. Note that this is a positive amount representing a previously taxex amount being credited back to the customer (i.e. a credit of an earlier tax). For example, if the original purchase was $1.00 and the original tax was $0.10, a credit of $0.50 of the original purchase (half) would also have a tax credit of $0.05 (also half). | +| `TotalAmount` | `*string` | Optional | The credit note total, which is `subtotal_amount - discount_amount + tax_amount`.' | +| `AppliedAmount` | `*string` | Optional | The amount of the credit note that has already been applied to invoices. | +| `RemainingAmount` | `*string` | Optional | The amount of the credit note remaining to be applied to invoices, which is `total_amount - applied_amount`. | +| `LineItems` | [`[]models.CreditNoteLineItem`](../../doc/models/credit-note-line-item.md) | Optional | Line items on the credit note. | +| `Discounts` | [`[]models.InvoiceDiscount`](../../doc/models/invoice-discount.md) | Optional | - | +| `Taxes` | [`[]models.InvoiceTax`](../../doc/models/invoice-tax.md) | Optional | - | +| `Applications` | [`[]models.CreditNoteApplication`](../../doc/models/credit-note-application.md) | Optional | - | +| `Refunds` | [`[]models.InvoiceRefund`](../../doc/models/invoice-refund.md) | Optional | - | +| `OriginInvoices` | [`[]models.OriginInvoice`](../../doc/models/origin-invoice.md) | Optional | An array of origin invoices for the credit note. Learn more about [Origin Invoice from our docs](https://chargify.zendesk.com/hc/en-us/articles/4407753036699#origin-invoices) | + +## Example (as JSON) + +```json +{ + "uid": "uid2", + "site_id": 218, + "customer_id": 74, + "subscription_id": 146, + "number": "number0" +} +``` + diff --git a/doc/models/credit-scheme-request.md b/doc/models/credit-scheme-request.md index 657b19c4..1ec79363 100644 --- a/doc/models/credit-scheme-request.md +++ b/doc/models/credit-scheme-request.md @@ -1,21 +1,21 @@ - -# Credit Scheme Request - -## Structure - -`CreditSchemeRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CreditScheme` | [`models.CreditScheme`](../../doc/models/credit-scheme.md) | Required | - | - -## Example (as JSON) - -```json -{ - "credit_scheme": "credit" -} -``` - + +# Credit Scheme Request + +## Structure + +`CreditSchemeRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CreditScheme` | [`models.CreditScheme`](../../doc/models/credit-scheme.md) | Required | - | + +## Example (as JSON) + +```json +{ + "credit_scheme": "credit" +} +``` + diff --git a/doc/models/credit-scheme.md b/doc/models/credit-scheme.md index 7c0076b0..fdf3956d 100644 --- a/doc/models/credit-scheme.md +++ b/doc/models/credit-scheme.md @@ -1,15 +1,15 @@ - -# Credit Scheme - -## Enumeration - -`CreditScheme` - -## Fields - -| Name | -| --- | -| `NONE` | -| `CREDIT` | -| `REFUND` | - + +# Credit Scheme + +## Enumeration + +`CreditScheme` + +## Fields + +| Name | +| --- | +| `NONE` | +| `CREDIT` | +| `REFUND` | + diff --git a/doc/models/credit-type.md b/doc/models/credit-type.md index cdc18531..b92ca7b7 100644 --- a/doc/models/credit-type.md +++ b/doc/models/credit-type.md @@ -1,18 +1,18 @@ - -# Credit Type - + +# Credit Type + The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. -Available values: `full`, `prorated`, `none`. - -## Enumeration - -`CreditType` - -## Fields - -| Name | -| --- | -| `FULL` | -| `PRORATED` | -| `NONE` | - +Available values: `full`, `prorated`, `none`. + +## Enumeration + +`CreditType` + +## Fields + +| Name | +| --- | +| `FULL` | +| `PRORATED` | +| `NONE` | + diff --git a/doc/models/currency-price-role.md b/doc/models/currency-price-role.md index 8f089134..32d78475 100644 --- a/doc/models/currency-price-role.md +++ b/doc/models/currency-price-role.md @@ -1,17 +1,17 @@ - -# Currency Price Role - -Role for the price. - -## Enumeration - -`CurrencyPriceRole` - -## Fields - -| Name | -| --- | -| `BASELINE` | -| `TRIAL` | -| `INITIAL` | - + +# Currency Price Role + +Role for the price. + +## Enumeration + +`CurrencyPriceRole` + +## Fields + +| Name | +| --- | +| `BASELINE` | +| `TRIAL` | +| `INITIAL` | + diff --git a/doc/models/currency-price.md b/doc/models/currency-price.md index 99f0e5dc..ae33e5f2 100644 --- a/doc/models/currency-price.md +++ b/doc/models/currency-price.md @@ -1,30 +1,30 @@ - -# Currency Price - -## Structure - -`CurrencyPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Currency` | `*string` | Optional | - | -| `Price` | `*float64` | Optional | - | -| `FormattedPrice` | `*string` | Optional | - | -| `ProductPricePointId` | `*int` | Optional | - | -| `Role` | [`*models.CurrencyPriceRole`](../../doc/models/currency-price-role.md) | Optional | Role for the price. | - -## Example (as JSON) - -```json -{ - "id": 88, - "currency": "currency6", - "price": 41.36, - "formatted_price": "formatted_price4", - "product_price_point_id": 210 -} -``` - + +# Currency Price + +## Structure + +`CurrencyPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Currency` | `*string` | Optional | - | +| `Price` | `*float64` | Optional | - | +| `FormattedPrice` | `*string` | Optional | - | +| `ProductPricePointId` | `*int` | Optional | - | +| `Role` | [`*models.CurrencyPriceRole`](../../doc/models/currency-price-role.md) | Optional | Role for the price. | + +## Example (as JSON) + +```json +{ + "id": 88, + "currency": "currency6", + "price": 41.36, + "formatted_price": "formatted_price4", + "product_price_point_id": 210 +} +``` + diff --git a/doc/models/currency-prices-response.md b/doc/models/currency-prices-response.md index 1d0c5647..4cd95fb1 100644 --- a/doc/models/currency-prices-response.md +++ b/doc/models/currency-prices-response.md @@ -1,29 +1,29 @@ - -# Currency Prices Response - -## Structure - -`CurrencyPricesResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CurrencyPrices` | [`[]models.CurrencyPrice`](../../doc/models/currency-price.md) | Required | - | - -## Example (as JSON) - -```json -{ - "currency_prices": [ - { - "id": 50, - "currency": "currency8", - "price": 233.74, - "formatted_price": "formatted_price6", - "product_price_point_id": 172 - } - ] -} -``` - + +# Currency Prices Response + +## Structure + +`CurrencyPricesResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrencyPrices` | [`[]models.CurrencyPrice`](../../doc/models/currency-price.md) | Required | - | + +## Example (as JSON) + +```json +{ + "currency_prices": [ + { + "id": 50, + "currency": "currency8", + "price": 233.74, + "formatted_price": "formatted_price6", + "product_price_point_id": 172 + } + ] +} +``` + diff --git a/doc/models/current-vault.md b/doc/models/current-vault.md index 24c3b892..30a70aac 100644 --- a/doc/models/current-vault.md +++ b/doc/models/current-vault.md @@ -1,41 +1,41 @@ - -# Current Vault - -The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. - -## Enumeration - -`CurrentVault` - -## Fields - -| Name | -| --- | -| `ADYEN` | -| `AUTHORIZENET` | -| `AVALARA` | -| `BEANSTREAM` | -| `BLUESNAP` | -| `BOGUS` | -| `BRAINTREEBLUE` | -| `CHECKOUT` | -| `CYBERSOURCE` | -| `ELAVON` | -| `EWAY` | -| `EWAYRAPIDSTD` | -| `FIRSTDATA` | -| `FORTE` | -| `GOCARDLESS` | -| `LITLE` | -| `MAXIOPAYMENTS` | -| `MODUSLINK` | -| `MONERIS` | -| `NMI` | -| `ORBITAL` | -| `PAYMENTEXPRESS` | -| `PIN` | -| `SQUARE` | -| `STRIPECONNECT` | -| `TRUSTCOMMERCE` | -| `UNIPAAS` | - + +# Current Vault + +The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. + +## Enumeration + +`CurrentVault` + +## Fields + +| Name | +| --- | +| `ADYEN` | +| `AUTHORIZENET` | +| `AVALARA` | +| `BEANSTREAM` | +| `BLUESNAP` | +| `BOGUS` | +| `BRAINTREEBLUE` | +| `CHECKOUT` | +| `CYBERSOURCE` | +| `ELAVON` | +| `EWAY` | +| `EWAYRAPIDSTD` | +| `FIRSTDATA` | +| `FORTE` | +| `GOCARDLESS` | +| `LITLE` | +| `MAXIOPAYMENTS` | +| `MODUSLINK` | +| `MONERIS` | +| `NMI` | +| `ORBITAL` | +| `PAYMENTEXPRESS` | +| `PIN` | +| `SQUARE` | +| `STRIPECONNECT` | +| `TRUSTCOMMERCE` | +| `UNIPAAS` | + diff --git a/doc/models/custom-field-owner.md b/doc/models/custom-field-owner.md index 683dcc65..77c2f821 100644 --- a/doc/models/custom-field-owner.md +++ b/doc/models/custom-field-owner.md @@ -1,14 +1,14 @@ - -# Custom Field Owner - -## Enumeration - -`CustomFieldOwner` - -## Fields - -| Name | -| --- | -| `CUSTOMER` | -| `SUBSCRIPTION` | - + +# Custom Field Owner + +## Enumeration + +`CustomFieldOwner` + +## Fields + +| Name | +| --- | +| `CUSTOMER` | +| `SUBSCRIPTION` | + diff --git a/doc/models/custom-field-value-change.md b/doc/models/custom-field-value-change.md new file mode 100644 index 00000000..17a2acef --- /dev/null +++ b/doc/models/custom-field-value-change.md @@ -0,0 +1,33 @@ + +# Custom Field Value Change + +## Structure + +`CustomFieldValueChange` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `EventType` | `string` | Required | - | +| `MetafieldName` | `string` | Required | - | +| `MetafieldId` | `int` | Required | - | +| `OldValue` | `*string` | Required | - | +| `NewValue` | `*string` | Required | - | +| `ResourceType` | `string` | Required | - | +| `ResourceId` | `int` | Required | - | + +## Example (as JSON) + +```json +{ + "event_type": "event_type2", + "metafield_name": "metafield_name6", + "metafield_id": 78, + "old_value": "old_value2", + "new_value": "new_value8", + "resource_type": "resource_type2", + "resource_id": 74 +} +``` + diff --git a/doc/models/customer-1.md b/doc/models/customer-1.md index 2d34c066..a29a77dc 100644 --- a/doc/models/customer-1.md +++ b/doc/models/customer-1.md @@ -1,31 +1,31 @@ - -# Customer 1 - -## Structure - -`Customer1` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ChargifyId` | `Optional[int]` | Optional | - | -| `FirstName` | `*string` | Optional | - | -| `LastName` | `*string` | Optional | - | -| `Organization` | `Optional[string]` | Optional | - | -| `Email` | `*string` | Optional | - | -| `VatNumber` | `Optional[string]` | Optional | - | -| `Reference` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "chargify_id": 126, - "first_name": "first_name8", - "last_name": "last_name6", - "organization": "organization8", - "email": "email8" -} -``` - + +# Customer 1 + +## Structure + +`Customer1` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ChargifyId` | `models.Optional[int]` | Optional | - | +| `FirstName` | `*string` | Optional | - | +| `LastName` | `*string` | Optional | - | +| `Organization` | `models.Optional[string]` | Optional | - | +| `Email` | `*string` | Optional | - | +| `VatNumber` | `models.Optional[string]` | Optional | - | +| `Reference` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "chargify_id": 126, + "first_name": "first_name8", + "last_name": "last_name6", + "organization": "organization8", + "email": "email8" +} +``` + diff --git a/doc/models/customer-attributes.md b/doc/models/customer-attributes.md index eb15b9c8..1777a4ba 100644 --- a/doc/models/customer-attributes.md +++ b/doc/models/customer-attributes.md @@ -1,46 +1,46 @@ - -# Customer Attributes - -## Structure - -`CustomerAttributes` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `FirstName` | `*string` | Optional | The first name of the customer. Required when creating a customer via attributes. | -| `LastName` | `*string` | Optional | The last name of the customer. Required when creating a customer via attributes. | -| `Email` | `*string` | Optional | The email address of the customer. Required when creating a customer via attributes. | -| `CcEmails` | `*string` | Optional | A list of emails that should be cc’d on all customer communications. Optional. | -| `Organization` | `*string` | Optional | The organization/company of the customer. Optional. | -| `Reference` | `*string` | Optional | A customer “reference”, or unique identifier from your app, stored in Chargify. Can be used so that you may reference your customer’s within Chargify using the same unique value you use in your application. Optional. | -| `Address` | `*string` | Optional | (Optional) The customer’s shipping street address (i.e. “123 Main St.”). | -| `Address2` | `Optional[string]` | Optional | (Optional) Second line of the customer’s shipping address i.e. “Apt. 100” | -| `City` | `*string` | Optional | (Optional) The customer’s shipping address city (i.e. “Boston”). | -| `State` | `*string` | Optional | (Optional) The customer’s shipping address state (i.e. “MA”). This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. | -| `Zip` | `*string` | Optional | (Optional) The customer’s shipping address zip code (i.e. “12345”). | -| `Country` | `*string` | Optional | (Optional) The customer shipping address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). | -| `Phone` | `*string` | Optional | (Optional) The phone number of the customer. | -| `Verified` | `*bool` | Optional | - | -| `TaxExempt` | `*bool` | Optional | (Optional) The tax_exempt status of the customer. Acceptable values are true or 1 for true and false or 0 for false. | -| `VatNumber` | `*string` | Optional | (Optional) Supplying the VAT number allows EU customer’s to opt-out of the Value Added Tax assuming the merchant address and customer billing address are not within the same EU country. It’s important to omit the country code from the VAT number upon entry. Otherwise, taxes will be assessed upon the purchase. | -| `Metafields` | `map[string]string` | Optional | (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. | -| `ParentId` | `Optional[int]` | Optional | The parent ID in Chargify if applicable. Parent is another Customer object. | - -## Example (as JSON) - -```json -{ - "metafields": { - "custom_field_name_1": "custom_field_value_1", - "custom_field_name_2": "custom_field_value_2" - }, - "first_name": "first_name4", - "last_name": "last_name2", - "email": "email2", - "cc_emails": "cc_emails6", - "organization": "organization8" -} -``` - + +# Customer Attributes + +## Structure + +`CustomerAttributes` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FirstName` | `*string` | Optional | The first name of the customer. Required when creating a customer via attributes. | +| `LastName` | `*string` | Optional | The last name of the customer. Required when creating a customer via attributes. | +| `Email` | `*string` | Optional | The email address of the customer. Required when creating a customer via attributes. | +| `CcEmails` | `*string` | Optional | A list of emails that should be cc’d on all customer communications. Optional. | +| `Organization` | `*string` | Optional | The organization/company of the customer. Optional. | +| `Reference` | `*string` | Optional | A customer “reference”, or unique identifier from your app, stored in Chargify. Can be used so that you may reference your customer’s within Chargify using the same unique value you use in your application. Optional. | +| `Address` | `*string` | Optional | (Optional) The customer’s shipping street address (i.e. “123 Main St.”). | +| `Address2` | `models.Optional[string]` | Optional | (Optional) Second line of the customer’s shipping address i.e. “Apt. 100” | +| `City` | `*string` | Optional | (Optional) The customer’s shipping address city (i.e. “Boston”). | +| `State` | `*string` | Optional | (Optional) The customer’s shipping address state (i.e. “MA”). This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. | +| `Zip` | `*string` | Optional | (Optional) The customer’s shipping address zip code (i.e. “12345”). | +| `Country` | `*string` | Optional | (Optional) The customer shipping address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). | +| `Phone` | `*string` | Optional | (Optional) The phone number of the customer. | +| `Verified` | `*bool` | Optional | - | +| `TaxExempt` | `*bool` | Optional | (Optional) The tax_exempt status of the customer. Acceptable values are true or 1 for true and false or 0 for false. | +| `VatNumber` | `*string` | Optional | (Optional) Supplying the VAT number allows EU customer’s to opt-out of the Value Added Tax assuming the merchant address and customer billing address are not within the same EU country. It’s important to omit the country code from the VAT number upon entry. Otherwise, taxes will be assessed upon the purchase. | +| `Metafields` | `map[string]string` | Optional | (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. | +| `ParentId` | `models.Optional[int]` | Optional | The parent ID in Chargify if applicable. Parent is another Customer object. | + +## Example (as JSON) + +```json +{ + "metafields": { + "custom_field_name_1": "custom_field_value_1", + "custom_field_name_2": "custom_field_value_2" + }, + "first_name": "first_name4", + "last_name": "last_name2", + "email": "email2", + "cc_emails": "cc_emails6", + "organization": "organization8" +} +``` + diff --git a/doc/models/customer-change.md b/doc/models/customer-change.md index 8d9b4b81..ef2a3a0b 100644 --- a/doc/models/customer-change.md +++ b/doc/models/customer-change.md @@ -1,110 +1,96 @@ - -# Customer Change - -## Structure - -`CustomerChange` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Payer` | [`Optional[models.CustomerPayerChange]`](../../doc/models/customer-payer-change.md) | Optional | - | -| `ShippingAddress` | [`Optional[models.AddressChange]`](../../doc/models/address-change.md) | Optional | - | -| `BillingAddress` | [`Optional[models.AddressChange]`](../../doc/models/address-change.md) | Optional | - | -| `CustomFields` | [`Optional[models.CustomerCustomFieldsChange]`](../../doc/models/customer-custom-fields-change.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "payer": { - "before": { - "first_name": "first_name0", - "last_name": "last_name8", - "organization": "organization4", - "email": "email6" - }, - "after": { - "first_name": "first_name2", - "last_name": "last_name0", - "organization": "organization4", - "email": "email4" - } - }, - "shipping_address": { - "before": { - "street": "street0", - "line2": "line24", - "city": "city0", - "state": "state6", - "zip": "zip4" - }, - "after": { - "street": "street2", - "line2": "line26", - "city": "city8", - "state": "state2", - "zip": "zip4" - } - }, - "billing_address": { - "before": { - "street": "street0", - "line2": "line24", - "city": "city0", - "state": "state6", - "zip": "zip4" - }, - "after": { - "street": "street2", - "line2": "line26", - "city": "city8", - "state": "state2", - "zip": "zip4" - } - }, - "custom_fields": { - "before": [ - { - "owner_id": 26, - "owner_type": "Customer", - "name": "name0", - "value": "value2", - "metadatum_id": 26 - }, - { - "owner_id": 26, - "owner_type": "Customer", - "name": "name0", - "value": "value2", - "metadatum_id": 26 - } - ], - "after": [ - { - "owner_id": 130, - "owner_type": "Customer", - "name": "name2", - "value": "value4", - "metadatum_id": 130 - }, - { - "owner_id": 130, - "owner_type": "Customer", - "name": "name2", - "value": "value4", - "metadatum_id": 130 - }, - { - "owner_id": 130, - "owner_type": "Customer", - "name": "name2", - "value": "value4", - "metadatum_id": 130 - } - ] - } -} -``` - + +# Customer Change + +## Structure + +`CustomerChange` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Payer` | [`models.Optional[models.CustomerChangePayer]`](../../doc/models/containers/customer-change-payer.md) | Optional | This is a container for one-of cases. | +| `ShippingAddress` | [`models.Optional[models.CustomerChangeShippingAddress]`](../../doc/models/containers/customer-change-shipping-address.md) | Optional | This is a container for one-of cases. | +| `BillingAddress` | [`models.Optional[models.CustomerChangeBillingAddress]`](../../doc/models/containers/customer-change-billing-address.md) | Optional | This is a container for one-of cases. | +| `CustomFields` | [`models.Optional[models.CustomerChangeCustomFields]`](../../doc/models/containers/customer-change-custom-fields.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "payer": { + "before": { + "first_name": "first_name0", + "last_name": "last_name8", + "organization": "organization4", + "email": "email6" + }, + "after": { + "first_name": "first_name2", + "last_name": "last_name0", + "organization": "organization4", + "email": "email4" + } + }, + "shipping_address": { + "before": { + "street": "street0", + "line2": "line24", + "city": "city0", + "state": "state6", + "zip": "zip4" + }, + "after": { + "street": "street2", + "line2": "line26", + "city": "city8", + "state": "state2", + "zip": "zip4" + } + }, + "billing_address": { + "before": { + "street": "street0", + "line2": "line24", + "city": "city0", + "state": "state6", + "zip": "zip4" + }, + "after": { + "street": "street2", + "line2": "line26", + "city": "city8", + "state": "state2", + "zip": "zip4" + } + }, + "custom_fields": { + "before": [ + { + "owner_id": 26, + "owner_type": "Customer", + "name": "name0", + "value": "value2", + "metadatum_id": 26 + } + ], + "after": [ + { + "owner_id": 130, + "owner_type": "Customer", + "name": "name2", + "value": "value4", + "metadatum_id": 130 + }, + { + "owner_id": 130, + "owner_type": "Customer", + "name": "name2", + "value": "value4", + "metadatum_id": 130 + } + ] + } +} +``` + diff --git a/doc/models/customer-changes-preview-response.md b/doc/models/customer-changes-preview-response.md index 36cd56e8..33c8f622 100644 --- a/doc/models/customer-changes-preview-response.md +++ b/doc/models/customer-changes-preview-response.md @@ -1,109 +1,95 @@ - -# Customer Changes Preview Response - -## Structure - -`CustomerChangesPreviewResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Changes` | [`models.CustomerChange`](../../doc/models/customer-change.md) | Required | - | - -## Example (as JSON) - -```json -{ - "changes": { - "payer": { - "before": { - "first_name": "first_name0", - "last_name": "last_name8", - "organization": "organization4", - "email": "email6" - }, - "after": { - "first_name": "first_name2", - "last_name": "last_name0", - "organization": "organization4", - "email": "email4" - } - }, - "shipping_address": { - "before": { - "street": "street0", - "line2": "line24", - "city": "city0", - "state": "state6", - "zip": "zip4" - }, - "after": { - "street": "street2", - "line2": "line26", - "city": "city8", - "state": "state2", - "zip": "zip4" - } - }, - "billing_address": { - "before": { - "street": "street0", - "line2": "line24", - "city": "city0", - "state": "state6", - "zip": "zip4" - }, - "after": { - "street": "street2", - "line2": "line26", - "city": "city8", - "state": "state2", - "zip": "zip4" - } - }, - "custom_fields": { - "before": [ - { - "owner_id": 26, - "owner_type": "Customer", - "name": "name0", - "value": "value2", - "metadatum_id": 26 - }, - { - "owner_id": 26, - "owner_type": "Customer", - "name": "name0", - "value": "value2", - "metadatum_id": 26 - } - ], - "after": [ - { - "owner_id": 130, - "owner_type": "Customer", - "name": "name2", - "value": "value4", - "metadatum_id": 130 - }, - { - "owner_id": 130, - "owner_type": "Customer", - "name": "name2", - "value": "value4", - "metadatum_id": 130 - }, - { - "owner_id": 130, - "owner_type": "Customer", - "name": "name2", - "value": "value4", - "metadatum_id": 130 - } - ] - } - } -} -``` - + +# Customer Changes Preview Response + +## Structure + +`CustomerChangesPreviewResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Changes` | [`models.CustomerChange`](../../doc/models/customer-change.md) | Required | - | + +## Example (as JSON) + +```json +{ + "changes": { + "payer": { + "before": { + "first_name": "first_name0", + "last_name": "last_name8", + "organization": "organization4", + "email": "email6" + }, + "after": { + "first_name": "first_name2", + "last_name": "last_name0", + "organization": "organization4", + "email": "email4" + } + }, + "shipping_address": { + "before": { + "street": "street0", + "line2": "line24", + "city": "city0", + "state": "state6", + "zip": "zip4" + }, + "after": { + "street": "street2", + "line2": "line26", + "city": "city8", + "state": "state2", + "zip": "zip4" + } + }, + "billing_address": { + "before": { + "street": "street0", + "line2": "line24", + "city": "city0", + "state": "state6", + "zip": "zip4" + }, + "after": { + "street": "street2", + "line2": "line26", + "city": "city8", + "state": "state2", + "zip": "zip4" + } + }, + "custom_fields": { + "before": [ + { + "owner_id": 26, + "owner_type": "Customer", + "name": "name0", + "value": "value2", + "metadatum_id": 26 + } + ], + "after": [ + { + "owner_id": 130, + "owner_type": "Customer", + "name": "name2", + "value": "value4", + "metadatum_id": 130 + }, + { + "owner_id": 130, + "owner_type": "Customer", + "name": "name2", + "value": "value4", + "metadatum_id": 130 + } + ] + } + } +} +``` + diff --git a/doc/models/customer-custom-fields-change.md b/doc/models/customer-custom-fields-change.md index 9131ec4c..2d26ebca 100644 --- a/doc/models/customer-custom-fields-change.md +++ b/doc/models/customer-custom-fields-change.md @@ -1,39 +1,39 @@ - -# Customer Custom Fields Change - -## Structure - -`CustomerCustomFieldsChange` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Before` | [`[]models.InvoiceCustomField`](../../doc/models/invoice-custom-field.md) | Required | - | -| `After` | [`[]models.InvoiceCustomField`](../../doc/models/invoice-custom-field.md) | Required | - | - -## Example (as JSON) - -```json -{ - "before": [ - { - "owner_id": 26, - "owner_type": "Customer", - "name": "name0", - "value": "value2", - "metadatum_id": 26 - } - ], - "after": [ - { - "owner_id": 130, - "owner_type": "Customer", - "name": "name2", - "value": "value4", - "metadatum_id": 130 - } - ] -} -``` - + +# Customer Custom Fields Change + +## Structure + +`CustomerCustomFieldsChange` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Before` | [`[]models.InvoiceCustomField`](../../doc/models/invoice-custom-field.md) | Required | - | +| `After` | [`[]models.InvoiceCustomField`](../../doc/models/invoice-custom-field.md) | Required | - | + +## Example (as JSON) + +```json +{ + "before": [ + { + "owner_id": 26, + "owner_type": "Customer", + "name": "name0", + "value": "value2", + "metadatum_id": 26 + } + ], + "after": [ + { + "owner_id": 130, + "owner_type": "Customer", + "name": "name2", + "value": "value4", + "metadatum_id": 130 + } + ] +} +``` + diff --git a/doc/models/customer-error-response-exception.md b/doc/models/customer-error-response-exception.md index b63fd683..02109574 100644 --- a/doc/models/customer-error-response-exception.md +++ b/doc/models/customer-error-response-exception.md @@ -1,24 +1,23 @@ - -# Customer Error Response Exception - -## Structure - -`CustomerErrorResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | `*interface{}` | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Customer Error Response Exception + +## Structure + +`CustomerErrorResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`*models.CustomerErrorResponseErrors`](../../doc/models/containers/customer-error-response-errors.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "errors": { + "customer": "customer8" + } +} +``` + diff --git a/doc/models/customer-error.md b/doc/models/customer-error.md new file mode 100644 index 00000000..b88e3e10 --- /dev/null +++ b/doc/models/customer-error.md @@ -0,0 +1,21 @@ + +# Customer Error + +## Structure + +`CustomerError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Customer` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "customer": "customer8" +} +``` + diff --git a/doc/models/customer-payer-change.md b/doc/models/customer-payer-change.md index 4056efdd..f5133aec 100644 --- a/doc/models/customer-payer-change.md +++ b/doc/models/customer-payer-change.md @@ -1,33 +1,33 @@ - -# Customer Payer Change - -## Structure - -`CustomerPayerChange` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Before` | [`models.InvoicePayerChange`](../../doc/models/invoice-payer-change.md) | Required | - | -| `After` | [`models.InvoicePayerChange`](../../doc/models/invoice-payer-change.md) | Required | - | - -## Example (as JSON) - -```json -{ - "before": { - "first_name": "first_name0", - "last_name": "last_name8", - "organization": "organization4", - "email": "email6" - }, - "after": { - "first_name": "first_name2", - "last_name": "last_name0", - "organization": "organization4", - "email": "email4" - } -} -``` - + +# Customer Payer Change + +## Structure + +`CustomerPayerChange` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Before` | [`models.InvoicePayerChange`](../../doc/models/invoice-payer-change.md) | Required | - | +| `After` | [`models.InvoicePayerChange`](../../doc/models/invoice-payer-change.md) | Required | - | + +## Example (as JSON) + +```json +{ + "before": { + "first_name": "first_name0", + "last_name": "last_name8", + "organization": "organization4", + "email": "email6" + }, + "after": { + "first_name": "first_name2", + "last_name": "last_name0", + "organization": "organization4", + "email": "email4" + } +} +``` + diff --git a/doc/models/customer-response.md b/doc/models/customer-response.md index 3b96bc6b..36a39d59 100644 --- a/doc/models/customer-response.md +++ b/doc/models/customer-response.md @@ -1,27 +1,27 @@ - -# Customer Response - -## Structure - -`CustomerResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Customer` | [`models.Customer`](../../doc/models/customer.md) | Required | - | - -## Example (as JSON) - -```json -{ - "customer": { - "first_name": "first_name0", - "last_name": "last_name8", - "email": "email6", - "cc_emails": "cc_emails0", - "organization": "organization6" - } -} -``` - + +# Customer Response + +## Structure + +`CustomerResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Customer` | [`models.Customer`](../../doc/models/customer.md) | Required | - | + +## Example (as JSON) + +```json +{ + "customer": { + "first_name": "first_name0", + "last_name": "last_name8", + "email": "email6", + "cc_emails": "cc_emails0", + "organization": "organization6" + } +} +``` + diff --git a/doc/models/customer.md b/doc/models/customer.md index 6570b6eb..a19c9743 100644 --- a/doc/models/customer.md +++ b/doc/models/customer.md @@ -1,51 +1,51 @@ - -# Customer - -## Structure - -`Customer` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `FirstName` | `*string` | Optional | The first name of the customer | -| `LastName` | `*string` | Optional | The last name of the customer | -| `Email` | `*string` | Optional | The email address of the customer | -| `CcEmails` | `Optional[string]` | Optional | A comma-separated list of emails that should be cc’d on all customer communications (i.e. “joe@example.com, sue@example.com”) | -| `Organization` | `Optional[string]` | Optional | The organization of the customer | -| `Reference` | `Optional[string]` | Optional | The unique identifier used within your own application for this customer | -| `Id` | `*int` | Optional | The customer ID in Chargify | -| `CreatedAt` | `*time.Time` | Optional | The timestamp in which the customer object was created in Chargify | -| `UpdatedAt` | `*time.Time` | Optional | The timestamp in which the customer object was last edited | -| `Address` | `Optional[string]` | Optional | The customer’s shipping street address (i.e. “123 Main St.”) | -| `Address2` | `Optional[string]` | Optional | Second line of the customer’s shipping address i.e. “Apt. 100” | -| `City` | `Optional[string]` | Optional | The customer’s shipping address city (i.e. “Boston”) | -| `State` | `Optional[string]` | Optional | The customer’s shipping address state (i.e. “MA”) | -| `StateName` | `Optional[string]` | Optional | The customer's full name of state | -| `Zip` | `Optional[string]` | Optional | The customer’s shipping address zip code (i.e. “12345”) | -| `Country` | `Optional[string]` | Optional | The customer shipping address country | -| `CountryName` | `Optional[string]` | Optional | The customer's full name of country | -| `Phone` | `Optional[string]` | Optional | The phone number of the customer | -| `Verified` | `Optional[bool]` | Optional | Is the customer verified to use ACH as a payment method. Available only on Authorize.Net gateway | -| `PortalCustomerCreatedAt` | `Optional[time.Time]` | Optional | The timestamp of when the Billing Portal entry was created at for the customer | -| `PortalInviteLastSentAt` | `Optional[time.Time]` | Optional | The timestamp of when the Billing Portal invite was last sent at | -| `PortalInviteLastAcceptedAt` | `Optional[time.Time]` | Optional | The timestamp of when the Billing Portal invite was last accepted | -| `TaxExempt` | `*bool` | Optional | The tax exempt status for the customer. Acceptable values are true or 1 for true and false or 0 for false. | -| `VatNumber` | `Optional[string]` | Optional | The VAT business identification number for the customer. This number is used to determine VAT tax opt out rules. It is not validated when added or updated on a customer record. Instead, it is validated via VIES before calculating taxes. Only valid business identification numbers will allow for VAT opt out. | -| `ParentId` | `Optional[int]` | Optional | The parent ID in Chargify if applicable. Parent is another Customer object. | -| `Locale` | `Optional[string]` | Optional | The locale for the customer to identify language-region | -| `DefaultSubscriptionGroupUid` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "first_name": "first_name8", - "last_name": "last_name6", - "email": "email8", - "cc_emails": "cc_emails2", - "organization": "organization8" -} -``` - + +# Customer + +## Structure + +`Customer` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FirstName` | `*string` | Optional | The first name of the customer | +| `LastName` | `*string` | Optional | The last name of the customer | +| `Email` | `*string` | Optional | The email address of the customer | +| `CcEmails` | `models.Optional[string]` | Optional | A comma-separated list of emails that should be cc’d on all customer communications (i.e. “joe@example.com, sue@example.com”) | +| `Organization` | `models.Optional[string]` | Optional | The organization of the customer | +| `Reference` | `models.Optional[string]` | Optional | The unique identifier used within your own application for this customer | +| `Id` | `*int` | Optional | The customer ID in Chargify | +| `CreatedAt` | `*time.Time` | Optional | The timestamp in which the customer object was created in Chargify | +| `UpdatedAt` | `*time.Time` | Optional | The timestamp in which the customer object was last edited | +| `Address` | `models.Optional[string]` | Optional | The customer’s shipping street address (i.e. “123 Main St.”) | +| `Address2` | `models.Optional[string]` | Optional | Second line of the customer’s shipping address i.e. “Apt. 100” | +| `City` | `models.Optional[string]` | Optional | The customer’s shipping address city (i.e. “Boston”) | +| `State` | `models.Optional[string]` | Optional | The customer’s shipping address state (i.e. “MA”) | +| `StateName` | `models.Optional[string]` | Optional | The customer's full name of state | +| `Zip` | `models.Optional[string]` | Optional | The customer’s shipping address zip code (i.e. “12345”) | +| `Country` | `models.Optional[string]` | Optional | The customer shipping address country | +| `CountryName` | `models.Optional[string]` | Optional | The customer's full name of country | +| `Phone` | `models.Optional[string]` | Optional | The phone number of the customer | +| `Verified` | `models.Optional[bool]` | Optional | Is the customer verified to use ACH as a payment method. Available only on Authorize.Net gateway | +| `PortalCustomerCreatedAt` | `models.Optional[time.Time]` | Optional | The timestamp of when the Billing Portal entry was created at for the customer | +| `PortalInviteLastSentAt` | `models.Optional[time.Time]` | Optional | The timestamp of when the Billing Portal invite was last sent at | +| `PortalInviteLastAcceptedAt` | `models.Optional[time.Time]` | Optional | The timestamp of when the Billing Portal invite was last accepted | +| `TaxExempt` | `*bool` | Optional | The tax exempt status for the customer. Acceptable values are true or 1 for true and false or 0 for false. | +| `VatNumber` | `models.Optional[string]` | Optional | The VAT business identification number for the customer. This number is used to determine VAT tax opt out rules. It is not validated when added or updated on a customer record. Instead, it is validated via VIES before calculating taxes. Only valid business identification numbers will allow for VAT opt out. | +| `ParentId` | `models.Optional[int]` | Optional | The parent ID in Chargify if applicable. Parent is another Customer object. | +| `Locale` | `models.Optional[string]` | Optional | The locale for the customer to identify language-region | +| `DefaultSubscriptionGroupUid` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "first_name": "first_name8", + "last_name": "last_name6", + "email": "email8", + "cc_emails": "cc_emails2", + "organization": "organization8" +} +``` + diff --git a/doc/models/deduct-service-credit-request.md b/doc/models/deduct-service-credit-request.md index d7796f9d..78e05805 100644 --- a/doc/models/deduct-service-credit-request.md +++ b/doc/models/deduct-service-credit-request.md @@ -1,27 +1,24 @@ - -# Deduct Service Credit Request - -## Structure - -`DeductServiceCreditRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Deduction` | [`models.DeductServiceCredit`](../../doc/models/deduct-service-credit.md) | Required | - | - -## Example (as JSON) - -```json -{ - "deduction": { - "amount": { - "key1": "val1", - "key2": "val2" - }, - "memo": "memo0" - } -} -``` - + +# Deduct Service Credit Request + +## Structure + +`DeductServiceCreditRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Deduction` | [`models.DeductServiceCredit`](../../doc/models/deduct-service-credit.md) | Required | - | + +## Example (as JSON) + +```json +{ + "deduction": { + "amount": "String9", + "memo": "memo0" + } +} +``` + diff --git a/doc/models/deduct-service-credit.md b/doc/models/deduct-service-credit.md index 9fa7b3a3..5d328f4f 100644 --- a/doc/models/deduct-service-credit.md +++ b/doc/models/deduct-service-credit.md @@ -1,26 +1,23 @@ - -# Deduct Service Credit - -## Structure - -`DeductServiceCredit` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Amount` | `interface{}` | Required | - | -| `Memo` | `string` | Required | - | - -## Example (as JSON) - -```json -{ - "amount": { - "key1": "val1", - "key2": "val2" - }, - "memo": "memo2" -} -``` - + +# Deduct Service Credit + +## Structure + +`DeductServiceCredit` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Amount` | [`models.DeductServiceCreditAmount`](../../doc/models/containers/deduct-service-credit-amount.md) | Required | This is a container for one-of cases. | +| `Memo` | `string` | Required | - | + +## Example (as JSON) + +```json +{ + "amount": "String1", + "memo": "memo2" +} +``` + diff --git a/doc/models/delayed-cancellation-response.md b/doc/models/delayed-cancellation-response.md index 365c4377..e95c99de 100644 --- a/doc/models/delayed-cancellation-response.md +++ b/doc/models/delayed-cancellation-response.md @@ -1,21 +1,21 @@ - -# Delayed Cancellation Response - -## Structure - -`DelayedCancellationResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Message` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "message": "message8" -} -``` - + +# Delayed Cancellation Response + +## Structure + +`DelayedCancellationResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Message` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "message": "message8" +} +``` + diff --git a/doc/models/delete-subscription-group-response.md b/doc/models/delete-subscription-group-response.md index ca2131ad..6cf3d340 100644 --- a/doc/models/delete-subscription-group-response.md +++ b/doc/models/delete-subscription-group-response.md @@ -1,23 +1,23 @@ - -# Delete Subscription Group Response - -## Structure - -`DeleteSubscriptionGroupResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `Deleted` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid4", - "deleted": false -} -``` - + +# Delete Subscription Group Response + +## Structure + +`DeleteSubscriptionGroupResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `Deleted` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid4", + "deleted": false +} +``` + diff --git a/doc/models/direction.md b/doc/models/direction.md index d2e77390..ef6c29da 100644 --- a/doc/models/direction.md +++ b/doc/models/direction.md @@ -1,14 +1,14 @@ - -# Direction - -## Enumeration - -`Direction` - -## Fields - -| Name | -| --- | -| `ASC` | -| `DESC` | - + +# Direction + +## Enumeration + +`Direction` + +## Fields + +| Name | +| --- | +| `ASC` | +| `DESC` | + diff --git a/doc/models/discount-type.md b/doc/models/discount-type.md index d134aec1..77357ece 100644 --- a/doc/models/discount-type.md +++ b/doc/models/discount-type.md @@ -1,14 +1,14 @@ - -# Discount Type - -## Enumeration - -`DiscountType` - -## Fields - -| Name | -| --- | -| `AMOUNT` | -| `PERCENT` | - + +# Discount Type + +## Enumeration + +`DiscountType` + +## Fields + +| Name | +| --- | +| `AMOUNT` | +| `PERCENT` | + diff --git a/doc/models/dunner-data.md b/doc/models/dunner-data.md new file mode 100644 index 00000000..16248d80 --- /dev/null +++ b/doc/models/dunner-data.md @@ -0,0 +1,31 @@ + +# Dunner Data + +## Structure + +`DunnerData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `State` | `string` | Required | - | +| `SubscriptionId` | `int` | Required | - | +| `RevenueAtRiskInCents` | `int64` | Required | - | +| `CreatedAt` | `time.Time` | Required | - | +| `Attempts` | `int` | Required | - | +| `LastAttemptedAt` | `time.Time` | Required | - | + +## Example (as JSON) + +```json +{ + "state": "state4", + "subscription_id": 126, + "revenue_at_risk_in_cents": 30, + "created_at": "2016-03-13T12:52:32.123Z", + "attempts": 110, + "last_attempted_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/dunning-step-data.md b/doc/models/dunning-step-data.md new file mode 100644 index 00000000..f0f7bd12 --- /dev/null +++ b/doc/models/dunning-step-data.md @@ -0,0 +1,35 @@ + +# Dunning Step Data + +## Structure + +`DunningStepData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `DayThreshold` | `int` | Required | - | +| `Action` | `string` | Required | - | +| `EmailBody` | `models.Optional[string]` | Optional | - | +| `EmailSubject` | `models.Optional[string]` | Optional | - | +| `SendEmail` | `bool` | Required | - | +| `SendBccEmail` | `bool` | Required | - | +| `SendSms` | `bool` | Required | - | +| `SmsBody` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "day_threshold": 88, + "action": "action4", + "email_body": "email_body4", + "email_subject": "email_subject4", + "send_email": false, + "send_bcc_email": false, + "send_sms": false, + "sms_body": "sms_body0" +} +``` + diff --git a/doc/models/dunning-step-reached.md b/doc/models/dunning-step-reached.md new file mode 100644 index 00000000..05927f4e --- /dev/null +++ b/doc/models/dunning-step-reached.md @@ -0,0 +1,50 @@ + +# Dunning Step Reached + +## Structure + +`DunningStepReached` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Dunner` | [`models.DunnerData`](../../doc/models/dunner-data.md) | Required | - | +| `CurrentStep` | [`models.DunningStepData`](../../doc/models/dunning-step-data.md) | Required | - | +| `NextStep` | [`models.DunningStepData`](../../doc/models/dunning-step-data.md) | Required | - | + +## Example (as JSON) + +```json +{ + "dunner": { + "state": "state8", + "subscription_id": 194, + "revenue_at_risk_in_cents": 98, + "created_at": "2016-03-13T12:52:32.123Z", + "attempts": 42, + "last_attempted_at": "2016-03-13T12:52:32.123Z" + }, + "current_step": { + "day_threshold": 198, + "action": "action4", + "email_body": "email_body4", + "email_subject": "email_subject6", + "send_email": false, + "send_bcc_email": false, + "send_sms": false, + "sms_body": "sms_body0" + }, + "next_step": { + "day_threshold": 30, + "action": "action4", + "email_body": "email_body4", + "email_subject": "email_subject4", + "send_email": false, + "send_bcc_email": false, + "send_sms": false, + "sms_body": "sms_body0" + } +} +``` + diff --git a/doc/models/ebb-component.md b/doc/models/ebb-component.md index c4cc74cb..4732e7ef 100644 --- a/doc/models/ebb-component.md +++ b/doc/models/ebb-component.md @@ -1,60 +1,51 @@ - -# EBB Component - -## Structure - -`EBBComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `string` | Required | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | -| `UnitName` | `string` | Required | The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item | -| `Description` | `*string` | Optional | A description for the component that will be displayed to the user on the hosted signup page. | -| `Handle` | `*string` | Optional | A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'.
**Constraints**: *Pattern*: `^[a-z0-9][a-z0-9\-_:.]*$` | -| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | -| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://help.chargify.com/products/product-components.html#general-price-bracket-rules) for an overview of how price brackets work for different pricing schemes. | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `PricePoints` | [`[]models.ComponentPricePointItem`](../../doc/models/component-price-point-item.md) | Optional | - | -| `UnitPrice` | `*interface{}` | Optional | The amount the customer will be charged per unit when the pricing scheme is “per_unit”. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 | -| `TaxCode` | `*string` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | -| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | -| `PriceInCents` | `*string` | Optional | deprecated May 2011 - use unit_price instead | -| `EventBasedBillingMetricId` | `int` | Required | The ID of an event based billing metric that will be attached to this component. | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. | - -## Example (as JSON) - -```json -{ - "name": "name0", - "unit_name": "unit_name2", - "description": "description0", - "handle": "handle6", - "taxable": false, - "pricing_scheme": "per_unit", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ], - "upgrade_charge": "full", - "event_based_billing_metric_id": 190 -} -``` - + +# EBB Component + +## Structure + +`EBBComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | +| `UnitName` | `string` | Required | The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item | +| `Description` | `*string` | Optional | A description for the component that will be displayed to the user on the hosted signup page. | +| `Handle` | `*string` | Optional | A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'.
**Constraints**: *Pattern*: `^[a-z0-9][a-z0-9\-_:.]*$` | +| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | +| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://help.chargify.com/products/product-components.html#general-price-bracket-rules) for an overview of how price brackets work for different pricing schemes. | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `PricePoints` | [`[]models.ComponentPricePointItem`](../../doc/models/component-price-point-item.md) | Optional | - | +| `UnitPrice` | [`*models.EBBComponentUnitPrice`](../../doc/models/containers/ebb-component-unit-price.md) | Optional | This is a container for one-of cases. | +| `TaxCode` | `*string` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | +| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | +| `PriceInCents` | `*string` | Optional | deprecated May 2011 - use unit_price instead | +| `EventBasedBillingMetricId` | `int` | Required | The ID of an event based billing metric that will be attached to this component. | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. | + +## Example (as JSON) + +```json +{ + "name": "name0", + "unit_name": "unit_name2", + "description": "description0", + "handle": "handle6", + "taxable": false, + "pricing_scheme": "per_unit", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "upgrade_charge": "full", + "event_based_billing_metric_id": 190 +} +``` + diff --git a/doc/models/ebb-event.md b/doc/models/ebb-event.md index ad276190..fcdd38a7 100644 --- a/doc/models/ebb-event.md +++ b/doc/models/ebb-event.md @@ -1,38 +1,38 @@ - -# EBB Event - -## Structure - -`EBBEvent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Chargify` | [`*models.ChargifyEBB`](../../doc/models/chargify-ebb.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "chargify": { - "subscription_id": 1, - "timestamp": "2020-02-27T17:45:50-05:00", - "id": "id6", - "created_at": "2016-03-13T12:52:32.123Z", - "uniqueness_token": "uniqueness_token2" - }, - "messages": 150, - "country": "US", - "customer": { - "name": "John", - "lastName": "Doe", - "address": { - "street": "Maple Street", - "zip": 4888, - "state": "MA" - } - } -} -``` - + +# EBB Event + +## Structure + +`EBBEvent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Chargify` | [`*models.ChargifyEBB`](../../doc/models/chargify-ebb.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "chargify": { + "subscription_id": 1, + "timestamp": "2020-02-27T17:45:50-05:00", + "id": "id6", + "created_at": "2016-03-13T12:52:32.123Z", + "uniqueness_token": "uniqueness_token2" + }, + "messages": 150, + "country": "US", + "customer": { + "name": "John", + "lastName": "Doe", + "address": { + "street": "Maple Street", + "zip": 4888, + "state": "MA" + } + } +} +``` + diff --git a/doc/models/enable-webhooks-request.md b/doc/models/enable-webhooks-request.md index 113a7e1e..317c4289 100644 --- a/doc/models/enable-webhooks-request.md +++ b/doc/models/enable-webhooks-request.md @@ -1,21 +1,21 @@ - -# Enable Webhooks Request - -## Structure - -`EnableWebhooksRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `WebhooksEnabled` | `bool` | Required | - | - -## Example (as JSON) - -```json -{ - "webhooks_enabled": false -} -``` - + +# Enable Webhooks Request + +## Structure + +`EnableWebhooksRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `WebhooksEnabled` | `bool` | Required | - | + +## Example (as JSON) + +```json +{ + "webhooks_enabled": false +} +``` + diff --git a/doc/models/enable-webhooks-response.md b/doc/models/enable-webhooks-response.md index eb925269..c386f6c1 100644 --- a/doc/models/enable-webhooks-response.md +++ b/doc/models/enable-webhooks-response.md @@ -1,21 +1,21 @@ - -# Enable Webhooks Response - -## Structure - -`EnableWebhooksResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `WebhooksEnabled` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "webhooks_enabled": false -} -``` - + +# Enable Webhooks Response + +## Structure + +`EnableWebhooksResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `WebhooksEnabled` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "webhooks_enabled": false +} +``` + diff --git a/doc/models/endpoint-response.md b/doc/models/endpoint-response.md index 69662bb3..39d3484d 100644 --- a/doc/models/endpoint-response.md +++ b/doc/models/endpoint-response.md @@ -1,29 +1,29 @@ - -# Endpoint Response - -## Structure - -`EndpointResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Endpoint` | [`*models.Endpoint`](../../doc/models/endpoint.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "endpoint": { - "id": 202, - "url": "url2", - "site_id": 128, - "status": "status0", - "webhook_subscriptions": [ - "webhook_subscriptions4" - ] - } -} -``` - + +# Endpoint Response + +## Structure + +`EndpointResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Endpoint` | [`*models.Endpoint`](../../doc/models/endpoint.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "endpoint": { + "id": 202, + "url": "url2", + "site_id": 128, + "status": "status0", + "webhook_subscriptions": [ + "webhook_subscriptions4" + ] + } +} +``` + diff --git a/doc/models/endpoint.md b/doc/models/endpoint.md index 39552de5..c8e5a3a3 100644 --- a/doc/models/endpoint.md +++ b/doc/models/endpoint.md @@ -1,32 +1,32 @@ - -# Endpoint - -## Structure - -`Endpoint` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Url` | `*string` | Optional | - | -| `SiteId` | `*int` | Optional | - | -| `Status` | `*string` | Optional | - | -| `WebhookSubscriptions` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 196, - "url": "url2", - "site_id": 122, - "status": "status0", - "webhook_subscriptions": [ - "webhook_subscriptions4", - "webhook_subscriptions3" - ] -} -``` - + +# Endpoint + +## Structure + +`Endpoint` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Url` | `*string` | Optional | - | +| `SiteId` | `*int` | Optional | - | +| `Status` | `*string` | Optional | - | +| `WebhookSubscriptions` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 196, + "url": "url2", + "site_id": 122, + "status": "status0", + "webhook_subscriptions": [ + "webhook_subscriptions4", + "webhook_subscriptions3" + ] +} +``` + diff --git a/doc/models/error-array-map-response-exception.md b/doc/models/error-array-map-response-exception.md index 960a0f69..0f48ab98 100644 --- a/doc/models/error-array-map-response-exception.md +++ b/doc/models/error-array-map-response-exception.md @@ -1,26 +1,26 @@ - -# Error Array Map Response Exception - -## Structure - -`ErrorArrayMapResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | `map[string]interface{}` | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": { - "key0": { - "key1": "val1", - "key2": "val2" - } - } -} -``` - + +# Error Array Map Response Exception + +## Structure + +`ErrorArrayMapResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | `map[string]interface{}` | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": { + "key0": { + "key1": "val1", + "key2": "val2" + } + } +} +``` + diff --git a/doc/models/error-list-response-exception.md b/doc/models/error-list-response-exception.md index c183004f..b76a2b99 100644 --- a/doc/models/error-list-response-exception.md +++ b/doc/models/error-list-response-exception.md @@ -1,27 +1,27 @@ - -# Error List Response Exception - -Error which contains list of messages. - -## Structure - -`ErrorListResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | `[]string` | Required | - | - -## Example (as JSON) - -```json -{ - "errors": [ - "errors5", - "errors6", - "errors7" - ] -} -``` - + +# Error List Response Exception + +Error which contains list of messages. + +## Structure + +`ErrorListResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | `[]string` | Required | - | + +## Example (as JSON) + +```json +{ + "errors": [ + "errors5", + "errors6", + "errors7" + ] +} +``` + diff --git a/doc/models/error-string-map-response-exception.md b/doc/models/error-string-map-response-exception.md index 9cf6bb0c..7da28ab8 100644 --- a/doc/models/error-string-map-response-exception.md +++ b/doc/models/error-string-map-response-exception.md @@ -1,24 +1,24 @@ - -# Error String Map Response Exception - -## Structure - -`ErrorStringMapResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | `map[string]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": { - "key0": "errors3", - "key1": "errors4" - } -} -``` - + +# Error String Map Response Exception + +## Structure + +`ErrorStringMapResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | `map[string]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": { + "key0": "errors3", + "key1": "errors4" + } +} +``` + diff --git a/doc/models/errors.md b/doc/models/errors.md index c3d56b85..706c5718 100644 --- a/doc/models/errors.md +++ b/doc/models/errors.md @@ -1,29 +1,29 @@ - -# Errors - -## Structure - -`Errors` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PerPage` | `[]string` | Optional | - | -| `PricePoint` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "per_page": [ - "per_page7", - "per_page8" - ], - "price_point": [ - "price_point6", - "price_point7" - ] -} -``` - + +# Errors + +## Structure + +`Errors` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PerPage` | `[]string` | Optional | - | +| `PricePoint` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "per_page": [ + "per_page7", + "per_page8" + ], + "price_point": [ + "price_point6", + "price_point7" + ] +} +``` + diff --git a/doc/models/event-based-billing-list-segments-errors-exception.md b/doc/models/event-based-billing-list-segments-errors-exception.md index 7f4b3a36..18aff644 100644 --- a/doc/models/event-based-billing-list-segments-errors-exception.md +++ b/doc/models/event-based-billing-list-segments-errors-exception.md @@ -1,32 +1,32 @@ - -# Event Based Billing List Segments Errors Exception - -## Structure - -`EventBasedBillingListSegmentsErrorsException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`*models.Errors`](../../doc/models/errors.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": { - "per_page": [ - "per_page1", - "per_page2", - "per_page3" - ], - "price_point": [ - "price_point0", - "price_point9", - "price_point8" - ] - } -} -``` - + +# Event Based Billing List Segments Errors Exception + +## Structure + +`EventBasedBillingListSegmentsErrorsException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`*models.Errors`](../../doc/models/errors.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": { + "per_page": [ + "per_page1", + "per_page2", + "per_page3" + ], + "price_point": [ + "price_point0", + "price_point9", + "price_point8" + ] + } +} +``` + diff --git a/doc/models/event-based-billing-segment-error.md b/doc/models/event-based-billing-segment-error.md index af60c450..33c80a63 100644 --- a/doc/models/event-based-billing-segment-error.md +++ b/doc/models/event-based-billing-segment-error.md @@ -1,30 +1,30 @@ - -# Event Based Billing Segment Error - -## Structure - -`EventBasedBillingSegmentError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Segments` | `map[string]interface{}` | Required | The key of the object would be a number (an index in the request array) where the error occurred. In the value object, the key represents the field and the value is an array with error messages. In most cases, this object would contain just one key. | - -## Example (as JSON) - -```json -{ - "segments": { - "key0": { - "key1": "val1", - "key2": "val2" - }, - "key1": { - "key1": "val1", - "key2": "val2" - } - } -} -``` - + +# Event Based Billing Segment Error + +## Structure + +`EventBasedBillingSegmentError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Segments` | `map[string]interface{}` | Required | The key of the object would be a number (an index in the request array) where the error occurred. In the value object, the key represents the field and the value is an array with error messages. In most cases, this object would contain just one key. | + +## Example (as JSON) + +```json +{ + "segments": { + "key0": { + "key1": "val1", + "key2": "val2" + }, + "key1": { + "key1": "val1", + "key2": "val2" + } + } +} +``` + diff --git a/doc/models/event-based-billing-segment-errors-exception.md b/doc/models/event-based-billing-segment-errors-exception.md index f8c4ab47..ec4919dd 100644 --- a/doc/models/event-based-billing-segment-errors-exception.md +++ b/doc/models/event-based-billing-segment-errors-exception.md @@ -1,34 +1,34 @@ - -# Event Based Billing Segment Errors Exception - -## Structure - -`EventBasedBillingSegmentErrorsException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | `map[string]interface{}` | Optional | The key of the object would be a number (an index in the request array) where the error occurred. In the value object, the key represents the field and the value is an array with error messages. In most cases, this object would contain just one key. | - -## Example (as JSON) - -```json -{ - "errors": { - "key0": { - "key1": "val1", - "key2": "val2" - }, - "key1": { - "key1": "val1", - "key2": "val2" - }, - "key2": { - "key1": "val1", - "key2": "val2" - } - } -} -``` - + +# Event Based Billing Segment Errors Exception + +## Structure + +`EventBasedBillingSegmentErrorsException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | `map[string]interface{}` | Optional | The key of the object would be a number (an index in the request array) where the error occurred. In the value object, the key represents the field and the value is an array with error messages. In most cases, this object would contain just one key. | + +## Example (as JSON) + +```json +{ + "errors": { + "key0": { + "key1": "val1", + "key2": "val2" + }, + "key1": { + "key1": "val1", + "key2": "val2" + }, + "key2": { + "key1": "val1", + "key2": "val2" + } + } +} +``` + diff --git a/doc/models/event-based-billing-segment-exception.md b/doc/models/event-based-billing-segment-exception.md index 10f7226e..99ffedaf 100644 --- a/doc/models/event-based-billing-segment-exception.md +++ b/doc/models/event-based-billing-segment-exception.md @@ -1,28 +1,28 @@ - -# Event Based Billing Segment Exception - -## Structure - -`EventBasedBillingSegmentException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`models.EventBasedBillingSegmentError`](../../doc/models/event-based-billing-segment-error.md) | Required | - | - -## Example (as JSON) - -```json -{ - "errors": { - "segments": { - "key0": { - "key1": "val1", - "key2": "val2" - } - } - } -} -``` - + +# Event Based Billing Segment Exception + +## Structure + +`EventBasedBillingSegmentException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`models.EventBasedBillingSegmentError`](../../doc/models/event-based-billing-segment-error.md) | Required | - | + +## Example (as JSON) + +```json +{ + "errors": { + "segments": { + "key0": { + "key1": "val1", + "key2": "val2" + } + } + } +} +``` + diff --git a/doc/models/event-response.md b/doc/models/event-response.md index e2e40b90..5ffe05ab 100644 --- a/doc/models/event-response.md +++ b/doc/models/event-response.md @@ -1,32 +1,44 @@ - -# Event Response - -## Structure - -`EventResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Event` | [`models.Event`](../../doc/models/event.md) | Required | - | - -## Example (as JSON) - -```json -{ - "event": { - "id": 242, - "key": "key0", - "message": "message0", - "subscription_id": 96, - "customer_id": 24, - "created_at": "2016-03-13T12:52:32.123Z", - "event_specific_data": { - "key1": "val1", - "key2": "val2" - } - } -} -``` - + +# Event Response + +## Structure + +`EventResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Event` | [`models.Event`](../../doc/models/event.md) | Required | - | + +## Example (as JSON) + +```json +{ + "event": { + "id": 242, + "key": "key0", + "message": "message0", + "subscription_id": 96, + "customer_id": 24, + "created_at": "2016-03-13T12:52:32.123Z", + "event_specific_data": { + "previous_unit_balance": null, + "previous_overage_unit_balance": null, + "new_unit_balance": null, + "new_overage_unit_balance": null, + "usage_quantity": null, + "overage_usage_quantity": null, + "component_id": null, + "component_handle": null, + "memo": null, + "allocation_details": [ + null + ], + "previous_product_id": 126, + "new_product_id": 12 + } + } +} +``` + diff --git a/doc/models/event-type.md b/doc/models/event-type.md index 5689fa9f..da8af062 100644 --- a/doc/models/event-type.md +++ b/doc/models/event-type.md @@ -1,46 +1,46 @@ - -# Event Type - -## Enumeration - -`EventType` - -## Fields - -| Name | -| --- | -| `ACCOUNTTRANSACTIONCHANGED` | -| `BILLINGDATECHANGE` | -| `COMPONENTALLOCATIONCHANGE` | -| `CUSTOMERUPDATE` | -| `CUSTOMERCREATE` | -| `DUNNINGSTEPREACHED` | -| `EXPIRATIONDATECHANGE` | -| `EXPIRINGCARD` | -| `METEREDUSAGE` | -| `PAYMENTSUCCESS` | -| `PAYMENTSUCCESSRECREATED` | -| `PAYMENTFAILURE` | -| `PAYMENTFAILURERECREATED` | -| `REFUNDFAILURE` | -| `REFUNDSUCCESS` | -| `RENEWALSUCCESS` | -| `RENEWALSUCCESSRECREATED` | -| `RENEWALFAILURE` | -| `SIGNUPSUCCESS` | -| `SIGNUPFAILURE` | -| `STATEMENTCLOSED` | -| `STATEMENTSETTLED` | -| `SUBSCRIPTIONBANKACCOUNTUPDATE` | -| `SUBSCRIPTIONDELETION` | -| `SUBSCRIPTIONPAYPALACCOUNTUPDATE` | -| `SUBSCRIPTIONPRODUCTCHANGE` | -| `SUBSCRIPTIONSTATECHANGE` | -| `TRIALENDNOTICE` | -| `UPGRADEDOWNGRADESUCCESS` | -| `UPGRADEDOWNGRADEFAILURE` | -| `UPCOMINGRENEWALNOTICE` | -| `CUSTOMFIELDVALUECHANGE` | -| `SUBSCRIPTIONPREPAYMENTACCOUNTBALANCECHANGED` | -| `SUBSCRIPTIONSERVICECREDITACCOUNTBALANCECHANGED` | - + +# Event Type + +## Enumeration + +`EventType` + +## Fields + +| Name | +| --- | +| `ACCOUNTTRANSACTIONCHANGED` | +| `BILLINGDATECHANGE` | +| `COMPONENTALLOCATIONCHANGE` | +| `CUSTOMERUPDATE` | +| `CUSTOMERCREATE` | +| `DUNNINGSTEPREACHED` | +| `EXPIRATIONDATECHANGE` | +| `EXPIRINGCARD` | +| `METEREDUSAGE` | +| `PAYMENTSUCCESS` | +| `PAYMENTSUCCESSRECREATED` | +| `PAYMENTFAILURE` | +| `PAYMENTFAILURERECREATED` | +| `REFUNDFAILURE` | +| `REFUNDSUCCESS` | +| `RENEWALSUCCESS` | +| `RENEWALSUCCESSRECREATED` | +| `RENEWALFAILURE` | +| `SIGNUPSUCCESS` | +| `SIGNUPFAILURE` | +| `STATEMENTCLOSED` | +| `STATEMENTSETTLED` | +| `SUBSCRIPTIONBANKACCOUNTUPDATE` | +| `SUBSCRIPTIONDELETION` | +| `SUBSCRIPTIONPAYPALACCOUNTUPDATE` | +| `SUBSCRIPTIONPRODUCTCHANGE` | +| `SUBSCRIPTIONSTATECHANGE` | +| `TRIALENDNOTICE` | +| `UPGRADEDOWNGRADESUCCESS` | +| `UPGRADEDOWNGRADEFAILURE` | +| `UPCOMINGRENEWALNOTICE` | +| `CUSTOMFIELDVALUECHANGE` | +| `SUBSCRIPTIONPREPAYMENTACCOUNTBALANCECHANGED` | +| `SUBSCRIPTIONSERVICECREDITACCOUNTBALANCECHANGED` | + diff --git a/doc/models/event.md b/doc/models/event.md index 26100c2f..163fbe63 100644 --- a/doc/models/event.md +++ b/doc/models/event.md @@ -1,36 +1,48 @@ - -# Event - -## Structure - -`Event` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `int` | Required | - | -| `Key` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `Message` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `SubscriptionId` | `*int` | Required | - | -| `CustomerId` | `*int` | Required | - | -| `CreatedAt` | `time.Time` | Required | - | -| `EventSpecificData` | `interface{}` | Required | - | - -## Example (as JSON) - -```json -{ - "id": 40, - "key": "key2", - "message": "message8", - "subscription_id": 150, - "customer_id": 78, - "created_at": "2016-03-13T12:52:32.123Z", - "event_specific_data": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Event + +## Structure + +`Event` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `int` | Required | - | +| `Key` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `Message` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `SubscriptionId` | `*int` | Required | - | +| `CustomerId` | `*int` | Required | - | +| `CreatedAt` | `time.Time` | Required | - | +| `EventSpecificData` | [`*models.EventEventSpecificData`](../../doc/models/containers/event-event-specific-data.md) | Required | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "id": 40, + "key": "key2", + "message": "message8", + "subscription_id": 150, + "customer_id": 78, + "created_at": "2016-03-13T12:52:32.123Z", + "event_specific_data": { + "previous_unit_balance": null, + "previous_overage_unit_balance": null, + "new_unit_balance": null, + "new_overage_unit_balance": null, + "usage_quantity": null, + "overage_usage_quantity": null, + "component_id": null, + "component_handle": null, + "memo": null, + "allocation_details": [ + null + ], + "previous_product_id": 126, + "new_product_id": 12 + } +} +``` + diff --git a/doc/models/extended-interval-unit.md b/doc/models/extended-interval-unit.md index 9b4bfbef..f51e38fc 100644 --- a/doc/models/extended-interval-unit.md +++ b/doc/models/extended-interval-unit.md @@ -1,15 +1,15 @@ - -# Extended Interval Unit - -## Enumeration - -`ExtendedIntervalUnit` - -## Fields - -| Name | -| --- | -| `DAY` | -| `MONTH` | -| `NEVER` | - + +# Extended Interval Unit + +## Enumeration + +`ExtendedIntervalUnit` + +## Fields + +| Name | +| --- | +| `DAY` | +| `MONTH` | +| `NEVER` | + diff --git a/doc/models/failed-payment-action.md b/doc/models/failed-payment-action.md index 2344516b..99b4c95c 100644 --- a/doc/models/failed-payment-action.md +++ b/doc/models/failed-payment-action.md @@ -1,21 +1,21 @@ - -# Failed Payment Action - + +# Failed Payment Action + Action taken when payment for an invoice fails: - `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. - `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. -- `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). - -## Enumeration - -`FailedPaymentAction` - -## Fields - -| Name | -| --- | -| `LEAVEOPENINVOICE` | -| `ROLLBACKTOPENDING` | -| `INITIATEDUNNING` | - +- `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). + +## Enumeration + +`FailedPaymentAction` + +## Fields + +| Name | +| --- | +| `LEAVEOPENINVOICE` | +| `ROLLBACKTOPENDING` | +| `INITIATEDUNNING` | + diff --git a/doc/models/first-charge-type.md b/doc/models/first-charge-type.md index 767122d9..9fa953d6 100644 --- a/doc/models/first-charge-type.md +++ b/doc/models/first-charge-type.md @@ -1,15 +1,15 @@ - -# First Charge Type - -## Enumeration - -`FirstChargeType` - -## Fields - -| Name | -| --- | -| `PRORATED` | -| `IMMEDIATE` | -| `DELAYED` | - + +# First Charge Type + +## Enumeration + +`FirstChargeType` + +## Fields + +| Name | +| --- | +| `PRORATED` | +| `IMMEDIATE` | +| `DELAYED` | + diff --git a/doc/models/full-subscription-group-response.md b/doc/models/full-subscription-group-response.md index 0277e0e7..f9ce67d4 100644 --- a/doc/models/full-subscription-group-response.md +++ b/doc/models/full-subscription-group-response.md @@ -1,40 +1,40 @@ - -# Full Subscription Group Response - -## Structure - -`FullSubscriptionGroupResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `Scheme` | `*int` | Optional | - | -| `CustomerId` | `*int` | Optional | - | -| `PaymentProfileId` | `*int` | Optional | - | -| `SubscriptionIds` | `[]int` | Optional | - | -| `PrimarySubscriptionId` | `*int` | Optional | - | -| `NextAssessmentAt` | `*time.Time` | Optional | - | -| `State` | `*string` | Optional | - | -| `CancelAtEndOfPeriod` | `*bool` | Optional | - | -| `CurrentBillingAmountInCents` | `*int64` | Optional | - | -| `Customer` | [`*models.SubscriptionGroupCustomer`](../../doc/models/subscription-group-customer.md) | Optional | - | -| `AccountBalances` | [`*models.SubscriptionGroupBalances`](../../doc/models/subscription-group-balances.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid8", - "scheme": 90, - "customer_id": 110, - "payment_profile_id": 18, - "subscription_ids": [ - 220, - 221, - 222 - ] -} -``` - + +# Full Subscription Group Response + +## Structure + +`FullSubscriptionGroupResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `Scheme` | `*int` | Optional | - | +| `CustomerId` | `*int` | Optional | - | +| `PaymentProfileId` | `*int` | Optional | - | +| `SubscriptionIds` | `[]int` | Optional | - | +| `PrimarySubscriptionId` | `*int` | Optional | - | +| `NextAssessmentAt` | `*time.Time` | Optional | - | +| `State` | [`*models.SubscriptionState`](../../doc/models/subscription-state.md) | Optional | The state of a subscription.

* **Live States**
* `active` - A normal, active subscription. It is not in a trial and is paid and up to date.
* `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state.
* `paused` - An internal state that indicates that your account with Advanced Billing is in arrears.
* **Problem States**
* `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers.
* `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed.
* `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`.
* **End of Life States**
* `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription.
While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance.
* `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period.
* `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.)
* `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time.
* `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state.
* `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details.

See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. | +| `CancelAtEndOfPeriod` | `*bool` | Optional | - | +| `CurrentBillingAmountInCents` | `*int64` | Optional | - | +| `Customer` | [`*models.SubscriptionGroupCustomer`](../../doc/models/subscription-group-customer.md) | Optional | - | +| `AccountBalances` | [`*models.SubscriptionGroupBalances`](../../doc/models/subscription-group-balances.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid8", + "scheme": 90, + "customer_id": 110, + "payment_profile_id": 18, + "subscription_ids": [ + 220, + 221, + 222 + ] +} +``` + diff --git a/doc/models/get-one-time-token-payment-profile.md b/doc/models/get-one-time-token-payment-profile.md index eb4e5c30..d00838cb 100644 --- a/doc/models/get-one-time-token-payment-profile.md +++ b/doc/models/get-one-time-token-payment-profile.md @@ -1,61 +1,61 @@ - -# Get One Time Token Payment Profile - -## Structure - -`GetOneTimeTokenPaymentProfile` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `Optional[string]` | Optional | - | -| `FirstName` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `LastName` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `MaskedCardNumber` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `CardType` | [`models.CardType`](../../doc/models/card-type.md) | Required | The type of card used. | -| `ExpirationMonth` | `float64` | Required | - | -| `ExpirationYear` | `float64` | Required | - | -| `CustomerId` | `Optional[string]` | Optional | - | -| `CurrentVault` | [`models.CurrentVault`](../../doc/models/current-vault.md) | Required | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | -| `VaultToken` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `BillingAddress` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `BillingAddress2` | `*string` | Optional | - | -| `BillingCity` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `BillingCountry` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `BillingState` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `BillingZip` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `PaymentType` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `Disabled` | `bool` | Required | - | -| `SiteGatewaySettingId` | `int` | Required | - | -| `CustomerVaultToken` | `Optional[string]` | Optional | - | -| `GatewayHandle` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": "id2", - "first_name": "first_name2", - "last_name": "last_name0", - "masked_card_number": "masked_card_number0", - "card_type": "routex", - "expiration_month": 187.78, - "expiration_year": 164.44, - "customer_id": "customer_id0", - "current_vault": "firstdata", - "vault_token": "vault_token4", - "billing_address": "billing_address4", - "billing_address_2": "billing_address_24", - "billing_city": "billing_city0", - "billing_country": "billing_country6", - "billing_state": "billing_state6", - "billing_zip": "billing_zip0", - "payment_type": "payment_type2", - "disabled": false, - "site_gateway_setting_id": 232, - "customer_vault_token": "customer_vault_token0", - "gateway_handle": "gateway_handle4" -} -``` - + +# Get One Time Token Payment Profile + +## Structure + +`GetOneTimeTokenPaymentProfile` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `models.Optional[string]` | Optional | - | +| `FirstName` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `LastName` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `MaskedCardNumber` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `CardType` | [`models.CardType`](../../doc/models/card-type.md) | Required | The type of card used. | +| `ExpirationMonth` | `float64` | Required | - | +| `ExpirationYear` | `float64` | Required | - | +| `CustomerId` | `models.Optional[string]` | Optional | - | +| `CurrentVault` | [`models.CurrentVault`](../../doc/models/current-vault.md) | Required | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | +| `VaultToken` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `BillingAddress` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `BillingAddress2` | `*string` | Optional | - | +| `BillingCity` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `BillingCountry` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `BillingState` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `BillingZip` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `PaymentType` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `Disabled` | `bool` | Required | - | +| `SiteGatewaySettingId` | `int` | Required | - | +| `CustomerVaultToken` | `models.Optional[string]` | Optional | - | +| `GatewayHandle` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": "id2", + "first_name": "first_name2", + "last_name": "last_name0", + "masked_card_number": "masked_card_number0", + "card_type": "routex", + "expiration_month": 187.78, + "expiration_year": 164.44, + "customer_id": "customer_id0", + "current_vault": "firstdata", + "vault_token": "vault_token4", + "billing_address": "billing_address4", + "billing_address_2": "billing_address_24", + "billing_city": "billing_city0", + "billing_country": "billing_country6", + "billing_state": "billing_state6", + "billing_zip": "billing_zip0", + "payment_type": "payment_type2", + "disabled": false, + "site_gateway_setting_id": 232, + "customer_vault_token": "customer_vault_token0", + "gateway_handle": "gateway_handle4" +} +``` + diff --git a/doc/models/get-one-time-token-request.md b/doc/models/get-one-time-token-request.md index 0fa94e18..5a0576a9 100644 --- a/doc/models/get-one-time-token-request.md +++ b/doc/models/get-one-time-token-request.md @@ -1,43 +1,43 @@ - -# Get One Time Token Request - -## Structure - -`GetOneTimeTokenRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PaymentProfile` | [`models.GetOneTimeTokenPaymentProfile`](../../doc/models/get-one-time-token-payment-profile.md) | Required | - | - -## Example (as JSON) - -```json -{ - "payment_profile": { - "id": "id4", - "first_name": "first_name4", - "last_name": "last_name2", - "masked_card_number": "masked_card_number2", - "card_type": "bogus", - "expiration_month": 133.5, - "expiration_year": 156.84, - "customer_id": "customer_id2", - "current_vault": "eway", - "vault_token": "vault_token6", - "billing_address": "billing_address4", - "billing_address_2": "billing_address_26", - "billing_city": "billing_city8", - "billing_country": "billing_country2", - "billing_state": "billing_state2", - "billing_zip": "billing_zip2", - "payment_type": "payment_type6", - "disabled": false, - "site_gateway_setting_id": 104, - "customer_vault_token": "customer_vault_token2", - "gateway_handle": "gateway_handle4" - } -} -``` - + +# Get One Time Token Request + +## Structure + +`GetOneTimeTokenRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PaymentProfile` | [`models.GetOneTimeTokenPaymentProfile`](../../doc/models/get-one-time-token-payment-profile.md) | Required | - | + +## Example (as JSON) + +```json +{ + "payment_profile": { + "id": "id4", + "first_name": "first_name4", + "last_name": "last_name2", + "masked_card_number": "masked_card_number2", + "card_type": "bogus", + "expiration_month": 133.5, + "expiration_year": 156.84, + "customer_id": "customer_id2", + "current_vault": "eway", + "vault_token": "vault_token6", + "billing_address": "billing_address4", + "billing_address_2": "billing_address_26", + "billing_city": "billing_city8", + "billing_country": "billing_country2", + "billing_state": "billing_state2", + "billing_zip": "billing_zip2", + "payment_type": "payment_type6", + "disabled": false, + "site_gateway_setting_id": 104, + "customer_vault_token": "customer_vault_token2", + "gateway_handle": "gateway_handle4" + } +} +``` + diff --git a/doc/models/group-billing.md b/doc/models/group-billing.md index b7245c38..66f4e20c 100644 --- a/doc/models/group-billing.md +++ b/doc/models/group-billing.md @@ -1,27 +1,27 @@ - -# Group Billing - -Optional attributes related to billing date and accrual. Note: Only applicable for new subscriptions. - -## Structure - -`GroupBilling` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Accrue` | `*bool` | Optional | A flag indicating whether or not to accrue charges on the new subscription.
**Default**: `false` | -| `AlignDate` | `*bool` | Optional | A flag indicating whether or not to align the billing date of the new subscription with the billing date of the primary subscription of the hierarchy's default subscription group. Required to be true if prorate is also true.
**Default**: `false` | -| `Prorate` | `*bool` | Optional | A flag indicating whether or not to prorate billing of the new subscription for the current period. A value of true is ignored unless align_date is also true.
**Default**: `false` | - -## Example (as JSON) - -```json -{ - "accrue": false, - "align_date": false, - "prorate": false -} -``` - + +# Group Billing + +Optional attributes related to billing date and accrual. Note: Only applicable for new subscriptions. + +## Structure + +`GroupBilling` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Accrue` | `*bool` | Optional | A flag indicating whether or not to accrue charges on the new subscription.
**Default**: `false` | +| `AlignDate` | `*bool` | Optional | A flag indicating whether or not to align the billing date of the new subscription with the billing date of the primary subscription of the hierarchy's default subscription group. Required to be true if prorate is also true.
**Default**: `false` | +| `Prorate` | `*bool` | Optional | A flag indicating whether or not to prorate billing of the new subscription for the current period. A value of true is ignored unless align_date is also true.
**Default**: `false` | + +## Example (as JSON) + +```json +{ + "accrue": false, + "align_date": false, + "prorate": false +} +``` + diff --git a/doc/models/group-settings.md b/doc/models/group-settings.md index d1330aa9..3e883ae1 100644 --- a/doc/models/group-settings.md +++ b/doc/models/group-settings.md @@ -1,30 +1,30 @@ - -# Group Settings - -## Structure - -`GroupSettings` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Target` | [`models.GroupTarget`](../../doc/models/group-target.md) | Required | Attributes of the target customer who will be the responsible payer of the created subscription. Required. | -| `Billing` | [`*models.GroupBilling`](../../doc/models/group-billing.md) | Optional | Optional attributes related to billing date and accrual. Note: Only applicable for new subscriptions. | - -## Example (as JSON) - -```json -{ - "target": { - "type": "parent", - "id": 236 - }, - "billing": { - "accrue": false, - "align_date": false, - "prorate": false - } -} -``` - + +# Group Settings + +## Structure + +`GroupSettings` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Target` | [`models.GroupTarget`](../../doc/models/group-target.md) | Required | Attributes of the target customer who will be the responsible payer of the created subscription. Required. | +| `Billing` | [`*models.GroupBilling`](../../doc/models/group-billing.md) | Optional | Optional attributes related to billing date and accrual. Note: Only applicable for new subscriptions. | + +## Example (as JSON) + +```json +{ + "target": { + "type": "parent", + "id": 236 + }, + "billing": { + "accrue": false, + "align_date": false, + "prorate": false + } +} +``` + diff --git a/doc/models/group-target-type.md b/doc/models/group-target-type.md index db084c71..431d4fba 100644 --- a/doc/models/group-target-type.md +++ b/doc/models/group-target-type.md @@ -1,19 +1,19 @@ - -# Group Target Type - -The type of object indicated by the id attribute. - -## Enumeration - -`GroupTargetType` - -## Fields - -| Name | -| --- | -| `CUSTOMER` | -| `SUBSCRIPTION` | -| `SELF` | -| `PARENT` | -| `ELDEST` | - + +# Group Target Type + +The type of object indicated by the id attribute. + +## Enumeration + +`GroupTargetType` + +## Fields + +| Name | +| --- | +| `CUSTOMER` | +| `SUBSCRIPTION` | +| `SELF` | +| `PARENT` | +| `ELDEST` | + diff --git a/doc/models/group-target.md b/doc/models/group-target.md index 25832710..ef8ece31 100644 --- a/doc/models/group-target.md +++ b/doc/models/group-target.md @@ -1,25 +1,25 @@ - -# Group Target - -Attributes of the target customer who will be the responsible payer of the created subscription. Required. - -## Structure - -`GroupTarget` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Type` | [`models.GroupTargetType`](../../doc/models/group-target-type.md) | Required | The type of object indicated by the id attribute. | -| `Id` | `*int` | Optional | The id of the target customer or subscription to group the existing subscription with. Ignored and should not be included if type is "self" , "parent", or "eldest" | - -## Example (as JSON) - -```json -{ - "type": "self", - "id": 134 -} -``` - + +# Group Target + +Attributes of the target customer who will be the responsible payer of the created subscription. Required. + +## Structure + +`GroupTarget` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Type` | [`models.GroupTargetType`](../../doc/models/group-target-type.md) | Required | The type of object indicated by the id attribute. | +| `Id` | `*int` | Optional | The id of the target customer or subscription to group the existing subscription with. Ignored and should not be included if type is "self" , "parent", or "eldest" | + +## Example (as JSON) + +```json +{ + "type": "self", + "id": 134 +} +``` + diff --git a/doc/models/group-type.md b/doc/models/group-type.md new file mode 100644 index 00000000..68fd5f0d --- /dev/null +++ b/doc/models/group-type.md @@ -0,0 +1,14 @@ + +# Group Type + +## Enumeration + +`GroupType` + +## Fields + +| Name | +| --- | +| `SINGLECUSTOMER` | +| `MULTIPLECUSTOMERS` | + diff --git a/doc/models/include-not-null.md b/doc/models/include-not-null.md index de91e8ca..6b1f65fe 100644 --- a/doc/models/include-not-null.md +++ b/doc/models/include-not-null.md @@ -1,21 +1,21 @@ - -# Include Not Null - -Passed as a parameter to list methods to return only non null values. - -## Enumeration - -`IncludeNotNull` - -## Fields - -| Name | -| --- | -| `NOTNULL` | - -## Example - -``` -not_null -``` - + +# Include Not Null + +Passed as a parameter to list methods to return only non null values. + +## Enumeration + +`IncludeNotNull` + +## Fields + +| Name | +| --- | +| `NOTNULL` | + +## Example + +``` +not_null +``` + diff --git a/doc/models/include-option.md b/doc/models/include-option.md index e30fa605..0ad125f0 100644 --- a/doc/models/include-option.md +++ b/doc/models/include-option.md @@ -1,14 +1,14 @@ - -# Include Option - -## Enumeration - -`IncludeOption` - -## Fields - -| Name | -| --- | -| `EXCLUDE` | -| `INCLUDE` | - + +# Include Option + +## Enumeration + +`IncludeOption` + +## Fields + +| Name | +| --- | +| `EXCLUDE` | +| `INCLUDE` | + diff --git a/doc/models/interval-unit.md b/doc/models/interval-unit.md index 2ed5712f..7e4cab3b 100644 --- a/doc/models/interval-unit.md +++ b/doc/models/interval-unit.md @@ -1,14 +1,14 @@ - -# Interval Unit - -## Enumeration - -`IntervalUnit` - -## Fields - -| Name | -| --- | -| `DAY` | -| `MONTH` | - + +# Interval Unit + +## Enumeration + +`IntervalUnit` + +## Fields + +| Name | +| --- | +| `DAY` | +| `MONTH` | + diff --git a/doc/models/invoice-address.md b/doc/models/invoice-address.md index b86d363e..896cc53b 100644 --- a/doc/models/invoice-address.md +++ b/doc/models/invoice-address.md @@ -1,30 +1,30 @@ - -# Invoice Address - -## Structure - -`InvoiceAddress` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Street` | `Optional[string]` | Optional | - | -| `Line2` | `Optional[string]` | Optional | - | -| `City` | `Optional[string]` | Optional | - | -| `State` | `Optional[string]` | Optional | - | -| `Zip` | `Optional[string]` | Optional | - | -| `Country` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "street": "street0", - "line2": "line24", - "city": "city0", - "state": "state6", - "zip": "zip4" -} -``` - + +# Invoice Address + +## Structure + +`InvoiceAddress` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Street` | `models.Optional[string]` | Optional | - | +| `Line2` | `models.Optional[string]` | Optional | - | +| `City` | `models.Optional[string]` | Optional | - | +| `State` | `models.Optional[string]` | Optional | - | +| `Zip` | `models.Optional[string]` | Optional | - | +| `Country` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "street": "street0", + "line2": "line24", + "city": "city0", + "state": "state6", + "zip": "zip4" +} +``` + diff --git a/doc/models/invoice-balance-item.md b/doc/models/invoice-balance-item.md index 32537a35..c4bfa6c1 100644 --- a/doc/models/invoice-balance-item.md +++ b/doc/models/invoice-balance-item.md @@ -1,25 +1,25 @@ - -# Invoice Balance Item - -## Structure - -`InvoiceBalanceItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `Number` | `*string` | Optional | - | -| `OutstandingAmount` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid8", - "number": "number6", - "outstanding_amount": "outstanding_amount6" -} -``` - + +# Invoice Balance Item + +## Structure + +`InvoiceBalanceItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `Number` | `*string` | Optional | - | +| `OutstandingAmount` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid8", + "number": "number6", + "outstanding_amount": "outstanding_amount6" +} +``` + diff --git a/doc/models/invoice-consolidation-level.md b/doc/models/invoice-consolidation-level.md index fcd54172..b45b4b2a 100644 --- a/doc/models/invoice-consolidation-level.md +++ b/doc/models/invoice-consolidation-level.md @@ -1,6 +1,6 @@ - -# Invoice Consolidation Level - + +# Invoice Consolidation Level + Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values: * "none": A normal invoice with no consolidation. @@ -9,17 +9,17 @@ Consolidation level of the invoice, which is applicable to invoice consolidation "Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments. -See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). - -## Enumeration - -`InvoiceConsolidationLevel` - -## Fields - -| Name | -| --- | -| `NONE` | -| `CHILD` | -| `PARENT` | - +See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). + +## Enumeration + +`InvoiceConsolidationLevel` + +## Fields + +| Name | +| --- | +| `NONE` | +| `CHILD` | +| `PARENT` | + diff --git a/doc/models/invoice-credit.md b/doc/models/invoice-credit.md index 9f10d48b..b8566c36 100644 --- a/doc/models/invoice-credit.md +++ b/doc/models/invoice-credit.md @@ -1,31 +1,31 @@ - -# Invoice Credit - -## Structure - -`InvoiceCredit` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `CreditNoteNumber` | `*string` | Optional | - | -| `CreditNoteUid` | `*string` | Optional | - | -| `TransactionTime` | `*time.Time` | Optional | - | -| `Memo` | `*string` | Optional | - | -| `OriginalAmount` | `*string` | Optional | - | -| `AppliedAmount` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid6", - "credit_note_number": "credit_note_number0", - "credit_note_uid": "credit_note_uid0", - "transaction_time": "2016-03-13T12:52:32.123Z", - "memo": "memo0" -} -``` - + +# Invoice Credit + +## Structure + +`InvoiceCredit` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `CreditNoteNumber` | `*string` | Optional | - | +| `CreditNoteUid` | `*string` | Optional | - | +| `TransactionTime` | `*time.Time` | Optional | - | +| `Memo` | `*string` | Optional | - | +| `OriginalAmount` | `*string` | Optional | - | +| `AppliedAmount` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid6", + "credit_note_number": "credit_note_number0", + "credit_note_uid": "credit_note_uid0", + "transaction_time": "2016-03-13T12:52:32.123Z", + "memo": "memo0" +} +``` + diff --git a/doc/models/invoice-custom-field.md b/doc/models/invoice-custom-field.md index 3c71647d..602e524a 100644 --- a/doc/models/invoice-custom-field.md +++ b/doc/models/invoice-custom-field.md @@ -1,29 +1,29 @@ - -# Invoice Custom Field - -## Structure - -`InvoiceCustomField` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `OwnerId` | `*int` | Optional | - | -| `OwnerType` | [`*models.CustomFieldOwner`](../../doc/models/custom-field-owner.md) | Optional | - | -| `Name` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `Value` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `MetadatumId` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "owner_id": 142, - "owner_type": "Customer", - "name": "name0", - "value": "value2", - "metadatum_id": 142 -} -``` - + +# Invoice Custom Field + +## Structure + +`InvoiceCustomField` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `OwnerId` | `*int` | Optional | - | +| `OwnerType` | [`*models.CustomFieldOwner`](../../doc/models/custom-field-owner.md) | Optional | - | +| `Name` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `Value` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `MetadatumId` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "owner_id": 142, + "owner_type": "Customer", + "name": "name0", + "value": "value2", + "metadatum_id": 142 +} +``` + diff --git a/doc/models/invoice-customer.md b/doc/models/invoice-customer.md index 950a9821..00dca389 100644 --- a/doc/models/invoice-customer.md +++ b/doc/models/invoice-customer.md @@ -1,33 +1,33 @@ - -# Invoice Customer - -Information about the customer who is owner or recipient the invoiced subscription. - -## Structure - -`InvoiceCustomer` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ChargifyId` | `Optional[int]` | Optional | - | -| `FirstName` | `*string` | Optional | - | -| `LastName` | `*string` | Optional | - | -| `Organization` | `Optional[string]` | Optional | - | -| `Email` | `*string` | Optional | - | -| `VatNumber` | `Optional[string]` | Optional | - | -| `Reference` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "chargify_id": 236, - "first_name": "first_name0", - "last_name": "last_name8", - "organization": "organization4", - "email": "email6" -} -``` - + +# Invoice Customer + +Information about the customer who is owner or recipient the invoiced subscription. + +## Structure + +`InvoiceCustomer` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ChargifyId` | `models.Optional[int]` | Optional | - | +| `FirstName` | `*string` | Optional | - | +| `LastName` | `*string` | Optional | - | +| `Organization` | `models.Optional[string]` | Optional | - | +| `Email` | `*string` | Optional | - | +| `VatNumber` | `models.Optional[string]` | Optional | - | +| `Reference` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "chargify_id": 236, + "first_name": "first_name0", + "last_name": "last_name8", + "organization": "organization4", + "email": "email6" +} +``` + diff --git a/doc/models/invoice-date-field.md b/doc/models/invoice-date-field.md index 05322faa..b79fe41a 100644 --- a/doc/models/invoice-date-field.md +++ b/doc/models/invoice-date-field.md @@ -1,23 +1,23 @@ - -# Invoice Date Field - -## Enumeration - -`InvoiceDateField` - -## Fields - -| Name | -| --- | -| `CREATEDAT` | -| `DUEDATE` | -| `ISSUEDATE` | -| `UPDATEDAT` | -| `PAIDDATE` | - -## Example - -``` -issue_date -``` - + +# Invoice Date Field + +## Enumeration + +`InvoiceDateField` + +## Fields + +| Name | +| --- | +| `CREATEDAT` | +| `DUEDATE` | +| `ISSUEDATE` | +| `UPDATEDAT` | +| `PAIDDATE` | + +## Example + +``` +issue_date +``` + diff --git a/doc/models/invoice-discount-breakout.md b/doc/models/invoice-discount-breakout.md index 86b1975d..9cfe690f 100644 --- a/doc/models/invoice-discount-breakout.md +++ b/doc/models/invoice-discount-breakout.md @@ -1,25 +1,25 @@ - -# Invoice Discount Breakout - -## Structure - -`InvoiceDiscountBreakout` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `EligibleAmount` | `*string` | Optional | - | -| `DiscountAmount` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid8", - "eligible_amount": "eligible_amount0", - "discount_amount": "discount_amount8" -} -``` - + +# Invoice Discount Breakout + +## Structure + +`InvoiceDiscountBreakout` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `EligibleAmount` | `*string` | Optional | - | +| `DiscountAmount` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid8", + "eligible_amount": "eligible_amount0", + "discount_amount": "discount_amount8" +} +``` + diff --git a/doc/models/invoice-discount-source-type.md b/doc/models/invoice-discount-source-type.md index 379ada29..add16fbd 100644 --- a/doc/models/invoice-discount-source-type.md +++ b/doc/models/invoice-discount-source-type.md @@ -1,15 +1,15 @@ - -# Invoice Discount Source Type - -## Enumeration - -`InvoiceDiscountSourceType` - -## Fields - -| Name | -| --- | -| `COUPON` | -| `REFERRAL` | -| `ENUMADHOCCOUPON` | - + +# Invoice Discount Source Type + +## Enumeration + +`InvoiceDiscountSourceType` + +## Fields + +| Name | +| --- | +| `COUPON` | +| `REFERRAL` | +| `ENUMADHOCCOUPON` | + diff --git a/doc/models/invoice-discount-type.md b/doc/models/invoice-discount-type.md index 7688960c..1fbbb4d7 100644 --- a/doc/models/invoice-discount-type.md +++ b/doc/models/invoice-discount-type.md @@ -1,15 +1,15 @@ - -# Invoice Discount Type - -## Enumeration - -`InvoiceDiscountType` - -## Fields - -| Name | -| --- | -| `PERCENTAGE` | -| `FLATAMOUNT` | -| `ROLLOVER` | - + +# Invoice Discount Type + +## Enumeration + +`InvoiceDiscountType` + +## Fields + +| Name | +| --- | +| `PERCENTAGE` | +| `FLATAMOUNT` | +| `ROLLOVER` | + diff --git a/doc/models/invoice-discount.md b/doc/models/invoice-discount.md index 6f5065ef..b7cce85e 100644 --- a/doc/models/invoice-discount.md +++ b/doc/models/invoice-discount.md @@ -1,36 +1,36 @@ - -# Invoice Discount - -## Structure - -`InvoiceDiscount` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `Title` | `*string` | Optional | - | -| `Description` | `Optional[string]` | Optional | - | -| `Code` | `*string` | Optional | - | -| `SourceType` | [`*models.InvoiceDiscountSourceType`](../../doc/models/invoice-discount-source-type.md) | Optional | - | -| `SourceId` | `*int` | Optional | - | -| `DiscountType` | [`*models.InvoiceDiscountType`](../../doc/models/invoice-discount-type.md) | Optional | - | -| `Percentage` | `*string` | Optional | - | -| `EligibleAmount` | `*string` | Optional | - | -| `DiscountAmount` | `*string` | Optional | - | -| `TransactionId` | `*int` | Optional | - | -| `LineItemBreakouts` | [`[]models.InvoiceDiscountBreakout`](../../doc/models/invoice-discount-breakout.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid0", - "title": "title4", - "description": "description0", - "code": "code8", - "source_type": "Coupon" -} -``` - + +# Invoice Discount + +## Structure + +`InvoiceDiscount` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `Title` | `*string` | Optional | - | +| `Description` | `models.Optional[string]` | Optional | - | +| `Code` | `*string` | Optional | - | +| `SourceType` | [`*models.InvoiceDiscountSourceType`](../../doc/models/invoice-discount-source-type.md) | Optional | - | +| `SourceId` | `*int` | Optional | - | +| `DiscountType` | [`*models.InvoiceDiscountType`](../../doc/models/invoice-discount-type.md) | Optional | - | +| `Percentage` | `*string` | Optional | - | +| `EligibleAmount` | `*string` | Optional | - | +| `DiscountAmount` | `*string` | Optional | - | +| `TransactionId` | `*int` | Optional | - | +| `LineItemBreakouts` | [`[]models.InvoiceDiscountBreakout`](../../doc/models/invoice-discount-breakout.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid0", + "title": "title4", + "description": "description0", + "code": "code8", + "source_type": "Coupon" +} +``` + diff --git a/doc/models/invoice-display-settings.md b/doc/models/invoice-display-settings.md index 747192b4..9d3bff6c 100644 --- a/doc/models/invoice-display-settings.md +++ b/doc/models/invoice-display-settings.md @@ -1,23 +1,23 @@ - -# Invoice Display Settings - -## Structure - -`InvoiceDisplaySettings` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `HideZeroSubtotalLines` | `*bool` | Optional | - | -| `IncludeDiscountsOnLines` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "hide_zero_subtotal_lines": false, - "include_discounts_on_lines": false -} -``` - + +# Invoice Display Settings + +## Structure + +`InvoiceDisplaySettings` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `HideZeroSubtotalLines` | `*bool` | Optional | - | +| `IncludeDiscountsOnLines` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "hide_zero_subtotal_lines": false, + "include_discounts_on_lines": false +} +``` + diff --git a/doc/models/invoice-event-data.md b/doc/models/invoice-event-data.md index 5b0caeb2..70a69a01 100644 --- a/doc/models/invoice-event-data.md +++ b/doc/models/invoice-event-data.md @@ -1,58 +1,58 @@ - -# Invoice Event Data - -The event data is the data that, when combined with the command, results in the output invoice found in the invoice field. - -## Structure - -`InvoiceEventData` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | Unique identifier for the credit note application. It is generated automatically by Chargify and has the prefix "cdt_" followed by alphanumeric characters. | -| `CreditNoteNumber` | `*string` | Optional | A unique, identifying string that appears on the credit note and in places it is referenced. | -| `CreditNoteUid` | `*string` | Optional | Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. | -| `OriginalAmount` | `*string` | Optional | The full, original amount of the credit note. | -| `AppliedAmount` | `*string` | Optional | The amount of the credit note applied to invoice. | -| `TransactionTime` | `*time.Time` | Optional | The time the credit note was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" | -| `Memo` | `*string` | Optional | The credit note memo. | -| `Role` | `*string` | Optional | The role of the credit note (e.g. 'general') | -| `ConsolidatedInvoice` | `*bool` | Optional | Shows whether it was applied to consolidated invoice or not | -| `AppliedCreditNotes` | [`[]models.AppliedCreditNoteData`](../../doc/models/applied-credit-note-data.md) | Optional | List of credit notes applied to children invoices (if consolidated invoice) | -| `DebitNoteNumber` | `*string` | Optional | A unique, identifying string that appears on the debit note and in places it is referenced. | -| `DebitNoteUid` | `*string` | Optional | Unique identifier for the debit note. It is generated automatically by Chargify and has the prefix "db_" followed by alphanumeric characters. | -| `PaymentMethod` | [`*models.InvoiceEventPayment1`](../../doc/models/invoice-event-payment-1.md) | Optional | A nested data structure detailing the method of payment | -| `TransactionId` | `*int` | Optional | The Chargify id of the original payment | -| `ParentInvoiceNumber` | `Optional[int]` | Optional | - | -| `RemainingPrepaymentAmount` | `Optional[string]` | Optional | - | -| `Prepayment` | `*bool` | Optional | The flag that shows whether the original payment was a prepayment or not | -| `External` | `*bool` | Optional | - | -| `FromCollectionMethod` | `*string` | Optional | The previous collection method of the invoice. | -| `ToCollectionMethod` | `*string` | Optional | The new collection method of the invoice. | -| `ConsolidationLevel` | [`*models.InvoiceConsolidationLevel`](../../doc/models/invoice-consolidation-level.md) | Optional | Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values:

* "none": A normal invoice with no consolidation.
* "child": An invoice segment which has been combined into a consolidated invoice.
* "parent": A consolidated invoice, whose contents are composed of invoice segments.

"Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments.

See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). | -| `FromStatus` | [`*models.InvoiceStatus`](../../doc/models/invoice-status.md) | Optional | The status of the invoice before event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. | -| `ToStatus` | [`*models.InvoiceStatus`](../../doc/models/invoice-status.md) | Optional | The status of the invoice after event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. | -| `DueAmount` | `*string` | Optional | Amount due on the invoice, which is `total_amount - credit_amount - paid_amount`. | -| `TotalAmount` | `*string` | Optional | The invoice total, which is `subtotal_amount - discount_amount + tax_amount`.' | -| `ApplyCredit` | `*bool` | Optional | If true, credit was created and applied it to the invoice. | -| `CreditNoteAttributes` | [`*models.CreditNote1`](../../doc/models/credit-note-1.md) | Optional | - | -| `PaymentId` | `*int` | Optional | The ID of the payment transaction to be refunded. | -| `RefundAmount` | `*string` | Optional | The amount of the refund. | -| `RefundId` | `*int` | Optional | The ID of the refund transaction. | -| `IsAdvanceInvoice` | `*bool` | Optional | If true, the invoice is an advance invoice. | -| `Reason` | `*string` | Optional | The reason for the void. | - -## Example (as JSON) - -```json -{ - "uid": "uid0", - "credit_note_number": "credit_note_number6", - "credit_note_uid": "credit_note_uid6", - "original_amount": "original_amount4", - "applied_amount": "applied_amount8" -} -``` - + +# Invoice Event Data + +The event data is the data that, when combined with the command, results in the output invoice found in the invoice field. + +## Structure + +`InvoiceEventData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | Unique identifier for the credit note application. It is generated automatically by Chargify and has the prefix "cdt_" followed by alphanumeric characters. | +| `CreditNoteNumber` | `*string` | Optional | A unique, identifying string that appears on the credit note and in places it is referenced. | +| `CreditNoteUid` | `*string` | Optional | Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. | +| `OriginalAmount` | `*string` | Optional | The full, original amount of the credit note. | +| `AppliedAmount` | `*string` | Optional | The amount of the credit note applied to invoice. | +| `TransactionTime` | `*time.Time` | Optional | The time the credit note was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" | +| `Memo` | `*string` | Optional | The credit note memo. | +| `Role` | `*string` | Optional | The role of the credit note (e.g. 'general') | +| `ConsolidatedInvoice` | `*bool` | Optional | Shows whether it was applied to consolidated invoice or not | +| `AppliedCreditNotes` | [`[]models.AppliedCreditNoteData`](../../doc/models/applied-credit-note-data.md) | Optional | List of credit notes applied to children invoices (if consolidated invoice) | +| `DebitNoteNumber` | `*string` | Optional | A unique, identifying string that appears on the debit note and in places it is referenced. | +| `DebitNoteUid` | `*string` | Optional | Unique identifier for the debit note. It is generated automatically by Chargify and has the prefix "db_" followed by alphanumeric characters. | +| `PaymentMethod` | [`*models.InvoiceEventDataPaymentMethod`](../../doc/models/containers/invoice-event-data-payment-method.md) | Optional | This is a container for any-of cases. | +| `TransactionId` | `*int` | Optional | The Chargify id of the original payment | +| `ParentInvoiceNumber` | `models.Optional[int]` | Optional | - | +| `RemainingPrepaymentAmount` | `models.Optional[string]` | Optional | - | +| `Prepayment` | `*bool` | Optional | The flag that shows whether the original payment was a prepayment or not | +| `External` | `*bool` | Optional | - | +| `FromCollectionMethod` | `*string` | Optional | The previous collection method of the invoice. | +| `ToCollectionMethod` | `*string` | Optional | The new collection method of the invoice. | +| `ConsolidationLevel` | [`*models.InvoiceConsolidationLevel`](../../doc/models/invoice-consolidation-level.md) | Optional | Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values:

* "none": A normal invoice with no consolidation.
* "child": An invoice segment which has been combined into a consolidated invoice.
* "parent": A consolidated invoice, whose contents are composed of invoice segments.

"Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments.

See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). | +| `FromStatus` | [`*models.InvoiceStatus`](../../doc/models/invoice-status.md) | Optional | The status of the invoice before event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. | +| `ToStatus` | [`*models.InvoiceStatus`](../../doc/models/invoice-status.md) | Optional | The status of the invoice after event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. | +| `DueAmount` | `*string` | Optional | Amount due on the invoice, which is `total_amount - credit_amount - paid_amount`. | +| `TotalAmount` | `*string` | Optional | The invoice total, which is `subtotal_amount - discount_amount + tax_amount`.' | +| `ApplyCredit` | `*bool` | Optional | If true, credit was created and applied it to the invoice. | +| `CreditNoteAttributes` | [`*models.CreditNote1`](../../doc/models/credit-note-1.md) | Optional | - | +| `PaymentId` | `*int` | Optional | The ID of the payment transaction to be refunded. | +| `RefundAmount` | `*string` | Optional | The amount of the refund. | +| `RefundId` | `*int` | Optional | The ID of the refund transaction. | +| `IsAdvanceInvoice` | `*bool` | Optional | If true, the invoice is an advance invoice. | +| `Reason` | `*string` | Optional | The reason for the void. | + +## Example (as JSON) + +```json +{ + "uid": "uid0", + "credit_note_number": "credit_note_number6", + "credit_note_uid": "credit_note_uid6", + "original_amount": "original_amount4", + "applied_amount": "applied_amount8" +} +``` + diff --git a/doc/models/invoice-event-payment-1.md b/doc/models/invoice-event-payment-1.md index 7d13b6bf..0d06a670 100644 --- a/doc/models/invoice-event-payment-1.md +++ b/doc/models/invoice-event-payment-1.md @@ -1,43 +1,43 @@ - -# Invoice Event Payment 1 - -A nested data structure detailing the method of payment - -## Structure - -`InvoiceEventPayment1` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Type` | `*string` | Optional | - | -| `MaskedAccountNumber` | `string` | Required | - | -| `MaskedRoutingNumber` | `string` | Required | - | -| `CardBrand` | `string` | Required | - | -| `CardExpiration` | `*string` | Optional | - | -| `LastFour` | `Optional[string]` | Optional | - | -| `MaskedCardNumber` | `string` | Required | - | -| `Details` | `*string` | Required | - | -| `Kind` | `string` | Required | - | -| `Memo` | `*string` | Required | - | -| `Email` | `string` | Required | - | - -## Example (as JSON) - -```json -{ - "type": "Invoice Event Payment1", - "masked_account_number": "masked_account_number4", - "masked_routing_number": "masked_routing_number4", - "card_brand": "card_brand8", - "card_expiration": "card_expiration4", - "last_four": "last_four2", - "masked_card_number": "masked_card_number6", - "details": "details8", - "kind": "kind6", - "memo": "memo2", - "email": "email8" -} -``` - + +# Invoice Event Payment 1 + +A nested data structure detailing the method of payment + +## Structure + +`InvoiceEventPayment1` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Type` | `*string` | Optional | - | +| `MaskedAccountNumber` | `string` | Required | - | +| `MaskedRoutingNumber` | `string` | Required | - | +| `CardBrand` | `string` | Required | - | +| `CardExpiration` | `*string` | Optional | - | +| `LastFour` | `models.Optional[string]` | Optional | - | +| `MaskedCardNumber` | `string` | Required | - | +| `Details` | `*string` | Required | - | +| `Kind` | `string` | Required | - | +| `Memo` | `*string` | Required | - | +| `Email` | `string` | Required | - | + +## Example (as JSON) + +```json +{ + "type": "Invoice Event Payment1", + "masked_account_number": "masked_account_number4", + "masked_routing_number": "masked_routing_number4", + "card_brand": "card_brand8", + "card_expiration": "card_expiration4", + "last_four": "last_four2", + "masked_card_number": "masked_card_number6", + "details": "details8", + "kind": "kind6", + "memo": "memo2", + "email": "email8" +} +``` + diff --git a/doc/models/invoice-event-payment-method.md b/doc/models/invoice-event-payment-method.md index 1a53670f..2b222fad 100644 --- a/doc/models/invoice-event-payment-method.md +++ b/doc/models/invoice-event-payment-method.md @@ -1,17 +1,17 @@ - -# Invoice Event Payment Method - -## Enumeration - -`InvoiceEventPaymentMethod` - -## Fields - -| Name | -| --- | -| `APPLEPAY` | -| `BANKACCOUNT` | -| `CREDITCARD` | -| `EXTERNAL` | -| `PAYPALACCOUNT` | - + +# Invoice Event Payment Method + +## Enumeration + +`InvoiceEventPaymentMethod` + +## Fields + +| Name | +| --- | +| `APPLEPAY` | +| `BANKACCOUNT` | +| `CREDITCARD` | +| `EXTERNAL` | +| `PAYPALACCOUNT` | + diff --git a/doc/models/invoice-event-payment.md b/doc/models/invoice-event-payment.md index 948c56ae..d9c09e97 100644 --- a/doc/models/invoice-event-payment.md +++ b/doc/models/invoice-event-payment.md @@ -1,37 +1,37 @@ - -# Invoice Event Payment - -A nested data structure detailing the method of payment - -## Structure - -`InvoiceEventPayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Type` | `*string` | Optional | - | -| `MaskedAccountNumber` | `*string` | Optional | - | -| `MaskedRoutingNumber` | `*string` | Optional | - | -| `CardBrand` | `*string` | Optional | - | -| `CardExpiration` | `*string` | Optional | - | -| `LastFour` | `Optional[string]` | Optional | - | -| `MaskedCardNumber` | `*string` | Optional | - | -| `Details` | `Optional[string]` | Optional | - | -| `Kind` | `*string` | Optional | - | -| `Memo` | `Optional[string]` | Optional | - | -| `Email` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "type": "Invoice Event Payment", - "masked_account_number": "masked_account_number8", - "masked_routing_number": "masked_routing_number8", - "card_brand": "card_brand4", - "card_expiration": "card_expiration2" -} -``` - + +# Invoice Event Payment + +A nested data structure detailing the method of payment + +## Structure + +`InvoiceEventPayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Type` | `*string` | Optional | - | +| `MaskedAccountNumber` | `*string` | Optional | - | +| `MaskedRoutingNumber` | `*string` | Optional | - | +| `CardBrand` | `*string` | Optional | - | +| `CardExpiration` | `*string` | Optional | - | +| `LastFour` | `models.Optional[string]` | Optional | - | +| `MaskedCardNumber` | `*string` | Optional | - | +| `Details` | `models.Optional[string]` | Optional | - | +| `Kind` | `*string` | Optional | - | +| `Memo` | `models.Optional[string]` | Optional | - | +| `Email` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "type": "Invoice Event Payment", + "masked_account_number": "masked_account_number8", + "masked_routing_number": "masked_routing_number8", + "card_brand": "card_brand4", + "card_expiration": "card_expiration2" +} +``` + diff --git a/doc/models/invoice-event-type.md b/doc/models/invoice-event-type.md index ff7d9c78..fea1486a 100644 --- a/doc/models/invoice-event-type.md +++ b/doc/models/invoice-event-type.md @@ -1,28 +1,28 @@ - -# Invoice Event Type - -Invoice Event Type - -## Enumeration - -`InvoiceEventType` - -## Fields - -| Name | -| --- | -| `ISSUEINVOICE` | -| `APPLYCREDITNOTE` | -| `CREATECREDITNOTE` | -| `APPLYPAYMENT` | -| `APPLYDEBITNOTE` | -| `REFUNDINVOICE` | -| `VOIDINVOICE` | -| `VOIDREMAINDER` | -| `BACKPORTINVOICE` | -| `CHANGEINVOICESTATUS` | -| `CHANGEINVOICECOLLECTIONMETHOD` | -| `REMOVEPAYMENT` | -| `FAILEDPAYMENT` | -| `CHANGECHARGEBACKSTATUS` | - + +# Invoice Event Type + +Invoice Event Type + +## Enumeration + +`InvoiceEventType` + +## Fields + +| Name | +| --- | +| `ISSUEINVOICE` | +| `APPLYCREDITNOTE` | +| `CREATECREDITNOTE` | +| `APPLYPAYMENT` | +| `APPLYDEBITNOTE` | +| `REFUNDINVOICE` | +| `VOIDINVOICE` | +| `VOIDREMAINDER` | +| `BACKPORTINVOICE` | +| `CHANGEINVOICESTATUS` | +| `CHANGEINVOICECOLLECTIONMETHOD` | +| `REMOVEPAYMENT` | +| `FAILEDPAYMENT` | +| `CHANGECHARGEBACKSTATUS` | + diff --git a/doc/models/invoice-event.md b/doc/models/invoice-event.md index 4b6f3e48..839b2790 100644 --- a/doc/models/invoice-event.md +++ b/doc/models/invoice-event.md @@ -1,41 +1,55 @@ - -# Invoice Event - -## Structure - -`InvoiceEvent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `EventType` | [`*models.InvoiceEventType`](../../doc/models/invoice-event-type.md) | Optional | Invoice Event Type | -| `EventData` | [`*models.InvoiceEventData`](../../doc/models/invoice-event-data.md) | Optional | The event data is the data that, when combined with the command, results in the output invoice found in the invoice field. | -| `Timestamp` | `*time.Time` | Optional | - | -| `Invoice` | [`*models.Invoice`](../../doc/models/invoice.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 78, - "event_type": "void_invoice", - "event_data": { - "uid": "uid6", - "credit_note_number": "credit_note_number0", - "credit_note_uid": "credit_note_uid0", - "original_amount": "original_amount0", - "applied_amount": "applied_amount2" - }, - "timestamp": "2016-03-13T12:52:32.123Z", - "invoice": { - "id": 166, - "uid": "uid6", - "site_id": 92, - "customer_id": 204, - "subscription_id": 20 - } -} -``` - + +# Invoice Event + +## Structure + +`InvoiceEvent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `EventType` | [`*models.InvoiceEventType`](../../doc/models/invoice-event-type.md) | Optional | Invoice Event Type | +| `EventData` | [`*models.InvoiceEventEventData`](../../doc/models/containers/invoice-event-event-data.md) | Optional | This is a container for any-of cases. | +| `Timestamp` | `*time.Time` | Optional | - | +| `Invoice` | [`*models.Invoice`](../../doc/models/invoice.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 78, + "event_type": "void_invoice", + "event_data": { + "uid": "uid2", + "credit_note_number": "credit_note_number4", + "credit_note_uid": "credit_note_uid4", + "original_amount": "original_amount6", + "applied_amount": "applied_amount6", + "transaction_time": "2016-03-13T12:52:32.123Z", + "memo": "memo6", + "role": "role4", + "consolidated_invoice": false, + "applied_credit_notes": [ + { + "uid": "uid4", + "number": "number8" + }, + { + "uid": "uid4", + "number": "number8" + } + ] + }, + "timestamp": "2016-03-13T12:52:32.123Z", + "invoice": { + "id": 166, + "uid": "uid6", + "site_id": 92, + "customer_id": 204, + "subscription_id": 20 + } +} +``` + diff --git a/doc/models/invoice-issued.md b/doc/models/invoice-issued.md new file mode 100644 index 00000000..2f0cd37b --- /dev/null +++ b/doc/models/invoice-issued.md @@ -0,0 +1,57 @@ + +# Invoice Issued + +## Structure + +`InvoiceIssued` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `string` | Required | - | +| `Number` | `string` | Required | - | +| `Role` | `string` | Required | - | +| `DueDate` | `time.Time` | Required | - | +| `IssueDate` | `time.Time` | Required | - | +| `PaidDate` | `time.Time` | Required | - | +| `DueAmount` | `string` | Required | - | +| `PaidAmount` | `string` | Required | - | +| `TaxAmount` | `string` | Required | - | +| `RefundAmount` | `string` | Required | - | +| `TotalAmount` | `string` | Required | - | +| `StatusAmount` | `string` | Required | - | +| `ProductName` | `string` | Required | - | +| `ConsolidationLevel` | `string` | Required | - | +| `LineItems` | [`[]models.InvoiceLineItemEventData`](../../doc/models/invoice-line-item-event-data.md) | Required | - | + +## Example (as JSON) + +```json +{ + "uid": "uid4", + "number": "number8", + "role": "role2", + "due_date": "2016-03-13T12:52:32.123Z", + "issue_date": "2016-03-13T12:52:32.123Z", + "paid_date": "2016-03-13T12:52:32.123Z", + "due_amount": "due_amount6", + "paid_amount": "paid_amount4", + "tax_amount": "tax_amount2", + "refund_amount": "refund_amount0", + "total_amount": "total_amount0", + "status_amount": "status_amount4", + "product_name": "product_name0", + "consolidation_level": "consolidation_level4", + "line_items": [ + { + "uid": "uid8", + "title": "title4", + "description": "description8", + "quantity": 102, + "quantity_delta": 204 + } + ] +} +``` + diff --git a/doc/models/invoice-line-item-component-cost-data.md b/doc/models/invoice-line-item-component-cost-data.md index 5168aa78..635a9faa 100644 --- a/doc/models/invoice-line-item-component-cost-data.md +++ b/doc/models/invoice-line-item-component-cost-data.md @@ -1,43 +1,43 @@ - -# Invoice Line Item Component Cost Data - -## Structure - -`InvoiceLineItemComponentCostData` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Rates` | [`[]models.ComponentCostData`](../../doc/models/component-cost-data.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "rates": [ - { - "component_code_id": 116, - "price_point_id": 226, - "product_id": 94, - "quantity": "quantity0", - "amount": "amount6" - }, - { - "component_code_id": 116, - "price_point_id": 226, - "product_id": 94, - "quantity": "quantity0", - "amount": "amount6" - }, - { - "component_code_id": 116, - "price_point_id": 226, - "product_id": 94, - "quantity": "quantity0", - "amount": "amount6" - } - ] -} -``` - + +# Invoice Line Item Component Cost Data + +## Structure + +`InvoiceLineItemComponentCostData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Rates` | [`[]models.ComponentCostData`](../../doc/models/component-cost-data.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "rates": [ + { + "component_code_id": 116, + "price_point_id": 226, + "product_id": 94, + "quantity": "quantity0", + "amount": "amount6" + }, + { + "component_code_id": 116, + "price_point_id": 226, + "product_id": 94, + "quantity": "quantity0", + "amount": "amount6" + }, + { + "component_code_id": 116, + "price_point_id": 226, + "product_id": 94, + "quantity": "quantity0", + "amount": "amount6" + } + ] +} +``` + diff --git a/doc/models/invoice-line-item-event-data.md b/doc/models/invoice-line-item-event-data.md new file mode 100644 index 00000000..73f96e27 --- /dev/null +++ b/doc/models/invoice-line-item-event-data.md @@ -0,0 +1,44 @@ + +# Invoice Line Item Event Data + +## Structure + +`InvoiceLineItemEventData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `Title` | `*string` | Optional | - | +| `Description` | `*string` | Optional | - | +| `Quantity` | `*int` | Optional | - | +| `QuantityDelta` | `models.Optional[int]` | Optional | - | +| `UnitPrice` | `*string` | Optional | - | +| `PeriodRangeStart` | `*string` | Optional | - | +| `PeriodRangeEnd` | `*string` | Optional | - | +| `Amount` | `*string` | Optional | - | +| `LineReferences` | `*string` | Optional | - | +| `PricingDetailsIndex` | `models.Optional[int]` | Optional | - | +| `PricingDetails` | [`[]models.InvoiceLineItemPricingDetail`](../../doc/models/invoice-line-item-pricing-detail.md) | Optional | - | +| `TaxCode` | `models.Optional[string]` | Optional | - | +| `TaxAmount` | `*string` | Optional | - | +| `ProductId` | `*int` | Optional | - | +| `ProductPricePointId` | `models.Optional[int]` | Optional | - | +| `PricePointId` | `models.Optional[int]` | Optional | - | +| `ComponentId` | `models.Optional[int]` | Optional | - | +| `BillingScheduleItemId` | `models.Optional[int]` | Optional | - | +| `CustomItem` | `models.Optional[bool]` | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid4", + "title": "title0", + "description": "description6", + "quantity": 40, + "quantity_delta": 114 +} +``` + diff --git a/doc/models/invoice-line-item-pricing-detail.md b/doc/models/invoice-line-item-pricing-detail.md new file mode 100644 index 00000000..546b6eb3 --- /dev/null +++ b/doc/models/invoice-line-item-pricing-detail.md @@ -0,0 +1,23 @@ + +# Invoice Line Item Pricing Detail + +## Structure + +`InvoiceLineItemPricingDetail` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Label` | `*string` | Optional | - | +| `Amount` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "label": "label0", + "amount": "amount2" +} +``` + diff --git a/doc/models/invoice-line-item.md b/doc/models/invoice-line-item.md index 759af568..e3eee0c9 100644 --- a/doc/models/invoice-line-item.md +++ b/doc/models/invoice-line-item.md @@ -1,46 +1,46 @@ - -# Invoice Line Item - -## Structure - -`InvoiceLineItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | Unique identifier for the line item. Useful when cross-referencing the line against individual discounts in the `discounts` or `taxes` lists. | -| `Title` | `*string` | Optional | A short descriptor for the charge or item represented by this line. | -| `Description` | `*string` | Optional | Detailed description for the charge or item represented by this line. May include proration details in plain text.

Note: this string may contain line breaks that are hints for the best display format on the invoice. | -| `Quantity` | `*string` | Optional | The quantity or count of units billed by the line item.

This is a decimal number represented as a string. (See "About Decimal Numbers".) | -| `UnitPrice` | `*string` | Optional | The price per unit for the line item.

When tiered pricing was used (i.e. not every unit was actually priced at the same price) this will be the blended average cost per unit and the `tiered_unit_price` field will be set to `true`. | -| `SubtotalAmount` | `*string` | Optional | The line subtotal, generally calculated as `quantity * unit_price`. This is the canonical amount of record for the line - when rounding differences are in play, `subtotal_amount` takes precedence over the value derived from `quantity * unit_price` (which may not have the proper precision to exactly equal this amount). | -| `DiscountAmount` | `*string` | Optional | The approximate discount applied to just this line.

The value is approximated in cases where rounding errors make it difficult to apportion exactly a total discount among many lines. Several lines may have been summed prior to applying the discount to arrive at `discount_amount` for the invoice - backing that out to the discount on a single line may introduce rounding or precision errors. | -| `TaxAmount` | `*string` | Optional | The approximate tax applied to just this line.

The value is approximated in cases where rounding errors make it difficult to apportion exactly a total tax among many lines. Several lines may have been summed prior to applying the tax rate to arrive at `tax_amount` for the invoice - backing that out to the tax on a single line may introduce rounding or precision errors. | -| `TotalAmount` | `*string` | Optional | The non-canonical total amount for the line.

`subtotal_amount` is the canonical amount for a line. The invoice `total_amount` is derived from the sum of the line `subtotal_amount`s and discounts or taxes applied thereafter. Therefore, due to rounding or precision errors, the sum of line `total_amount`s may not equal the invoice `total_amount`. | -| `TieredUnitPrice` | `*bool` | Optional | When `true`, indicates that the actual pricing scheme for the line was tiered, so the `unit_price` shown is the blended average for all units. | -| `PeriodRangeStart` | `*time.Time` | Optional | Start date for the period covered by this line. The format is `"YYYY-MM-DD"`.

* For periodic charges paid in advance, this date will match the billing date, and the end date will be in the future.
* For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the previous billing, and the end date will be the current billing date.
* For non-periodic charges, this date and the end date will match. | -| `PeriodRangeEnd` | `*time.Time` | Optional | End date for the period covered by this line. The format is `"YYYY-MM-DD"`.

* For periodic charges paid in advance, this date will match the next (future) billing date.
* For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the current billing date.
* For non-periodic charges, this date and the start date will match. | -| `TransactionId` | `*int` | Optional | - | -| `ProductId` | `Optional[int]` | Optional | The ID of the product subscribed when the charge was made.

This may be set even for component charges, so true product-only (non-component) charges will also have a nil `component_id`. | -| `ProductVersion` | `Optional[int]` | Optional | The version of the product subscribed when the charge was made. | -| `ComponentId` | `Optional[int]` | Optional | The ID of the component being billed. Will be `nil` for non-component charges. | -| `PricePointId` | `Optional[int]` | Optional | The price point ID of the component being billed. Will be `nil` for non-component charges. | -| `Hide` | `*bool` | Optional | - | -| `ComponentCostData` | [`Optional[models.InvoiceLineItemComponentCostData]`](../../doc/models/invoice-line-item-component-cost-data.md) | Optional | - | -| `ProductPricePointId` | `Optional[int]` | Optional | The price point ID of the line item's product | -| `CustomItem` | `*bool` | Optional | - | -| `Kind` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid4", - "title": "title0", - "description": "description4", - "quantity": "quantity0", - "unit_price": "unit_price2" -} -``` - + +# Invoice Line Item + +## Structure + +`InvoiceLineItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | Unique identifier for the line item. Useful when cross-referencing the line against individual discounts in the `discounts` or `taxes` lists. | +| `Title` | `*string` | Optional | A short descriptor for the charge or item represented by this line. | +| `Description` | `*string` | Optional | Detailed description for the charge or item represented by this line. May include proration details in plain text.

Note: this string may contain line breaks that are hints for the best display format on the invoice. | +| `Quantity` | `*string` | Optional | The quantity or count of units billed by the line item.

This is a decimal number represented as a string. (See "About Decimal Numbers".) | +| `UnitPrice` | `*string` | Optional | The price per unit for the line item.

When tiered pricing was used (i.e. not every unit was actually priced at the same price) this will be the blended average cost per unit and the `tiered_unit_price` field will be set to `true`. | +| `SubtotalAmount` | `*string` | Optional | The line subtotal, generally calculated as `quantity * unit_price`. This is the canonical amount of record for the line - when rounding differences are in play, `subtotal_amount` takes precedence over the value derived from `quantity * unit_price` (which may not have the proper precision to exactly equal this amount). | +| `DiscountAmount` | `*string` | Optional | The approximate discount applied to just this line.

The value is approximated in cases where rounding errors make it difficult to apportion exactly a total discount among many lines. Several lines may have been summed prior to applying the discount to arrive at `discount_amount` for the invoice - backing that out to the discount on a single line may introduce rounding or precision errors. | +| `TaxAmount` | `*string` | Optional | The approximate tax applied to just this line.

The value is approximated in cases where rounding errors make it difficult to apportion exactly a total tax among many lines. Several lines may have been summed prior to applying the tax rate to arrive at `tax_amount` for the invoice - backing that out to the tax on a single line may introduce rounding or precision errors. | +| `TotalAmount` | `*string` | Optional | The non-canonical total amount for the line.

`subtotal_amount` is the canonical amount for a line. The invoice `total_amount` is derived from the sum of the line `subtotal_amount`s and discounts or taxes applied thereafter. Therefore, due to rounding or precision errors, the sum of line `total_amount`s may not equal the invoice `total_amount`. | +| `TieredUnitPrice` | `*bool` | Optional | When `true`, indicates that the actual pricing scheme for the line was tiered, so the `unit_price` shown is the blended average for all units. | +| `PeriodRangeStart` | `*time.Time` | Optional | Start date for the period covered by this line. The format is `"YYYY-MM-DD"`.

* For periodic charges paid in advance, this date will match the billing date, and the end date will be in the future.
* For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the previous billing, and the end date will be the current billing date.
* For non-periodic charges, this date and the end date will match. | +| `PeriodRangeEnd` | `*time.Time` | Optional | End date for the period covered by this line. The format is `"YYYY-MM-DD"`.

* For periodic charges paid in advance, this date will match the next (future) billing date.
* For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the current billing date.
* For non-periodic charges, this date and the start date will match. | +| `TransactionId` | `*int` | Optional | - | +| `ProductId` | `models.Optional[int]` | Optional | The ID of the product subscribed when the charge was made.

This may be set even for component charges, so true product-only (non-component) charges will also have a nil `component_id`. | +| `ProductVersion` | `models.Optional[int]` | Optional | The version of the product subscribed when the charge was made. | +| `ComponentId` | `models.Optional[int]` | Optional | The ID of the component being billed. Will be `nil` for non-component charges. | +| `PricePointId` | `models.Optional[int]` | Optional | The price point ID of the component being billed. Will be `nil` for non-component charges. | +| `Hide` | `*bool` | Optional | - | +| `ComponentCostData` | [`models.Optional[models.InvoiceLineItemComponentCostData2]`](../../doc/models/containers/invoice-line-item-component-cost-data-2.md) | Optional | This is a container for one-of cases. | +| `ProductPricePointId` | `models.Optional[int]` | Optional | The price point ID of the line item's product | +| `CustomItem` | `*bool` | Optional | - | +| `Kind` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid4", + "title": "title0", + "description": "description4", + "quantity": "quantity0", + "unit_price": "unit_price2" +} +``` + diff --git a/doc/models/invoice-payer-change.md b/doc/models/invoice-payer-change.md index 201fc39d..1e93d4d5 100644 --- a/doc/models/invoice-payer-change.md +++ b/doc/models/invoice-payer-change.md @@ -1,27 +1,27 @@ - -# Invoice Payer Change - -## Structure - -`InvoicePayerChange` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `FirstName` | `*string` | Optional | - | -| `LastName` | `*string` | Optional | - | -| `Organization` | `*string` | Optional | - | -| `Email` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "first_name": "first_name2", - "last_name": "last_name0", - "organization": "organization4", - "email": "email4" -} -``` - + +# Invoice Payer Change + +## Structure + +`InvoicePayerChange` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FirstName` | `*string` | Optional | - | +| `LastName` | `*string` | Optional | - | +| `Organization` | `*string` | Optional | - | +| `Email` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "first_name": "first_name2", + "last_name": "last_name0", + "organization": "organization4", + "email": "email4" +} +``` + diff --git a/doc/models/invoice-payer.md b/doc/models/invoice-payer.md index 192c5ad9..09cb148c 100644 --- a/doc/models/invoice-payer.md +++ b/doc/models/invoice-payer.md @@ -1,30 +1,30 @@ - -# Invoice Payer - -## Structure - -`InvoicePayer` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ChargifyId` | `*int` | Optional | - | -| `FirstName` | `*string` | Optional | - | -| `LastName` | `*string` | Optional | - | -| `Organization` | `Optional[string]` | Optional | - | -| `Email` | `*string` | Optional | - | -| `VatNumber` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "chargify_id": 46, - "first_name": "first_name4", - "last_name": "last_name2", - "organization": "organization8", - "email": "email2" -} -``` - + +# Invoice Payer + +## Structure + +`InvoicePayer` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ChargifyId` | `*int` | Optional | - | +| `FirstName` | `*string` | Optional | - | +| `LastName` | `*string` | Optional | - | +| `Organization` | `models.Optional[string]` | Optional | - | +| `Email` | `*string` | Optional | - | +| `VatNumber` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "chargify_id": 46, + "first_name": "first_name4", + "last_name": "last_name2", + "organization": "organization8", + "email": "email2" +} +``` + diff --git a/doc/models/invoice-payment-application.md b/doc/models/invoice-payment-application.md index 7f46147d..53753c85 100644 --- a/doc/models/invoice-payment-application.md +++ b/doc/models/invoice-payment-application.md @@ -1,25 +1,25 @@ - -# Invoice Payment Application - -## Structure - -`InvoicePaymentApplication` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `InvoiceUid` | `*string` | Optional | Unique identifier for the paid invoice. It has the prefix "inv_" followed by alphanumeric characters. | -| `ApplicationUid` | `*string` | Optional | Unique identifier for the payment. It has the prefix "pmt_" followed by alphanumeric characters. | -| `AppliedAmount` | `*string` | Optional | Dollar amount of the paid invoice. | - -## Example (as JSON) - -```json -{ - "invoice_uid": "invoice_uid2", - "application_uid": "application_uid4", - "applied_amount": "applied_amount6" -} -``` - + +# Invoice Payment Application + +## Structure + +`InvoicePaymentApplication` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `InvoiceUid` | `*string` | Optional | Unique identifier for the paid invoice. It has the prefix "inv_" followed by alphanumeric characters. | +| `ApplicationUid` | `*string` | Optional | Unique identifier for the payment. It has the prefix "pmt_" followed by alphanumeric characters. | +| `AppliedAmount` | `*string` | Optional | Dollar amount of the paid invoice. | + +## Example (as JSON) + +```json +{ + "invoice_uid": "invoice_uid2", + "application_uid": "application_uid4", + "applied_amount": "applied_amount6" +} +``` + diff --git a/doc/models/invoice-payment-method-type.md b/doc/models/invoice-payment-method-type.md index dcf93ab0..0ee3ec2d 100644 --- a/doc/models/invoice-payment-method-type.md +++ b/doc/models/invoice-payment-method-type.md @@ -1,20 +1,20 @@ - -# Invoice Payment Method Type - -The type of payment method used. Defaults to other. - -## Enumeration - -`InvoicePaymentMethodType` - -## Fields - -| Name | -| --- | -| `CREDITCARD` | -| `CHECK` | -| `CASH` | -| `MONEYORDER` | -| `ACH` | -| `OTHER` | - + +# Invoice Payment Method Type + +The type of payment method used. Defaults to other. + +## Enumeration + +`InvoicePaymentMethodType` + +## Fields + +| Name | +| --- | +| `CREDITCARD` | +| `CHECK` | +| `CASH` | +| `MONEYORDER` | +| `ACH` | +| `OTHER` | + diff --git a/doc/models/invoice-payment-method.md b/doc/models/invoice-payment-method.md index 4332049c..c13edd36 100644 --- a/doc/models/invoice-payment-method.md +++ b/doc/models/invoice-payment-method.md @@ -1,32 +1,32 @@ - -# Invoice Payment Method - -## Structure - -`InvoicePaymentMethod` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Details` | `*string` | Optional | - | -| `Kind` | `*string` | Optional | - | -| `Memo` | `*string` | Optional | - | -| `Type` | `*string` | Optional | - | -| `CardBrand` | `*string` | Optional | - | -| `CardExpiration` | `*string` | Optional | - | -| `LastFour` | `Optional[string]` | Optional | - | -| `MaskedCardNumber` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "details": "details8", - "kind": "kind6", - "memo": "memo2", - "type": "type8", - "card_brand": "card_brand8" -} -``` - + +# Invoice Payment Method + +## Structure + +`InvoicePaymentMethod` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Details` | `*string` | Optional | - | +| `Kind` | `*string` | Optional | - | +| `Memo` | `*string` | Optional | - | +| `Type` | `*string` | Optional | - | +| `CardBrand` | `*string` | Optional | - | +| `CardExpiration` | `*string` | Optional | - | +| `LastFour` | `models.Optional[string]` | Optional | - | +| `MaskedCardNumber` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "details": "details8", + "kind": "kind6", + "memo": "memo2", + "type": "type8", + "card_brand": "card_brand8" +} +``` + diff --git a/doc/models/invoice-payment-type.md b/doc/models/invoice-payment-type.md index aa77d6fa..98dc2508 100644 --- a/doc/models/invoice-payment-type.md +++ b/doc/models/invoice-payment-type.md @@ -1,18 +1,18 @@ - -# Invoice Payment Type - -The type of payment to be applied to an Invoice. Defaults to external. - -## Enumeration - -`InvoicePaymentType` - -## Fields - -| Name | -| --- | -| `EXTERNAL` | -| `PREPAYMENT` | -| `SERVICECREDIT` | -| `PAYMENT` | - + +# Invoice Payment Type + +The type of payment to be applied to an Invoice. Defaults to external. + +## Enumeration + +`InvoicePaymentType` + +## Fields + +| Name | +| --- | +| `EXTERNAL` | +| `PREPAYMENT` | +| `SERVICECREDIT` | +| `PAYMENT` | + diff --git a/doc/models/invoice-payment.md b/doc/models/invoice-payment.md index a3ac1b2f..1b424dc5 100644 --- a/doc/models/invoice-payment.md +++ b/doc/models/invoice-payment.md @@ -1,40 +1,40 @@ - -# Invoice Payment - -## Structure - -`InvoicePayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TransactionTime` | `*time.Time` | Optional | - | -| `Memo` | `*string` | Optional | - | -| `OriginalAmount` | `*string` | Optional | - | -| `AppliedAmount` | `*string` | Optional | - | -| `PaymentMethod` | [`*models.InvoicePaymentMethod`](../../doc/models/invoice-payment-method.md) | Optional | - | -| `TransactionId` | `*int` | Optional | - | -| `Prepayment` | `*bool` | Optional | - | -| `GatewayHandle` | `Optional[string]` | Optional | - | -| `GatewayUsed` | `*string` | Optional | - | -| `GatewayTransactionId` | `Optional[string]` | Optional | The transaction ID for the payment as returned from the payment gateway | - -## Example (as JSON) - -```json -{ - "transaction_time": "2016-03-13T12:52:32.123Z", - "memo": "memo6", - "original_amount": "original_amount6", - "applied_amount": "applied_amount6", - "payment_method": { - "details": "details0", - "kind": "kind8", - "memo": "memo4", - "type": "type0", - "card_brand": "card_brand6" - } -} -``` - + +# Invoice Payment + +## Structure + +`InvoicePayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TransactionTime` | `*time.Time` | Optional | - | +| `Memo` | `*string` | Optional | - | +| `OriginalAmount` | `*string` | Optional | - | +| `AppliedAmount` | `*string` | Optional | - | +| `PaymentMethod` | [`*models.InvoicePaymentMethod`](../../doc/models/invoice-payment-method.md) | Optional | - | +| `TransactionId` | `*int` | Optional | - | +| `Prepayment` | `*bool` | Optional | - | +| `GatewayHandle` | `models.Optional[string]` | Optional | - | +| `GatewayUsed` | `*string` | Optional | - | +| `GatewayTransactionId` | `models.Optional[string]` | Optional | The transaction ID for the payment as returned from the payment gateway | + +## Example (as JSON) + +```json +{ + "transaction_time": "2016-03-13T12:52:32.123Z", + "memo": "memo6", + "original_amount": "original_amount6", + "applied_amount": "applied_amount6", + "payment_method": { + "details": "details0", + "kind": "kind8", + "memo": "memo4", + "type": "type0", + "card_brand": "card_brand6" + } +} +``` + diff --git a/doc/models/invoice-pre-payment.md b/doc/models/invoice-pre-payment.md index d0008ab0..bb61b6f5 100644 --- a/doc/models/invoice-pre-payment.md +++ b/doc/models/invoice-pre-payment.md @@ -1,25 +1,25 @@ - -# Invoice Pre Payment - -## Structure - -`InvoicePrePayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SubscriptionId` | `*int` | Optional | The subscription id for the prepayment account | -| `AmountInCents` | `*int64` | Optional | The amount in cents of the prepayment that was created as a result of this payment. | -| `EndingBalanceInCents` | `*int64` | Optional | The total balance of the prepayment account for this subscription including any prior prepayments | - -## Example (as JSON) - -```json -{ - "subscription_id": 180, - "amount_in_cents": 100, - "ending_balance_in_cents": 60 -} -``` - + +# Invoice Pre Payment + +## Structure + +`InvoicePrePayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionId` | `*int` | Optional | The subscription id for the prepayment account | +| `AmountInCents` | `*int64` | Optional | The amount in cents of the prepayment that was created as a result of this payment. | +| `EndingBalanceInCents` | `*int64` | Optional | The total balance of the prepayment account for this subscription including any prior prepayments | + +## Example (as JSON) + +```json +{ + "subscription_id": 180, + "amount_in_cents": 100, + "ending_balance_in_cents": 60 +} +``` + diff --git a/doc/models/invoice-previous-balance.md b/doc/models/invoice-previous-balance.md index a5b15144..e4d0b8ce 100644 --- a/doc/models/invoice-previous-balance.md +++ b/doc/models/invoice-previous-balance.md @@ -1,29 +1,29 @@ - -# Invoice Previous Balance - -## Structure - -`InvoicePreviousBalance` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CapturedAt` | `*time.Time` | Optional | - | -| `Invoices` | [`[]models.InvoiceBalanceItem`](../../doc/models/invoice-balance-item.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "captured_at": "2016-03-13T12:52:32.123Z", - "invoices": [ - { - "uid": "uid6", - "number": "number6", - "outstanding_amount": "outstanding_amount8" - } - ] -} -``` - + +# Invoice Previous Balance + +## Structure + +`InvoicePreviousBalance` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CapturedAt` | `*time.Time` | Optional | - | +| `Invoices` | [`[]models.InvoiceBalanceItem`](../../doc/models/invoice-balance-item.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "captured_at": "2016-03-13T12:52:32.123Z", + "invoices": [ + { + "uid": "uid6", + "number": "number6", + "outstanding_amount": "outstanding_amount8" + } + ] +} +``` + diff --git a/doc/models/invoice-refund.md b/doc/models/invoice-refund.md index c7d70338..4f099451 100644 --- a/doc/models/invoice-refund.md +++ b/doc/models/invoice-refund.md @@ -1,32 +1,32 @@ - -# Invoice Refund - -## Structure - -`InvoiceRefund` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TransactionId` | `*int` | Optional | - | -| `PaymentId` | `*int` | Optional | - | -| `Memo` | `*string` | Optional | - | -| `OriginalAmount` | `*string` | Optional | - | -| `AppliedAmount` | `*string` | Optional | - | -| `GatewayTransactionId` | `Optional[string]` | Optional | The transaction ID for the refund as returned from the payment gateway | -| `GatewayUsed` | `*string` | Optional | - | -| `GatewayHandle` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "transaction_id": 172, - "payment_id": 42, - "memo": "memo6", - "original_amount": "original_amount6", - "applied_amount": "applied_amount6" -} -``` - + +# Invoice Refund + +## Structure + +`InvoiceRefund` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TransactionId` | `*int` | Optional | - | +| `PaymentId` | `*int` | Optional | - | +| `Memo` | `*string` | Optional | - | +| `OriginalAmount` | `*string` | Optional | - | +| `AppliedAmount` | `*string` | Optional | - | +| `GatewayTransactionId` | `models.Optional[string]` | Optional | The transaction ID for the refund as returned from the payment gateway | +| `GatewayUsed` | `*string` | Optional | - | +| `GatewayHandle` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "transaction_id": 172, + "payment_id": 42, + "memo": "memo6", + "original_amount": "original_amount6", + "applied_amount": "applied_amount6" +} +``` + diff --git a/doc/models/invoice-response.md b/doc/models/invoice-response.md index ebb6d559..44aad1f9 100644 --- a/doc/models/invoice-response.md +++ b/doc/models/invoice-response.md @@ -1,31 +1,31 @@ - -# Invoice Response - -## Structure - -`InvoiceResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Invoice` | [`models.Invoice`](../../doc/models/invoice.md) | Required | - | - -## Example (as JSON) - -```json -{ - "invoice": { - "issue_date": "2024-01-01", - "due_date": "2024-01-01", - "paid_date": "2024-01-01", - "collection_method": "automatic", - "id": 166, - "uid": "uid6", - "site_id": 92, - "customer_id": 204, - "subscription_id": 20 - } -} -``` - + +# Invoice Response + +## Structure + +`InvoiceResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Invoice` | [`models.Invoice`](../../doc/models/invoice.md) | Required | - | + +## Example (as JSON) + +```json +{ + "invoice": { + "issue_date": "2024-01-01", + "due_date": "2024-01-01", + "paid_date": "2024-01-01", + "collection_method": "automatic", + "id": 166, + "uid": "uid6", + "site_id": 92, + "customer_id": 204, + "subscription_id": 20 + } +} +``` + diff --git a/doc/models/invoice-role.md b/doc/models/invoice-role.md index bbfa6721..2f75a786 100644 --- a/doc/models/invoice-role.md +++ b/doc/models/invoice-role.md @@ -1,22 +1,22 @@ - -# Invoice Role - -## Enumeration - -`InvoiceRole` - -## Fields - -| Name | -| --- | -| `UNSET` | -| `SIGNUP` | -| `RENEWAL` | -| `USAGE` | -| `REACTIVATION` | -| `PRORATION` | -| `MIGRATION` | -| `ADHOC` | -| `BACKPORT` | -| `BACKPORTBALANCERECONCILIATION` | - + +# Invoice Role + +## Enumeration + +`InvoiceRole` + +## Fields + +| Name | +| --- | +| `UNSET` | +| `SIGNUP` | +| `RENEWAL` | +| `USAGE` | +| `REACTIVATION` | +| `PRORATION` | +| `MIGRATION` | +| `ADHOC` | +| `BACKPORT` | +| `BACKPORTBALANCERECONCILIATION` | + diff --git a/doc/models/invoice-seller.md b/doc/models/invoice-seller.md index 5c71141d..20dc4889 100644 --- a/doc/models/invoice-seller.md +++ b/doc/models/invoice-seller.md @@ -1,35 +1,35 @@ - -# Invoice Seller - -Information about the seller (merchant) listed on the masthead of the invoice. - -## Structure - -`InvoiceSeller` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `*string` | Optional | - | -| `Address` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | - | -| `Phone` | `*string` | Optional | - | -| `LogoUrl` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "name": "name0", - "address": { - "street": "street6", - "line2": "line20", - "city": "city6", - "state": "state2", - "zip": "zip0" - }, - "phone": "phone0", - "logo_url": "logo_url0" -} -``` - + +# Invoice Seller + +Information about the seller (merchant) listed on the masthead of the invoice. + +## Structure + +`InvoiceSeller` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `*string` | Optional | - | +| `Address` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | - | +| `Phone` | `*string` | Optional | - | +| `LogoUrl` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name0", + "address": { + "street": "street6", + "line2": "line20", + "city": "city6", + "state": "state2", + "zip": "zip0" + }, + "phone": "phone0", + "logo_url": "logo_url0" +} +``` + diff --git a/doc/models/invoice-sort-field.md b/doc/models/invoice-sort-field.md index 24de9e6d..5e1c6a2b 100644 --- a/doc/models/invoice-sort-field.md +++ b/doc/models/invoice-sort-field.md @@ -1,26 +1,26 @@ - -# Invoice Sort Field - -## Enumeration - -`InvoiceSortField` - -## Fields - -| Name | -| --- | -| `STATUS` | -| `TOTALAMOUNT` | -| `DUEAMOUNT` | -| `CREATEDAT` | -| `UPDATEDAT` | -| `ISSUEDATE` | -| `DUEDATE` | -| `NUMBER` | - -## Example - -``` -total_amount -``` - + +# Invoice Sort Field + +## Enumeration + +`InvoiceSortField` + +## Fields + +| Name | +| --- | +| `STATUS` | +| `TOTALAMOUNT` | +| `DUEAMOUNT` | +| `CREATEDAT` | +| `UPDATEDAT` | +| `ISSUEDATE` | +| `DUEDATE` | +| `NUMBER` | + +## Example + +``` +total_amount +``` + diff --git a/doc/models/invoice-status.md b/doc/models/invoice-status.md index e20a446c..4e690dea 100644 --- a/doc/models/invoice-status.md +++ b/doc/models/invoice-status.md @@ -1,20 +1,20 @@ - -# Invoice Status - -The current status of the invoice. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. - -## Enumeration - -`InvoiceStatus` - -## Fields - -| Name | -| --- | -| `DRAFT` | -| `OPEN` | -| `PAID` | -| `PENDING` | -| `VOIDED` | -| `CANCELED` | - + +# Invoice Status + +The current status of the invoice. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. + +## Enumeration + +`InvoiceStatus` + +## Fields + +| Name | +| --- | +| `DRAFT` | +| `OPEN` | +| `PAID` | +| `PENDING` | +| `VOIDED` | +| `CANCELED` | + diff --git a/doc/models/invoice-tax-breakout.md b/doc/models/invoice-tax-breakout.md index 8ee9615a..7112ce03 100644 --- a/doc/models/invoice-tax-breakout.md +++ b/doc/models/invoice-tax-breakout.md @@ -1,27 +1,27 @@ - -# Invoice Tax Breakout - -## Structure - -`InvoiceTaxBreakout` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `TaxableAmount` | `*string` | Optional | - | -| `TaxAmount` | `*string` | Optional | - | -| `TaxExemptAmount` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid2", - "taxable_amount": "taxable_amount6", - "tax_amount": "tax_amount6", - "tax_exempt_amount": "tax_exempt_amount2" -} -``` - + +# Invoice Tax Breakout + +## Structure + +`InvoiceTaxBreakout` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `TaxableAmount` | `*string` | Optional | - | +| `TaxAmount` | `*string` | Optional | - | +| `TaxExemptAmount` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid2", + "taxable_amount": "taxable_amount6", + "tax_amount": "tax_amount6", + "tax_exempt_amount": "tax_exempt_amount2" +} +``` + diff --git a/doc/models/invoice-tax-component-breakout.md b/doc/models/invoice-tax-component-breakout.md index 956a1ac3..ccac38a3 100644 --- a/doc/models/invoice-tax-component-breakout.md +++ b/doc/models/invoice-tax-component-breakout.md @@ -1,27 +1,27 @@ - -# Invoice Tax Component Breakout - -## Structure - -`InvoiceTaxComponentBreakout` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TaxRuleId` | `*int` | Optional | - | -| `Percentage` | `*string` | Optional | - | -| `CountryCode` | `*string` | Optional | - | -| `SubdivisionCode` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "tax_rule_id": 226, - "percentage": "percentage0", - "country_code": "country_code8", - "subdivision_code": "subdivision_code6" -} -``` - + +# Invoice Tax Component Breakout + +## Structure + +`InvoiceTaxComponentBreakout` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TaxRuleId` | `*int` | Optional | - | +| `Percentage` | `*string` | Optional | - | +| `CountryCode` | `*string` | Optional | - | +| `SubdivisionCode` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "tax_rule_id": 226, + "percentage": "percentage0", + "country_code": "country_code8", + "subdivision_code": "subdivision_code6" +} +``` + diff --git a/doc/models/invoice-tax.md b/doc/models/invoice-tax.md index 6bdc4ab7..b52311f5 100644 --- a/doc/models/invoice-tax.md +++ b/doc/models/invoice-tax.md @@ -1,35 +1,35 @@ - -# Invoice Tax - -## Structure - -`InvoiceTax` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `Title` | `*string` | Optional | - | -| `Description` | `Optional[string]` | Optional | - | -| `SourceType` | [`*models.ProformaInvoiceTaxSourceType`](../../doc/models/proforma-invoice-tax-source-type.md) | Optional | - | -| `SourceId` | `*int` | Optional | - | -| `Percentage` | `*string` | Optional | - | -| `TaxableAmount` | `*string` | Optional | - | -| `TaxAmount` | `*string` | Optional | - | -| `TransactionId` | `*int` | Optional | - | -| `LineItemBreakouts` | [`[]models.InvoiceTaxBreakout`](../../doc/models/invoice-tax-breakout.md) | Optional | - | -| `TaxComponentBreakouts` | [`[]models.InvoiceTaxComponentBreakout`](../../doc/models/invoice-tax-component-breakout.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid8", - "title": "title6", - "description": "description2", - "source_type": "Tax", - "source_id": 164 -} -``` - + +# Invoice Tax + +## Structure + +`InvoiceTax` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `Title` | `*string` | Optional | - | +| `Description` | `models.Optional[string]` | Optional | - | +| `SourceType` | [`*models.ProformaInvoiceTaxSourceType`](../../doc/models/proforma-invoice-tax-source-type.md) | Optional | - | +| `SourceId` | `*int` | Optional | - | +| `Percentage` | `*string` | Optional | - | +| `TaxableAmount` | `*string` | Optional | - | +| `TaxAmount` | `*string` | Optional | - | +| `TransactionId` | `*int` | Optional | - | +| `LineItemBreakouts` | [`[]models.InvoiceTaxBreakout`](../../doc/models/invoice-tax-breakout.md) | Optional | - | +| `TaxComponentBreakouts` | [`[]models.InvoiceTaxComponentBreakout`](../../doc/models/invoice-tax-component-breakout.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid8", + "title": "title6", + "description": "description2", + "source_type": "Tax", + "source_id": 164 +} +``` + diff --git a/doc/models/invoice.md b/doc/models/invoice.md index 83565790..8e21ddc0 100644 --- a/doc/models/invoice.md +++ b/doc/models/invoice.md @@ -1,80 +1,80 @@ - -# Invoice - -## Structure - -`Invoice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int64` | Optional | - | -| `Uid` | `*string` | Optional | Unique identifier for the invoice. It is generated automatically by Chargify and has the prefix "inv_" followed by alphanumeric characters. | -| `SiteId` | `*int` | Optional | ID of the site to which the invoice belongs. | -| `CustomerId` | `*int` | Optional | ID of the customer to which the invoice belongs. | -| `SubscriptionId` | `*int` | Optional | ID of the subscription that generated the invoice. | -| `Number` | `*string` | Optional | A unique, identifying string that appears on the invoice and in places the invoice is referenced.

While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. | -| `SequenceNumber` | `*int` | Optional | A monotonically increasing number assigned to invoices as they are created. This number is unique within a site and can be used to sort and order invoices. | -| `TransactionTime` | `*time.Time` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `UpdatedAt` | `*time.Time` | Optional | - | -| `IssueDate` | `*time.Time` | Optional | Date the invoice was issued to the customer. This is the date that the invoice was made available for payment.

The format is `"YYYY-MM-DD"`. | -| `DueDate` | `*time.Time` | Optional | Date the invoice is due.

The format is `"YYYY-MM-DD"`. | -| `PaidDate` | `Optional[time.Time]` | Optional | Date the invoice became fully paid.

If partial payments are applied to the invoice, this date will not be present until payment has been made in full.

The format is `"YYYY-MM-DD"`. | -| `Status` | [`*models.InvoiceStatus`](../../doc/models/invoice-status.md) | Optional | The current status of the invoice. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. | -| `Role` | [`*models.InvoiceRole`](../../doc/models/invoice-role.md) | Optional | - | -| `ParentInvoiceId` | `Optional[int]` | Optional | - | -| `CollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | -| `PaymentInstructions` | `*string` | Optional | A message that is printed on the invoice when it is marked for remittance collection. It is intended to describe to the customer how they may make payment, and is configured by the merchant. | -| `Currency` | `*string` | Optional | The ISO 4217 currency code (3 character string) representing the currency of invoice transaction. | -| `ConsolidationLevel` | [`*models.InvoiceConsolidationLevel`](../../doc/models/invoice-consolidation-level.md) | Optional | Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values:

* "none": A normal invoice with no consolidation.
* "child": An invoice segment which has been combined into a consolidated invoice.
* "parent": A consolidated invoice, whose contents are composed of invoice segments.

"Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments.

See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). | -| `ParentInvoiceUid` | `Optional[string]` | Optional | For invoices with `consolidation_level` of `child`, this specifies the UID of the parent (consolidated) invoice. | -| `SubscriptionGroupId` | `Optional[int]` | Optional | - | -| `ParentInvoiceNumber` | `Optional[int]` | Optional | For invoices with `consolidation_level` of `child`, this specifies the number of the parent (consolidated) invoice. | -| `GroupPrimarySubscriptionId` | `Optional[int]` | Optional | For invoices with `consolidation_level` of `parent`, this specifies the ID of the subscription which was the primary subscription of the subscription group that generated the invoice. | -| `ProductName` | `*string` | Optional | The name of the product subscribed when the invoice was generated. | -| `ProductFamilyName` | `*string` | Optional | The name of the product family subscribed when the invoice was generated. | -| `Seller` | [`*models.InvoiceSeller`](../../doc/models/invoice-seller.md) | Optional | Information about the seller (merchant) listed on the masthead of the invoice. | -| `Customer` | [`*models.InvoiceCustomer`](../../doc/models/invoice-customer.md) | Optional | Information about the customer who is owner or recipient the invoiced subscription. | -| `Payer` | [`*models.InvoicePayer`](../../doc/models/invoice-payer.md) | Optional | - | -| `RecipientEmails` | `[]string` | Optional | **Constraints**: *Maximum Items*: `5` | -| `NetTerms` | `*int` | Optional | - | -| `Memo` | `*string` | Optional | The memo printed on invoices of any collection type. This message is in control of the merchant. | -| `BillingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | The invoice billing address. | -| `ShippingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | The invoice shipping address. | -| `SubtotalAmount` | `*string` | Optional | Subtotal of the invoice, which is the sum of all line items before discounts or taxes. | -| `DiscountAmount` | `*string` | Optional | Total discount applied to the invoice. | -| `TaxAmount` | `*string` | Optional | Total tax on the invoice. | -| `TotalAmount` | `*string` | Optional | The invoice total, which is `subtotal_amount - discount_amount + tax_amount`.' | -| `CreditAmount` | `*string` | Optional | The amount of credit (from credit notes) applied to this invoice.

Credits offset the amount due from the customer. | -| `RefundAmount` | `*string` | Optional | - | -| `PaidAmount` | `*string` | Optional | The amount paid on the invoice by the customer. | -| `DueAmount` | `*string` | Optional | Amount due on the invoice, which is `total_amount - credit_amount - paid_amount`. | -| `LineItems` | [`[]models.InvoiceLineItem`](../../doc/models/invoice-line-item.md) | Optional | Line items on the invoice. | -| `Discounts` | [`[]models.InvoiceDiscount`](../../doc/models/invoice-discount.md) | Optional | - | -| `Taxes` | [`[]models.InvoiceTax`](../../doc/models/invoice-tax.md) | Optional | - | -| `Credits` | [`[]models.InvoiceCredit`](../../doc/models/invoice-credit.md) | Optional | - | -| `Refunds` | [`[]models.InvoiceRefund`](../../doc/models/invoice-refund.md) | Optional | - | -| `Payments` | [`[]models.InvoicePayment`](../../doc/models/invoice-payment.md) | Optional | - | -| `CustomFields` | [`[]models.InvoiceCustomField`](../../doc/models/invoice-custom-field.md) | Optional | - | -| `DisplaySettings` | [`*models.InvoiceDisplaySettings`](../../doc/models/invoice-display-settings.md) | Optional | - | -| `PublicUrl` | `*string` | Optional | The public URL of the invoice | -| `PreviousBalanceData` | [`*models.InvoicePreviousBalance`](../../doc/models/invoice-previous-balance.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "issue_date": "2024-01-01", - "due_date": "2024-01-01", - "paid_date": "2024-01-01", - "collection_method": "automatic", - "id": 252, - "uid": "uid0", - "site_id": 178, - "customer_id": 34, - "subscription_id": 106 -} -``` - + +# Invoice + +## Structure + +`Invoice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int64` | Optional | - | +| `Uid` | `*string` | Optional | Unique identifier for the invoice. It is generated automatically by Chargify and has the prefix "inv_" followed by alphanumeric characters. | +| `SiteId` | `*int` | Optional | ID of the site to which the invoice belongs. | +| `CustomerId` | `*int` | Optional | ID of the customer to which the invoice belongs. | +| `SubscriptionId` | `*int` | Optional | ID of the subscription that generated the invoice. | +| `Number` | `*string` | Optional | A unique, identifying string that appears on the invoice and in places the invoice is referenced.

While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. | +| `SequenceNumber` | `*int` | Optional | A monotonically increasing number assigned to invoices as they are created. This number is unique within a site and can be used to sort and order invoices. | +| `TransactionTime` | `*time.Time` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `UpdatedAt` | `*time.Time` | Optional | - | +| `IssueDate` | `*time.Time` | Optional | Date the invoice was issued to the customer. This is the date that the invoice was made available for payment.

The format is `"YYYY-MM-DD"`. | +| `DueDate` | `*time.Time` | Optional | Date the invoice is due.

The format is `"YYYY-MM-DD"`. | +| `PaidDate` | `models.Optional[time.Time]` | Optional | Date the invoice became fully paid.

If partial payments are applied to the invoice, this date will not be present until payment has been made in full.

The format is `"YYYY-MM-DD"`. | +| `Status` | [`*models.InvoiceStatus`](../../doc/models/invoice-status.md) | Optional | The current status of the invoice. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. | +| `Role` | [`*models.InvoiceRole`](../../doc/models/invoice-role.md) | Optional | - | +| `ParentInvoiceId` | `models.Optional[int]` | Optional | - | +| `CollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | +| `PaymentInstructions` | `*string` | Optional | A message that is printed on the invoice when it is marked for remittance collection. It is intended to describe to the customer how they may make payment, and is configured by the merchant. | +| `Currency` | `*string` | Optional | The ISO 4217 currency code (3 character string) representing the currency of invoice transaction. | +| `ConsolidationLevel` | [`*models.InvoiceConsolidationLevel`](../../doc/models/invoice-consolidation-level.md) | Optional | Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values:

* "none": A normal invoice with no consolidation.
* "child": An invoice segment which has been combined into a consolidated invoice.
* "parent": A consolidated invoice, whose contents are composed of invoice segments.

"Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments.

See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). | +| `ParentInvoiceUid` | `models.Optional[string]` | Optional | For invoices with `consolidation_level` of `child`, this specifies the UID of the parent (consolidated) invoice. | +| `SubscriptionGroupId` | `models.Optional[int]` | Optional | - | +| `ParentInvoiceNumber` | `models.Optional[int]` | Optional | For invoices with `consolidation_level` of `child`, this specifies the number of the parent (consolidated) invoice. | +| `GroupPrimarySubscriptionId` | `models.Optional[int]` | Optional | For invoices with `consolidation_level` of `parent`, this specifies the ID of the subscription which was the primary subscription of the subscription group that generated the invoice. | +| `ProductName` | `*string` | Optional | The name of the product subscribed when the invoice was generated. | +| `ProductFamilyName` | `*string` | Optional | The name of the product family subscribed when the invoice was generated. | +| `Seller` | [`*models.InvoiceSeller`](../../doc/models/invoice-seller.md) | Optional | Information about the seller (merchant) listed on the masthead of the invoice. | +| `Customer` | [`*models.InvoiceCustomer`](../../doc/models/invoice-customer.md) | Optional | Information about the customer who is owner or recipient the invoiced subscription. | +| `Payer` | [`*models.InvoicePayer`](../../doc/models/invoice-payer.md) | Optional | - | +| `RecipientEmails` | `[]string` | Optional | **Constraints**: *Maximum Items*: `5` | +| `NetTerms` | `*int` | Optional | - | +| `Memo` | `*string` | Optional | The memo printed on invoices of any collection type. This message is in control of the merchant. | +| `BillingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | The invoice billing address. | +| `ShippingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | The invoice shipping address. | +| `SubtotalAmount` | `*string` | Optional | Subtotal of the invoice, which is the sum of all line items before discounts or taxes. | +| `DiscountAmount` | `*string` | Optional | Total discount applied to the invoice. | +| `TaxAmount` | `*string` | Optional | Total tax on the invoice. | +| `TotalAmount` | `*string` | Optional | The invoice total, which is `subtotal_amount - discount_amount + tax_amount`.' | +| `CreditAmount` | `*string` | Optional | The amount of credit (from credit notes) applied to this invoice.

Credits offset the amount due from the customer. | +| `RefundAmount` | `*string` | Optional | - | +| `PaidAmount` | `*string` | Optional | The amount paid on the invoice by the customer. | +| `DueAmount` | `*string` | Optional | Amount due on the invoice, which is `total_amount - credit_amount - paid_amount`. | +| `LineItems` | [`[]models.InvoiceLineItem`](../../doc/models/invoice-line-item.md) | Optional | Line items on the invoice. | +| `Discounts` | [`[]models.InvoiceDiscount`](../../doc/models/invoice-discount.md) | Optional | - | +| `Taxes` | [`[]models.InvoiceTax`](../../doc/models/invoice-tax.md) | Optional | - | +| `Credits` | [`[]models.InvoiceCredit`](../../doc/models/invoice-credit.md) | Optional | - | +| `Refunds` | [`[]models.InvoiceRefund`](../../doc/models/invoice-refund.md) | Optional | - | +| `Payments` | [`[]models.InvoicePayment`](../../doc/models/invoice-payment.md) | Optional | - | +| `CustomFields` | [`[]models.InvoiceCustomField`](../../doc/models/invoice-custom-field.md) | Optional | - | +| `DisplaySettings` | [`*models.InvoiceDisplaySettings`](../../doc/models/invoice-display-settings.md) | Optional | - | +| `PublicUrl` | `*string` | Optional | The public URL of the invoice | +| `PreviousBalanceData` | [`*models.InvoicePreviousBalance`](../../doc/models/invoice-previous-balance.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "issue_date": "2024-01-01", + "due_date": "2024-01-01", + "paid_date": "2024-01-01", + "collection_method": "automatic", + "id": 252, + "uid": "uid0", + "site_id": 178, + "customer_id": 34, + "subscription_id": 106 +} +``` + diff --git a/doc/models/issue-advance-invoice-request.md b/doc/models/issue-advance-invoice-request.md index b3dc1ffd..eb04bb6a 100644 --- a/doc/models/issue-advance-invoice-request.md +++ b/doc/models/issue-advance-invoice-request.md @@ -1,21 +1,21 @@ - -# Issue Advance Invoice Request - -## Structure - -`IssueAdvanceInvoiceRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Force` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "force": false -} -``` - + +# Issue Advance Invoice Request + +## Structure + +`IssueAdvanceInvoiceRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Force` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "force": false +} +``` + diff --git a/doc/models/issue-invoice-event-data.md b/doc/models/issue-invoice-event-data.md new file mode 100644 index 00000000..2cf70727 --- /dev/null +++ b/doc/models/issue-invoice-event-data.md @@ -0,0 +1,31 @@ + +# Issue Invoice Event Data + +Example schema for an `issue_invoice` event + +## Structure + +`IssueInvoiceEventData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ConsolidationLevel` | [`models.InvoiceConsolidationLevel`](../../doc/models/invoice-consolidation-level.md) | Required | Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values:

* "none": A normal invoice with no consolidation.
* "child": An invoice segment which has been combined into a consolidated invoice.
* "parent": A consolidated invoice, whose contents are composed of invoice segments.

"Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments.

See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). | +| `FromStatus` | [`models.InvoiceStatus`](../../doc/models/invoice-status.md) | Required | The status of the invoice before event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. | +| `ToStatus` | [`models.InvoiceStatus`](../../doc/models/invoice-status.md) | Required | The status of the invoice after event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. | +| `DueAmount` | `string` | Required | Amount due on the invoice, which is `total_amount - credit_amount - paid_amount`. | +| `TotalAmount` | `string` | Required | The invoice total, which is `subtotal_amount - discount_amount + tax_amount`.' | + +## Example (as JSON) + +```json +{ + "consolidation_level": "none", + "from_status": "draft", + "to_status": "voided", + "due_amount": "due_amount6", + "total_amount": "total_amount0" +} +``` + diff --git a/doc/models/issue-invoice-request.md b/doc/models/issue-invoice-request.md index 831c899f..5ca46798 100644 --- a/doc/models/issue-invoice-request.md +++ b/doc/models/issue-invoice-request.md @@ -1,21 +1,21 @@ - -# Issue Invoice Request - -## Structure - -`IssueInvoiceRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `OnFailedPayment` | [`*models.FailedPaymentAction`](../../doc/models/failed-payment-action.md) | Optional | Action taken when payment for an invoice fails:

- `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option.
- `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history.
- `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings).
**Default**: `"leave_open_invoice"` | - -## Example (as JSON) - -```json -{ - "on_failed_payment": "leave_open_invoice" -} -``` - + +# Issue Invoice Request + +## Structure + +`IssueInvoiceRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `OnFailedPayment` | [`*models.FailedPaymentAction`](../../doc/models/failed-payment-action.md) | Optional | Action taken when payment for an invoice fails:

- `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option.
- `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history.
- `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings).
**Default**: `"leave_open_invoice"` | + +## Example (as JSON) + +```json +{ + "on_failed_payment": "leave_open_invoice" +} +``` + diff --git a/doc/models/issue-service-credit-request.md b/doc/models/issue-service-credit-request.md index 0f3bc8ad..e890c744 100644 --- a/doc/models/issue-service-credit-request.md +++ b/doc/models/issue-service-credit-request.md @@ -1,27 +1,24 @@ - -# Issue Service Credit Request - -## Structure - -`IssueServiceCreditRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ServiceCredit` | [`models.IssueServiceCredit`](../../doc/models/issue-service-credit.md) | Required | - | - -## Example (as JSON) - -```json -{ - "service_credit": { - "amount": { - "key1": "val1", - "key2": "val2" - }, - "memo": "memo0" - } -} -``` - + +# Issue Service Credit Request + +## Structure + +`IssueServiceCreditRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ServiceCredit` | [`models.IssueServiceCredit`](../../doc/models/issue-service-credit.md) | Required | - | + +## Example (as JSON) + +```json +{ + "service_credit": { + "amount": 31.42, + "memo": "memo0" + } +} +``` + diff --git a/doc/models/issue-service-credit.md b/doc/models/issue-service-credit.md index 20cc80cb..30350100 100644 --- a/doc/models/issue-service-credit.md +++ b/doc/models/issue-service-credit.md @@ -1,26 +1,23 @@ - -# Issue Service Credit - -## Structure - -`IssueServiceCredit` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Amount` | `interface{}` | Required | - | -| `Memo` | `string` | Required | - | - -## Example (as JSON) - -```json -{ - "amount": { - "key1": "val1", - "key2": "val2" - }, - "memo": "memo4" -} -``` - + +# Issue Service Credit + +## Structure + +`IssueServiceCredit` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Amount` | [`models.IssueServiceCreditAmount`](../../doc/models/containers/issue-service-credit-amount.md) | Required | This is a container for one-of cases. | +| `Memo` | `string` | Required | - | + +## Example (as JSON) + +```json +{ + "amount": 5.82, + "memo": "memo4" +} +``` + diff --git a/doc/models/item-category.md b/doc/models/item-category.md index cedcdd2f..94f93a04 100644 --- a/doc/models/item-category.md +++ b/doc/models/item-category.md @@ -1,25 +1,25 @@ - -# Item Category - -One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other - -## Enumeration - -`ItemCategory` - -## Fields - -| Name | -| --- | -| `ENUMBUSINESSSOFTWARE` | -| `ENUMCONSUMERSOFTWARE` | -| `ENUMDIGITALSERVICES` | -| `ENUMPHYSICALGOODS` | -| `OTHER` | - -## Example - -``` -Business Software -``` - + +# Item Category + +One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other + +## Enumeration + +`ItemCategory` + +## Fields + +| Name | +| --- | +| `ENUMBUSINESSSOFTWARE` | +| `ENUMCONSUMERSOFTWARE` | +| `ENUMDIGITALSERVICES` | +| `ENUMPHYSICALGOODS` | +| `OTHER` | + +## Example + +``` +Business Software +``` + diff --git a/doc/models/item-price-point-changed.md b/doc/models/item-price-point-changed.md new file mode 100644 index 00000000..54c2a912 --- /dev/null +++ b/doc/models/item-price-point-changed.md @@ -0,0 +1,39 @@ + +# Item Price Point Changed + +## Structure + +`ItemPricePointChanged` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ItemId` | `int` | Required | - | +| `ItemType` | `string` | Required | - | +| `ItemHandle` | `string` | Required | - | +| `ItemName` | `string` | Required | - | +| `PreviousPricePoint` | [`models.ItemPricePointData`](../../doc/models/item-price-point-data.md) | Required | - | +| `CurrentPricePoint` | [`models.ItemPricePointData`](../../doc/models/item-price-point-data.md) | Required | - | + +## Example (as JSON) + +```json +{ + "item_id": 66, + "item_type": "item_type6", + "item_handle": "item_handle4", + "item_name": "item_name8", + "previous_price_point": { + "id": 216, + "handle": "handle6", + "name": "name0" + }, + "current_price_point": { + "id": 218, + "handle": "handle6", + "name": "name0" + } +} +``` + diff --git a/doc/models/item-price-point-data.md b/doc/models/item-price-point-data.md new file mode 100644 index 00000000..e9482c32 --- /dev/null +++ b/doc/models/item-price-point-data.md @@ -0,0 +1,25 @@ + +# Item Price Point Data + +## Structure + +`ItemPricePointData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Handle` | `*string` | Optional | - | +| `Name` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 192, + "handle": "handle6", + "name": "name0" +} +``` + diff --git a/doc/models/line-item-kind.md b/doc/models/line-item-kind.md index 4a364f88..5acf41b6 100644 --- a/doc/models/line-item-kind.md +++ b/doc/models/line-item-kind.md @@ -1,24 +1,24 @@ - -# Line Item Kind - -A handle for the line item kind - -## Enumeration - -`LineItemKind` - -## Fields - -| Name | -| --- | -| `BASELINE` | -| `INITIAL` | -| `TRIAL` | -| `QUANTITYBASEDCOMPONENT` | -| `PREPAIDUSAGECOMPONENT` | -| `ONOFFCOMPONENT` | -| `METEREDCOMPONENT` | -| `EVENTBASEDCOMPONENT` | -| `COUPON` | -| `TAX` | - + +# Line Item Kind + +A handle for the line item kind + +## Enumeration + +`LineItemKind` + +## Fields + +| Name | +| --- | +| `BASELINE` | +| `INITIAL` | +| `TRIAL` | +| `QUANTITYBASEDCOMPONENT` | +| `PREPAIDUSAGECOMPONENT` | +| `ONOFFCOMPONENT` | +| `METEREDCOMPONENT` | +| `EVENTBASEDCOMPONENT` | +| `COUPON` | +| `TAX` | + diff --git a/doc/models/line-item-transaction-type.md b/doc/models/line-item-transaction-type.md index 0c8d0a2d..ca5b83db 100644 --- a/doc/models/line-item-transaction-type.md +++ b/doc/models/line-item-transaction-type.md @@ -1,21 +1,21 @@ - -# Line Item Transaction Type - -A handle for the line item transaction type - -## Enumeration - -`LineItemTransactionType` - -## Fields - -| Name | -| --- | -| `CHARGE` | -| `CREDIT` | -| `ADJUSTMENT` | -| `PAYMENT` | -| `REFUND` | -| `INFOTRANSACTION` | -| `PAYMENTAUTHORIZATION` | - + +# Line Item Transaction Type + +A handle for the line item transaction type + +## Enumeration + +`LineItemTransactionType` + +## Fields + +| Name | +| --- | +| `CHARGE` | +| `CREDIT` | +| `ADJUSTMENT` | +| `PAYMENT` | +| `REFUND` | +| `INFOTRANSACTION` | +| `PAYMENTAUTHORIZATION` | + diff --git a/doc/models/list-components-price-points-include.md b/doc/models/list-components-price-points-include.md index a2df15ed..49459716 100644 --- a/doc/models/list-components-price-points-include.md +++ b/doc/models/list-components-price-points-include.md @@ -1,19 +1,19 @@ - -# List Components Price Points Include - -## Enumeration - -`ListComponentsPricePointsInclude` - -## Fields - -| Name | -| --- | -| `CURRENCYPRICES` | - -## Example - -``` -currency_prices -``` - + +# List Components Price Points Include + +## Enumeration + +`ListComponentsPricePointsInclude` + +## Fields + +| Name | +| --- | +| `CURRENCYPRICES` | + +## Example + +``` +currency_prices +``` + diff --git a/doc/models/list-components-price-points-response.md b/doc/models/list-components-price-points-response.md index bc44bbae..3b63c1ba 100644 --- a/doc/models/list-components-price-points-response.md +++ b/doc/models/list-components-price-points-response.md @@ -1,29 +1,29 @@ - -# List Components Price Points Response - -## Structure - -`ListComponentsPricePointsResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoints` | [`[]models.ComponentPricePoint`](../../doc/models/component-price-point.md) | Required | - | - -## Example (as JSON) - -```json -{ - "price_points": [ - { - "id": 40, - "type": "default", - "default": false, - "name": "name2", - "pricing_scheme": "per_unit" - } - ] -} -``` - + +# List Components Price Points Response + +## Structure + +`ListComponentsPricePointsResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoints` | [`[]models.ComponentPricePoint`](../../doc/models/component-price-point.md) | Required | - | + +## Example (as JSON) + +```json +{ + "price_points": [ + { + "id": 40, + "type": "default", + "default": false, + "name": "name2", + "pricing_scheme": "per_unit" + } + ] +} +``` + diff --git a/doc/models/list-credit-notes-response.md b/doc/models/list-credit-notes-response.md index 8d8e0202..1f8ecbbc 100644 --- a/doc/models/list-credit-notes-response.md +++ b/doc/models/list-credit-notes-response.md @@ -1,29 +1,29 @@ - -# List Credit Notes Response - -## Structure - -`ListCreditNotesResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CreditNotes` | [`[]models.CreditNote`](../../doc/models/credit-note.md) | Required | - | - -## Example (as JSON) - -```json -{ - "credit_notes": [ - { - "uid": "uid2", - "site_id": 112, - "customer_id": 224, - "subscription_id": 40, - "number": "number0" - } - ] -} -``` - + +# List Credit Notes Response + +## Structure + +`ListCreditNotesResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CreditNotes` | [`[]models.CreditNote`](../../doc/models/credit-note.md) | Required | - | + +## Example (as JSON) + +```json +{ + "credit_notes": [ + { + "uid": "uid2", + "site_id": 112, + "customer_id": 224, + "subscription_id": 40, + "number": "number0" + } + ] +} +``` + diff --git a/doc/models/list-events-date-field.md b/doc/models/list-events-date-field.md index ce5b4f15..2063a16f 100644 --- a/doc/models/list-events-date-field.md +++ b/doc/models/list-events-date-field.md @@ -1,19 +1,19 @@ - -# List Events Date Field - -## Enumeration - -`ListEventsDateField` - -## Fields - -| Name | -| --- | -| `CREATEDAT` | - -## Example - -``` -created_at -``` - + +# List Events Date Field + +## Enumeration + +`ListEventsDateField` + +## Fields + +| Name | +| --- | +| `CREATEDAT` | + +## Example + +``` +created_at +``` + diff --git a/doc/models/list-invoice-events-response.md b/doc/models/list-invoice-events-response.md index 40c92fd5..5080e57d 100644 --- a/doc/models/list-invoice-events-response.md +++ b/doc/models/list-invoice-events-response.md @@ -1,47 +1,61 @@ - -# List Invoice Events Response - -## Structure - -`ListInvoiceEventsResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Events` | [`[]models.InvoiceEvent`](../../doc/models/invoice-event.md) | Optional | - | -| `Page` | `*int` | Optional | - | -| `PerPage` | `*int` | Optional | - | -| `TotalPages` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "events": [ - { - "id": 68, - "event_type": "void_invoice", - "event_data": { - "uid": "uid6", - "credit_note_number": "credit_note_number0", - "credit_note_uid": "credit_note_uid0", - "original_amount": "original_amount0", - "applied_amount": "applied_amount2" - }, - "timestamp": "2016-03-13T12:52:32.123Z", - "invoice": { - "id": 166, - "uid": "uid6", - "site_id": 92, - "customer_id": 204, - "subscription_id": 20 - } - } - ], - "page": 184, - "per_page": 96, - "total_pages": 194 -} -``` - + +# List Invoice Events Response + +## Structure + +`ListInvoiceEventsResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Events` | [`[]models.InvoiceEvent`](../../doc/models/invoice-event.md) | Optional | - | +| `Page` | `*int` | Optional | - | +| `PerPage` | `*int` | Optional | - | +| `TotalPages` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "events": [ + { + "id": 68, + "event_type": "void_invoice", + "event_data": { + "uid": "uid2", + "credit_note_number": "credit_note_number4", + "credit_note_uid": "credit_note_uid4", + "original_amount": "original_amount6", + "applied_amount": "applied_amount6", + "transaction_time": "2016-03-13T12:52:32.123Z", + "memo": "memo6", + "role": "role4", + "consolidated_invoice": false, + "applied_credit_notes": [ + { + "uid": "uid4", + "number": "number8" + }, + { + "uid": "uid4", + "number": "number8" + } + ] + }, + "timestamp": "2016-03-13T12:52:32.123Z", + "invoice": { + "id": 166, + "uid": "uid6", + "site_id": 92, + "customer_id": 204, + "subscription_id": 20 + } + } + ], + "page": 184, + "per_page": 96, + "total_pages": 194 +} +``` + diff --git a/doc/models/list-invoices-response.md b/doc/models/list-invoices-response.md index c4090b52..5604b3d6 100644 --- a/doc/models/list-invoices-response.md +++ b/doc/models/list-invoices-response.md @@ -1,33 +1,33 @@ - -# List Invoices Response - -## Structure - -`ListInvoicesResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Invoices` | [`[]models.Invoice`](../../doc/models/invoice.md) | Required | - | - -## Example (as JSON) - -```json -{ - "invoices": [ - { - "issue_date": "2024-01-01", - "due_date": "2024-01-01", - "paid_date": "2024-01-01", - "collection_method": "automatic", - "id": 196, - "uid": "uid6", - "site_id": 122, - "customer_id": 234, - "subscription_id": 50 - } - ] -} -``` - + +# List Invoices Response + +## Structure + +`ListInvoicesResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Invoices` | [`[]models.Invoice`](../../doc/models/invoice.md) | Required | - | + +## Example (as JSON) + +```json +{ + "invoices": [ + { + "issue_date": "2024-01-01", + "due_date": "2024-01-01", + "paid_date": "2024-01-01", + "collection_method": "automatic", + "id": 196, + "uid": "uid6", + "site_id": 122, + "customer_id": 234, + "subscription_id": 50 + } + ] +} +``` + diff --git a/doc/models/list-metafields-response.md b/doc/models/list-metafields-response.md index 0bc4436a..f4b5f4eb 100644 --- a/doc/models/list-metafields-response.md +++ b/doc/models/list-metafields-response.md @@ -1,43 +1,43 @@ - -# List Metafields Response - -## Structure - -`ListMetafieldsResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TotalCount` | `*int` | Optional | - | -| `CurrentPage` | `*int` | Optional | - | -| `TotalPages` | `*int` | Optional | - | -| `PerPage` | `*int` | Optional | - | -| `Metafields` | [`[]models.Metafield`](../../doc/models/metafield.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "total_count": 210, - "current_page": 186, - "total_pages": 198, - "per_page": 92, - "metafields": [ - { - "id": 22, - "name": "name2", - "scope": { - "csv": "0", - "invoices": "0", - "statements": "0", - "portal": "0", - "public_show": "0" - }, - "data_count": 10, - "input_type": "balance_tracker" - } - ] -} -``` - + +# List Metafields Response + +## Structure + +`ListMetafieldsResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TotalCount` | `*int` | Optional | - | +| `CurrentPage` | `*int` | Optional | - | +| `TotalPages` | `*int` | Optional | - | +| `PerPage` | `*int` | Optional | - | +| `Metafields` | [`[]models.Metafield`](../../doc/models/metafield.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "total_count": 210, + "current_page": 186, + "total_pages": 198, + "per_page": 92, + "metafields": [ + { + "id": 22, + "name": "name2", + "scope": { + "csv": "0", + "invoices": "0", + "statements": "0", + "portal": "0", + "public_show": "0" + }, + "data_count": 10, + "input_type": "balance_tracker" + } + ] +} +``` + diff --git a/doc/models/list-mrr-response-result.md b/doc/models/list-mrr-response-result.md index 6eed7919..5eaa7858 100644 --- a/doc/models/list-mrr-response-result.md +++ b/doc/models/list-mrr-response-result.md @@ -1,31 +1,31 @@ - -# List MRR Response Result - -## Structure - -`ListMRRResponseResult` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Page` | `*int` | Optional | - | -| `PerPage` | `*int` | Optional | - | -| `TotalPages` | `*int` | Optional | - | -| `TotalEntries` | `*int` | Optional | - | -| `Currency` | `*string` | Optional | - | -| `CurrencySymbol` | `*string` | Optional | - | -| `Movements` | [`[]models.Movement`](../../doc/models/movement.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "page": 150, - "per_page": 238, - "total_pages": 16, - "total_entries": 112, - "currency": "currency8" -} -``` - + +# List MRR Response Result + +## Structure + +`ListMRRResponseResult` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Page` | `*int` | Optional | - | +| `PerPage` | `*int` | Optional | - | +| `TotalPages` | `*int` | Optional | - | +| `TotalEntries` | `*int` | Optional | - | +| `Currency` | `*string` | Optional | - | +| `CurrencySymbol` | `*string` | Optional | - | +| `Movements` | [`[]models.Movement`](../../doc/models/movement.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "page": 150, + "per_page": 238, + "total_pages": 16, + "total_entries": 112, + "currency": "currency8" +} +``` + diff --git a/doc/models/list-mrr-response.md b/doc/models/list-mrr-response.md index b5691029..32c50529 100644 --- a/doc/models/list-mrr-response.md +++ b/doc/models/list-mrr-response.md @@ -1,27 +1,27 @@ - -# List MRR Response - -## Structure - -`ListMRRResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Mrr` | [`models.ListMRRResponseResult`](../../doc/models/list-mrr-response-result.md) | Required | - | - -## Example (as JSON) - -```json -{ - "mrr": { - "page": 30, - "per_page": 198, - "total_pages": 92, - "total_entries": 188, - "currency": "currency4" - } -} -``` - + +# List MRR Response + +## Structure + +`ListMRRResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Mrr` | [`models.ListMRRResponseResult`](../../doc/models/list-mrr-response-result.md) | Required | - | + +## Example (as JSON) + +```json +{ + "mrr": { + "page": 30, + "per_page": 198, + "total_pages": 92, + "total_entries": 188, + "currency": "currency4" + } +} +``` + diff --git a/doc/models/list-offers-response.md b/doc/models/list-offers-response.md index 7bbee87a..095224cb 100644 --- a/doc/models/list-offers-response.md +++ b/doc/models/list-offers-response.md @@ -1,43 +1,43 @@ - -# List Offers Response - -## Structure - -`ListOffersResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Offers` | [`[]models.Offer`](../../doc/models/offer.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "offers": [ - { - "id": 12, - "site_id": 194, - "product_family_id": 16, - "product_id": 210, - "product_price_point_id": 134 - }, - { - "id": 12, - "site_id": 194, - "product_family_id": 16, - "product_id": 210, - "product_price_point_id": 134 - }, - { - "id": 12, - "site_id": 194, - "product_family_id": 16, - "product_id": 210, - "product_price_point_id": 134 - } - ] -} -``` - + +# List Offers Response + +## Structure + +`ListOffersResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Offers` | [`[]models.Offer`](../../doc/models/offer.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "offers": [ + { + "id": 12, + "site_id": 194, + "product_family_id": 16, + "product_id": 210, + "product_price_point_id": 134 + }, + { + "id": 12, + "site_id": 194, + "product_family_id": 16, + "product_id": 210, + "product_price_point_id": 134 + }, + { + "id": 12, + "site_id": 194, + "product_family_id": 16, + "product_id": 210, + "product_price_point_id": 134 + } + ] +} +``` + diff --git a/doc/models/list-product-price-points-response.md b/doc/models/list-product-price-points-response.md index 27a81ba8..b9963586 100644 --- a/doc/models/list-product-price-points-response.md +++ b/doc/models/list-product-price-points-response.md @@ -1,29 +1,29 @@ - -# List Product Price Points Response - -## Structure - -`ListProductPricePointsResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoints` | [`[]models.ProductPricePoint`](../../doc/models/product-price-point.md) | Required | - | - -## Example (as JSON) - -```json -{ - "price_points": [ - { - "id": 40, - "name": "name2", - "handle": "handle8", - "price_in_cents": 108, - "interval": 92 - } - ] -} -``` - + +# List Product Price Points Response + +## Structure + +`ListProductPricePointsResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoints` | [`[]models.ProductPricePoint`](../../doc/models/product-price-point.md) | Required | - | + +## Example (as JSON) + +```json +{ + "price_points": [ + { + "id": 40, + "name": "name2", + "handle": "handle8", + "price_in_cents": 108, + "interval": 92 + } + ] +} +``` + diff --git a/doc/models/list-products-include.md b/doc/models/list-products-include.md index dbf4c8b1..71d90e1b 100644 --- a/doc/models/list-products-include.md +++ b/doc/models/list-products-include.md @@ -1,19 +1,19 @@ - -# List Products Include - -## Enumeration - -`ListProductsInclude` - -## Fields - -| Name | -| --- | -| `PREPAIDPRODUCTPRICEPOINT` | - -## Example - -``` -prepaid_product_price_point -``` - + +# List Products Include + +## Enumeration + +`ListProductsInclude` + +## Fields + +| Name | +| --- | +| `PREPAIDPRODUCTPRICEPOINT` | + +## Example + +``` +prepaid_product_price_point +``` + diff --git a/doc/models/list-products-price-points-include.md b/doc/models/list-products-price-points-include.md index ba6c56fc..3e58e30d 100644 --- a/doc/models/list-products-price-points-include.md +++ b/doc/models/list-products-price-points-include.md @@ -1,19 +1,19 @@ - -# List Products Price Points Include - -## Enumeration - -`ListProductsPricePointsInclude` - -## Fields - -| Name | -| --- | -| `CURRENCYPRICES` | - -## Example - -``` -currency_prices -``` - + +# List Products Price Points Include + +## Enumeration + +`ListProductsPricePointsInclude` + +## Fields + +| Name | +| --- | +| `CURRENCYPRICES` | + +## Example + +``` +currency_prices +``` + diff --git a/doc/models/list-proforma-invoices-meta.md b/doc/models/list-proforma-invoices-meta.md index 3e4a0300..c9937993 100644 --- a/doc/models/list-proforma-invoices-meta.md +++ b/doc/models/list-proforma-invoices-meta.md @@ -1,27 +1,27 @@ - -# List Proforma Invoices Meta - -## Structure - -`ListProformaInvoicesMeta` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TotalCount` | `*int` | Optional | - | -| `CurrentPage` | `*int` | Optional | - | -| `TotalPages` | `*int` | Optional | - | -| `StatusCode` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "total_count": 226, - "current_page": 202, - "total_pages": 214, - "status_code": 244 -} -``` - + +# List Proforma Invoices Meta + +## Structure + +`ListProformaInvoicesMeta` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TotalCount` | `*int` | Optional | - | +| `CurrentPage` | `*int` | Optional | - | +| `TotalPages` | `*int` | Optional | - | +| `StatusCode` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "total_count": 226, + "current_page": 202, + "total_pages": 214, + "status_code": 244 +} +``` + diff --git a/doc/models/list-proforma-invoices-response.md b/doc/models/list-proforma-invoices-response.md index 967d8f41..3add9787 100644 --- a/doc/models/list-proforma-invoices-response.md +++ b/doc/models/list-proforma-invoices-response.md @@ -1,50 +1,50 @@ - -# List Proforma Invoices Response - -## Structure - -`ListProformaInvoicesResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ProformaInvoices` | [`[]models.ProformaInvoice`](../../doc/models/proforma-invoice.md) | Optional | - | -| `Meta` | [`*models.ListProformaInvoicesMeta`](../../doc/models/list-proforma-invoices-meta.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "proforma_invoices": [ - { - "uid": "uid0", - "site_id": 140, - "customer_id": 252, - "subscription_id": 68, - "number": 56 - }, - { - "uid": "uid0", - "site_id": 140, - "customer_id": 252, - "subscription_id": 68, - "number": 56 - }, - { - "uid": "uid0", - "site_id": 140, - "customer_id": 252, - "subscription_id": 68, - "number": 56 - } - ], - "meta": { - "total_count": 150, - "current_page": 126, - "total_pages": 138, - "status_code": 168 - } -} -``` - + +# List Proforma Invoices Response + +## Structure + +`ListProformaInvoicesResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProformaInvoices` | [`[]models.ProformaInvoice`](../../doc/models/proforma-invoice.md) | Optional | - | +| `Meta` | [`*models.ListProformaInvoicesMeta`](../../doc/models/list-proforma-invoices-meta.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "proforma_invoices": [ + { + "uid": "uid0", + "site_id": 140, + "customer_id": 252, + "subscription_id": 68, + "number": 56 + }, + { + "uid": "uid0", + "site_id": 140, + "customer_id": 252, + "subscription_id": 68, + "number": 56 + }, + { + "uid": "uid0", + "site_id": 140, + "customer_id": 252, + "subscription_id": 68, + "number": 56 + } + ], + "meta": { + "total_count": 150, + "current_page": 126, + "total_pages": 138, + "status_code": 168 + } +} +``` + diff --git a/doc/models/list-public-keys-meta.md b/doc/models/list-public-keys-meta.md index fae8cacf..3d570cca 100644 --- a/doc/models/list-public-keys-meta.md +++ b/doc/models/list-public-keys-meta.md @@ -1,27 +1,27 @@ - -# List Public Keys Meta - -## Structure - -`ListPublicKeysMeta` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TotalCount` | `*int` | Optional | - | -| `CurrentPage` | `*int` | Optional | - | -| `TotalPages` | `*int` | Optional | - | -| `PerPage` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "total_count": 22, - "current_page": 254, - "total_pages": 10, - "per_page": 24 -} -``` - + +# List Public Keys Meta + +## Structure + +`ListPublicKeysMeta` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TotalCount` | `*int` | Optional | - | +| `CurrentPage` | `*int` | Optional | - | +| `TotalPages` | `*int` | Optional | - | +| `PerPage` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "total_count": 22, + "current_page": 254, + "total_pages": 10, + "per_page": 24 +} +``` + diff --git a/doc/models/list-public-keys-response.md b/doc/models/list-public-keys-response.md index 1600152d..8d6c8a2b 100644 --- a/doc/models/list-public-keys-response.md +++ b/doc/models/list-public-keys-response.md @@ -1,39 +1,39 @@ - -# List Public Keys Response - -## Structure - -`ListPublicKeysResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ChargifyJsKeys` | [`[]models.PublicKey`](../../doc/models/public-key.md) | Optional | - | -| `Meta` | [`*models.ListPublicKeysMeta`](../../doc/models/list-public-keys-meta.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "chargify_js_keys": [ - { - "public_key": "public_key8", - "requires_security_token": false, - "created_at": "2016-03-13T12:52:32.123Z" - }, - { - "public_key": "public_key8", - "requires_security_token": false, - "created_at": "2016-03-13T12:52:32.123Z" - } - ], - "meta": { - "total_count": 150, - "current_page": 126, - "total_pages": 138, - "per_page": 152 - } -} -``` - + +# List Public Keys Response + +## Structure + +`ListPublicKeysResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ChargifyJsKeys` | [`[]models.PublicKey`](../../doc/models/public-key.md) | Optional | - | +| `Meta` | [`*models.ListPublicKeysMeta`](../../doc/models/list-public-keys-meta.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "chargify_js_keys": [ + { + "public_key": "public_key8", + "requires_security_token": false, + "created_at": "2016-03-13T12:52:32.123Z" + }, + { + "public_key": "public_key8", + "requires_security_token": false, + "created_at": "2016-03-13T12:52:32.123Z" + } + ], + "meta": { + "total_count": 150, + "current_page": 126, + "total_pages": 138, + "per_page": 152 + } +} +``` + diff --git a/doc/models/list-sale-rep-item.md b/doc/models/list-sale-rep-item.md index 108b08ac..7f73ccc1 100644 --- a/doc/models/list-sale-rep-item.md +++ b/doc/models/list-sale-rep-item.md @@ -1,45 +1,45 @@ - -# List Sale Rep Item - -## Structure - -`ListSaleRepItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `FullName` | `*string` | Optional | - | -| `SubscriptionsCount` | `*int` | Optional | - | -| `MrrData` | [`map[string]models.SaleRepItemMrr`](../../doc/models/sale-rep-item-mrr.md) | Optional | - | -| `TestMode` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "mrr_data": { - "november_2019": { - "mrr": "$0.00", - "usage": "$0.00", - "recurring": "$0.00" - }, - "december_2019": { - "mrr": "$0.00", - "usage": "$0.00", - "recurring": "$0.00" - }, - "january_2020": { - "mrr": "$400.00", - "usage": "$0.00", - "recurring": "$400.00" - } - }, - "id": 26, - "full_name": "full_name8", - "subscriptions_count": 154, - "test_mode": false -} -``` - + +# List Sale Rep Item + +## Structure + +`ListSaleRepItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `FullName` | `*string` | Optional | - | +| `SubscriptionsCount` | `*int` | Optional | - | +| `MrrData` | [`map[string]models.SaleRepItemMrr`](../../doc/models/sale-rep-item-mrr.md) | Optional | - | +| `TestMode` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "mrr_data": { + "november_2019": { + "mrr": "$0.00", + "usage": "$0.00", + "recurring": "$0.00" + }, + "december_2019": { + "mrr": "$0.00", + "usage": "$0.00", + "recurring": "$0.00" + }, + "january_2020": { + "mrr": "$400.00", + "usage": "$0.00", + "recurring": "$400.00" + } + }, + "id": 26, + "full_name": "full_name8", + "subscriptions_count": 154, + "test_mode": false +} +``` + diff --git a/doc/models/list-segments-response.md b/doc/models/list-segments-response.md index 2ae9bbc0..8a853448 100644 --- a/doc/models/list-segments-response.md +++ b/doc/models/list-segments-response.md @@ -1,29 +1,29 @@ - -# List Segments Response - -## Structure - -`ListSegmentsResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Segments` | [`[]models.Segment`](../../doc/models/segment.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "segments": [ - { - "id": 50, - "component_id": 160, - "price_point_id": 184, - "event_based_billing_metric_id": 244, - "pricing_scheme": "stairstep" - } - ] -} -``` - + +# List Segments Response + +## Structure + +`ListSegmentsResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Segments` | [`[]models.Segment`](../../doc/models/segment.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "segments": [ + { + "id": 50, + "component_id": 160, + "price_point_id": 184, + "event_based_billing_metric_id": 244, + "pricing_scheme": "stairstep" + } + ] +} +``` + diff --git a/doc/models/list-subcription-group-prepayment-item.md b/doc/models/list-subcription-group-prepayment-item.md index bb2451e0..9fa52e09 100644 --- a/doc/models/list-subcription-group-prepayment-item.md +++ b/doc/models/list-subcription-group-prepayment-item.md @@ -1,33 +1,33 @@ - -# List Subcription Group Prepayment Item - -## Structure - -`ListSubcriptionGroupPrepaymentItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `SubscriptionGroupUid` | `*string` | Optional | - | -| `AmountInCents` | `*int64` | Optional | - | -| `RemainingAmountInCents` | `*int64` | Optional | - | -| `Details` | `*string` | Optional | - | -| `External` | `*bool` | Optional | - | -| `Memo` | `*string` | Optional | - | -| `PaymentType` | [`*models.PrepaymentMethod`](../../doc/models/prepayment-method.md) | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 254, - "subscription_group_uid": "subscription_group_uid6", - "amount_in_cents": 172, - "remaining_amount_in_cents": 142, - "details": "details2" -} -``` - + +# List Subcription Group Prepayment Item + +## Structure + +`ListSubcriptionGroupPrepaymentItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `SubscriptionGroupUid` | `*string` | Optional | - | +| `AmountInCents` | `*int64` | Optional | - | +| `RemainingAmountInCents` | `*int64` | Optional | - | +| `Details` | `*string` | Optional | - | +| `External` | `*bool` | Optional | - | +| `Memo` | `*string` | Optional | - | +| `PaymentType` | [`*models.PrepaymentMethod`](../../doc/models/prepayment-method.md) | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 254, + "subscription_group_uid": "subscription_group_uid6", + "amount_in_cents": 172, + "remaining_amount_in_cents": 142, + "details": "details2" +} +``` + diff --git a/doc/models/list-subscription-components-include.md b/doc/models/list-subscription-components-include.md index 8ddf0f45..afc3a353 100644 --- a/doc/models/list-subscription-components-include.md +++ b/doc/models/list-subscription-components-include.md @@ -1,19 +1,19 @@ - -# List Subscription Components Include - -## Enumeration - -`ListSubscriptionComponentsInclude` - -## Fields - -| Name | -| --- | -| `SUBSCRIPTION` | - -## Example - -``` -subscription -``` - + +# List Subscription Components Include + +## Enumeration + +`ListSubscriptionComponentsInclude` + +## Fields + +| Name | +| --- | +| `SUBSCRIPTION` | + +## Example + +``` +subscription +``` + diff --git a/doc/models/list-subscription-components-response.md b/doc/models/list-subscription-components-response.md index 92d93138..981ec1bd 100644 --- a/doc/models/list-subscription-components-response.md +++ b/doc/models/list-subscription-components-response.md @@ -1,29 +1,29 @@ - -# List Subscription Components Response - -## Structure - -`ListSubscriptionComponentsResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SubscriptionsComponents` | [`[]models.SubscriptionComponent`](../../doc/models/subscription-component.md) | Required | - | - -## Example (as JSON) - -```json -{ - "subscriptions_components": [ - { - "id": 138, - "name": "name2", - "kind": "metered_component", - "unit_name": "unit_name4", - "enabled": false - } - ] -} -``` - + +# List Subscription Components Response + +## Structure + +`ListSubscriptionComponentsResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionsComponents` | [`[]models.SubscriptionComponent`](../../doc/models/subscription-component.md) | Required | - | + +## Example (as JSON) + +```json +{ + "subscriptions_components": [ + { + "id": 138, + "name": "name2", + "kind": "metered_component", + "unit_name": "unit_name4", + "enabled": false + } + ] +} +``` + diff --git a/doc/models/list-subscription-components-sort.md b/doc/models/list-subscription-components-sort.md index f23c5bc8..848f90d3 100644 --- a/doc/models/list-subscription-components-sort.md +++ b/doc/models/list-subscription-components-sort.md @@ -1,20 +1,20 @@ - -# List Subscription Components Sort - -## Enumeration - -`ListSubscriptionComponentsSort` - -## Fields - -| Name | -| --- | -| `ID` | -| `UPDATEDAT` | - -## Example - -``` -updated_at -``` - + +# List Subscription Components Sort + +## Enumeration + +`ListSubscriptionComponentsSort` + +## Fields + +| Name | +| --- | +| `ID` | +| `UPDATEDAT` | + +## Example + +``` +updated_at +``` + diff --git a/doc/models/list-subscription-group-prepayment-date-field.md b/doc/models/list-subscription-group-prepayment-date-field.md index 3a568d1d..f4c960c2 100644 --- a/doc/models/list-subscription-group-prepayment-date-field.md +++ b/doc/models/list-subscription-group-prepayment-date-field.md @@ -1,20 +1,20 @@ - -# List Subscription Group Prepayment Date Field - -## Enumeration - -`ListSubscriptionGroupPrepaymentDateField` - -## Fields - -| Name | -| --- | -| `CREATEDAT` | -| `APPLICATIONAT` | - -## Example - -``` -created_at -``` - + +# List Subscription Group Prepayment Date Field + +## Enumeration + +`ListSubscriptionGroupPrepaymentDateField` + +## Fields + +| Name | +| --- | +| `CREATEDAT` | +| `APPLICATIONAT` | + +## Example + +``` +created_at +``` + diff --git a/doc/models/list-subscription-group-prepayment-response.md b/doc/models/list-subscription-group-prepayment-response.md index 15d75fd8..2ba8f4e5 100644 --- a/doc/models/list-subscription-group-prepayment-response.md +++ b/doc/models/list-subscription-group-prepayment-response.md @@ -1,31 +1,31 @@ - -# List Subscription Group Prepayment Response - -## Structure - -`ListSubscriptionGroupPrepaymentResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Prepayments` | [`[]models.ListSubscriptionGroupPrepayment`](../../doc/models/list-subscription-group-prepayment.md) | Required | - | - -## Example (as JSON) - -```json -{ - "prepayments": [ - { - "prepayment": { - "id": 38, - "subscription_group_uid": "subscription_group_uid2", - "amount_in_cents": 124, - "remaining_amount_in_cents": 182, - "details": "details8" - } - } - ] -} -``` - + +# List Subscription Group Prepayment Response + +## Structure + +`ListSubscriptionGroupPrepaymentResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Prepayments` | [`[]models.ListSubscriptionGroupPrepayment`](../../doc/models/list-subscription-group-prepayment.md) | Required | - | + +## Example (as JSON) + +```json +{ + "prepayments": [ + { + "prepayment": { + "id": 38, + "subscription_group_uid": "subscription_group_uid2", + "amount_in_cents": 124, + "remaining_amount_in_cents": 182, + "details": "details8" + } + } + ] +} +``` + diff --git a/doc/models/list-subscription-group-prepayment.md b/doc/models/list-subscription-group-prepayment.md index 1e679f14..907568a3 100644 --- a/doc/models/list-subscription-group-prepayment.md +++ b/doc/models/list-subscription-group-prepayment.md @@ -1,27 +1,27 @@ - -# List Subscription Group Prepayment - -## Structure - -`ListSubscriptionGroupPrepayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Prepayment` | [`models.ListSubcriptionGroupPrepaymentItem`](../../doc/models/list-subcription-group-prepayment-item.md) | Required | - | - -## Example (as JSON) - -```json -{ - "prepayment": { - "id": 38, - "subscription_group_uid": "subscription_group_uid2", - "amount_in_cents": 124, - "remaining_amount_in_cents": 182, - "details": "details8" - } -} -``` - + +# List Subscription Group Prepayment + +## Structure + +`ListSubscriptionGroupPrepayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Prepayment` | [`models.ListSubcriptionGroupPrepaymentItem`](../../doc/models/list-subcription-group-prepayment-item.md) | Required | - | + +## Example (as JSON) + +```json +{ + "prepayment": { + "id": 38, + "subscription_group_uid": "subscription_group_uid2", + "amount_in_cents": 124, + "remaining_amount_in_cents": 182, + "details": "details8" + } +} +``` + diff --git a/doc/models/list-subscription-groups-item.md b/doc/models/list-subscription-groups-item.md index 51b5189a..210e3f50 100644 --- a/doc/models/list-subscription-groups-item.md +++ b/doc/models/list-subscription-groups-item.md @@ -1,36 +1,37 @@ - -# List Subscription Groups Item - -## Structure - -`ListSubscriptionGroupsItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `Scheme` | `*int` | Optional | - | -| `CustomerId` | `*int` | Optional | - | -| `PaymentProfileId` | `*int` | Optional | - | -| `SubscriptionIds` | `[]int` | Optional | - | -| `PrimarySubscriptionId` | `*int` | Optional | - | -| `NextAssessmentAt` | `*time.Time` | Optional | - | -| `State` | `*string` | Optional | - | -| `CancelAtEndOfPeriod` | `*bool` | Optional | - | -| `AccountBalances` | [`*models.SubscriptionGroupBalances`](../../doc/models/subscription-group-balances.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid0", - "scheme": 124, - "customer_id": 144, - "payment_profile_id": 52, - "subscription_ids": [ - 254 - ] -} -``` - + +# List Subscription Groups Item + +## Structure + +`ListSubscriptionGroupsItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `Scheme` | `*int` | Optional | - | +| `CustomerId` | `*int` | Optional | - | +| `PaymentProfileId` | `*int` | Optional | - | +| `SubscriptionIds` | `[]int` | Optional | - | +| `PrimarySubscriptionId` | `*int` | Optional | - | +| `NextAssessmentAt` | `*time.Time` | Optional | - | +| `State` | `*string` | Optional | - | +| `CancelAtEndOfPeriod` | `*bool` | Optional | - | +| `AccountBalances` | [`*models.SubscriptionGroupBalances`](../../doc/models/subscription-group-balances.md) | Optional | - | +| `GroupType` | [`*models.GroupType`](../../doc/models/group-type.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid0", + "scheme": 124, + "customer_id": 144, + "payment_profile_id": 52, + "subscription_ids": [ + 254 + ] +} +``` + diff --git a/doc/models/list-subscription-groups-meta.md b/doc/models/list-subscription-groups-meta.md index ed614246..316d617d 100644 --- a/doc/models/list-subscription-groups-meta.md +++ b/doc/models/list-subscription-groups-meta.md @@ -1,23 +1,23 @@ - -# List Subscription Groups Meta - -## Structure - -`ListSubscriptionGroupsMeta` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CurrentPage` | `*int` | Optional | - | -| `TotalCount` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "current_page": 14, - "total_count": 38 -} -``` - + +# List Subscription Groups Meta + +## Structure + +`ListSubscriptionGroupsMeta` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrentPage` | `*int` | Optional | - | +| `TotalCount` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "current_page": 14, + "total_count": 38 +} +``` + diff --git a/doc/models/list-subscription-groups-response.md b/doc/models/list-subscription-groups-response.md index b3e64cbb..579cd448 100644 --- a/doc/models/list-subscription-groups-response.md +++ b/doc/models/list-subscription-groups-response.md @@ -1,54 +1,54 @@ - -# List Subscription Groups Response - -## Structure - -`ListSubscriptionGroupsResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SubscriptionGroups` | [`[]models.ListSubscriptionGroupsItem`](../../doc/models/list-subscription-groups-item.md) | Optional | - | -| `Meta` | [`*models.ListSubscriptionGroupsMeta`](../../doc/models/list-subscription-groups-meta.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "subscription_groups": [ - { - "uid": "uid2", - "scheme": 166, - "customer_id": 186, - "payment_profile_id": 162, - "subscription_ids": [ - 40 - ] - }, - { - "uid": "uid2", - "scheme": 166, - "customer_id": 186, - "payment_profile_id": 162, - "subscription_ids": [ - 40 - ] - }, - { - "uid": "uid2", - "scheme": 166, - "customer_id": 186, - "payment_profile_id": 162, - "subscription_ids": [ - 40 - ] - } - ], - "meta": { - "current_page": 126, - "total_count": 150 - } -} -``` - + +# List Subscription Groups Response + +## Structure + +`ListSubscriptionGroupsResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionGroups` | [`[]models.ListSubscriptionGroupsItem`](../../doc/models/list-subscription-groups-item.md) | Optional | - | +| `Meta` | [`*models.ListSubscriptionGroupsMeta`](../../doc/models/list-subscription-groups-meta.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "subscription_groups": [ + { + "uid": "uid2", + "scheme": 166, + "customer_id": 186, + "payment_profile_id": 162, + "subscription_ids": [ + 40 + ] + }, + { + "uid": "uid2", + "scheme": 166, + "customer_id": 186, + "payment_profile_id": 162, + "subscription_ids": [ + 40 + ] + }, + { + "uid": "uid2", + "scheme": 166, + "customer_id": 186, + "payment_profile_id": 162, + "subscription_ids": [ + 40 + ] + } + ], + "meta": { + "current_page": 126, + "total_count": 150 + } +} +``` + diff --git a/doc/models/metadata.md b/doc/models/metadata.md index 68e4b5dc..b310e453 100644 --- a/doc/models/metadata.md +++ b/doc/models/metadata.md @@ -1,30 +1,30 @@ - -# Metadata - -## Structure - -`Metadata` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `Optional[int]` | Optional | - | -| `Value` | `Optional[string]` | Optional | - | -| `ResourceId` | `Optional[int]` | Optional | - | -| `Name` | `*string` | Optional | - | -| `DeletedAt` | `Optional[time.Time]` | Optional | - | -| `MetafieldId` | `Optional[int]` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 12, - "value": "value0", - "resource_id": 96, - "name": "name8", - "deleted_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Metadata + +## Structure + +`Metadata` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `models.Optional[int]` | Optional | - | +| `Value` | `models.Optional[string]` | Optional | - | +| `ResourceId` | `models.Optional[int]` | Optional | - | +| `Name` | `*string` | Optional | - | +| `DeletedAt` | `models.Optional[time.Time]` | Optional | - | +| `MetafieldId` | `models.Optional[int]` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 12, + "value": "value0", + "resource_id": 96, + "name": "name8", + "deleted_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/metafield-input.md b/doc/models/metafield-input.md index ee83a437..c2e84342 100644 --- a/doc/models/metafield-input.md +++ b/doc/models/metafield-input.md @@ -1,18 +1,18 @@ - -# Metafield Input - -Indicates how data should be added to the metafield. For example, a text type is just a string, so a given metafield of this type can have any value attached. On the other hand, dropdown and radio have a set of allowed values that can be input, and appear differently on a Public Signup Page. Defaults to 'text' - -## Enumeration - -`MetafieldInput` - -## Fields - -| Name | -| --- | -| `BALANCETRACKER` | -| `TEXT` | -| `RADIO` | -| `DROPDOWN` | - + +# Metafield Input + +Indicates how data should be added to the metafield. For example, a text type is just a string, so a given metafield of this type can have any value attached. On the other hand, dropdown and radio have a set of allowed values that can be input, and appear differently on a Public Signup Page. Defaults to 'text' + +## Enumeration + +`MetafieldInput` + +## Fields + +| Name | +| --- | +| `BALANCETRACKER` | +| `TEXT` | +| `RADIO` | +| `DROPDOWN` | + diff --git a/doc/models/metafield-scope.md b/doc/models/metafield-scope.md index 2bfcfc41..ce8cc9c4 100644 --- a/doc/models/metafield-scope.md +++ b/doc/models/metafield-scope.md @@ -1,33 +1,33 @@ - -# Metafield Scope - -Warning: When updating a metafield's scope attribute, all scope attributes must be passed. Partially complete scope attributes will override the existing settings. - -## Structure - -`MetafieldScope` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Csv` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from the csv export. | -| `Invoices` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from invoices. | -| `Statements` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from statements. | -| `Portal` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from the portal. | -| `PublicShow` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from being viewable by your ecosystem. | -| `PublicEdit` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from being edited by your ecosystem. | -| `Hosted` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "csv": "0", - "invoices": "0", - "statements": "0", - "portal": "0", - "public_show": "0" -} -``` - + +# Metafield Scope + +Warning: When updating a metafield's scope attribute, all scope attributes must be passed. Partially complete scope attributes will override the existing settings. + +## Structure + +`MetafieldScope` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Csv` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from the csv export. | +| `Invoices` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from invoices. | +| `Statements` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from statements. | +| `Portal` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from the portal. | +| `PublicShow` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from being viewable by your ecosystem. | +| `PublicEdit` | [`*models.IncludeOption`](../../doc/models/include-option.md) | Optional | Include (1) or exclude (0) metafields from being edited by your ecosystem. | +| `Hosted` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "csv": "0", + "invoices": "0", + "statements": "0", + "portal": "0", + "public_show": "0" +} +``` + diff --git a/doc/models/metafield.md b/doc/models/metafield.md index dec9a3eb..5c8b2903 100644 --- a/doc/models/metafield.md +++ b/doc/models/metafield.md @@ -1,36 +1,36 @@ - -# Metafield - -## Structure - -`Metafield` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Name` | `*string` | Optional | - | -| `Scope` | [`*models.MetafieldScope`](../../doc/models/metafield-scope.md) | Optional | Warning: When updating a metafield's scope attribute, all scope attributes must be passed. Partially complete scope attributes will override the existing settings. | -| `DataCount` | `*int` | Optional | the amount of subscriptions this metafield has been applied to in Chargify | -| `InputType` | [`*models.MetafieldInput`](../../doc/models/metafield-input.md) | Optional | Indicates how data should be added to the metafield. For example, a text type is just a string, so a given metafield of this type can have any value attached. On the other hand, dropdown and radio have a set of allowed values that can be input, and appear differently on a Public Signup Page. Defaults to 'text' | -| `Enum` | `Optional[interface{}]` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 52, - "name": "name8", - "scope": { - "csv": "0", - "invoices": "0", - "statements": "0", - "portal": "0", - "public_show": "0" - }, - "data_count": 216, - "input_type": "radio" -} -``` - + +# Metafield + +## Structure + +`Metafield` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Name` | `*string` | Optional | - | +| `Scope` | [`*models.MetafieldScope`](../../doc/models/metafield-scope.md) | Optional | Warning: When updating a metafield's scope attribute, all scope attributes must be passed. Partially complete scope attributes will override the existing settings. | +| `DataCount` | `*int` | Optional | the amount of subscriptions this metafield has been applied to in Chargify | +| `InputType` | [`*models.MetafieldInput`](../../doc/models/metafield-input.md) | Optional | Indicates how data should be added to the metafield. For example, a text type is just a string, so a given metafield of this type can have any value attached. On the other hand, dropdown and radio have a set of allowed values that can be input, and appear differently on a Public Signup Page. Defaults to 'text' | +| `Enum` | [`models.Optional[models.MetafieldEnum]`](../../doc/models/containers/metafield-enum.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "id": 52, + "name": "name8", + "scope": { + "csv": "0", + "invoices": "0", + "statements": "0", + "portal": "0", + "public_show": "0" + }, + "data_count": 216, + "input_type": "radio" +} +``` + diff --git a/doc/models/metered-component.md b/doc/models/metered-component.md index 1ec91a61..da3166cc 100644 --- a/doc/models/metered-component.md +++ b/doc/models/metered-component.md @@ -1,61 +1,52 @@ - -# Metered Component - -## Structure - -`MeteredComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `string` | Required | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | -| `UnitName` | `string` | Required | The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item | -| `Description` | `*string` | Optional | A description for the component that will be displayed to the user on the hosted signup page. | -| `Handle` | `*string` | Optional | A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'.
**Constraints**: *Pattern*: `^[a-z0-9][a-z0-9\-_:.]*$` | -| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | -| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `PricePoints` | [`[]models.ComponentPricePointItem`](../../doc/models/component-price-point-item.md) | Optional | - | -| `UnitPrice` | `*interface{}` | Optional | The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 | -| `TaxCode` | `*string` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | -| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | -| `PriceInCents` | `*string` | Optional | deprecated May 2011 - use unit_price instead | -| `DisplayOnHostedPage` | `*bool` | Optional | - | -| `AllowFractionalQuantities` | `*bool` | Optional | - | -| `PublicSignupPageIds` | `[]int` | Optional | - | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. | - -## Example (as JSON) - -```json -{ - "name": "name4", - "unit_name": "unit_name6", - "description": "description6", - "handle": "handle0", - "taxable": false, - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ], - "upgrade_charge": "full" -} -``` - + +# Metered Component + +## Structure + +`MeteredComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | +| `UnitName` | `string` | Required | The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item | +| `Description` | `*string` | Optional | A description for the component that will be displayed to the user on the hosted signup page. | +| `Handle` | `*string` | Optional | A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'.
**Constraints**: *Pattern*: `^[a-z0-9][a-z0-9\-_:.]*$` | +| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | +| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `PricePoints` | [`[]models.ComponentPricePointItem`](../../doc/models/component-price-point-item.md) | Optional | - | +| `UnitPrice` | [`*models.MeteredComponentUnitPrice`](../../doc/models/containers/metered-component-unit-price.md) | Optional | This is a container for one-of cases. | +| `TaxCode` | `*string` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | +| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | +| `PriceInCents` | `*string` | Optional | deprecated May 2011 - use unit_price instead | +| `DisplayOnHostedPage` | `*bool` | Optional | - | +| `AllowFractionalQuantities` | `*bool` | Optional | - | +| `PublicSignupPageIds` | `[]int` | Optional | - | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. | + +## Example (as JSON) + +```json +{ + "name": "name4", + "unit_name": "unit_name6", + "description": "description6", + "handle": "handle0", + "taxable": false, + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "upgrade_charge": "full" +} +``` + diff --git a/doc/models/metered-usage.md b/doc/models/metered-usage.md new file mode 100644 index 00000000..995a056f --- /dev/null +++ b/doc/models/metered-usage.md @@ -0,0 +1,31 @@ + +# Metered Usage + +## Structure + +`MeteredUsage` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PreviousUnitBalance` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `NewUnitBalance` | `int` | Required | - | +| `UsageQuantity` | `int` | Required | - | +| `ComponentId` | `int` | Required | - | +| `ComponentHandle` | `string` | Required | - | +| `Memo` | `string` | Required | - | + +## Example (as JSON) + +```json +{ + "previous_unit_balance": "previous_unit_balance6", + "new_unit_balance": 80, + "usage_quantity": 42, + "component_id": 4, + "component_handle": "component_handle8", + "memo": "memo2" +} +``` + diff --git a/doc/models/movement-line-item.md b/doc/models/movement-line-item.md index 92600324..0e6f6ceb 100644 --- a/doc/models/movement-line-item.md +++ b/doc/models/movement-line-item.md @@ -1,33 +1,33 @@ - -# Movement Line Item - -## Structure - -`MovementLineItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ProductId` | `*int` | Optional | - | -| `ComponentId` | `*int` | Optional | For Product (or "baseline") line items, this field will have a value of `0`. | -| `PricePointId` | `*int` | Optional | - | -| `Name` | `*string` | Optional | - | -| `Mrr` | `*int` | Optional | - | -| `MrrMovements` | [`[]models.MRRMovement`](../../doc/models/mrr-movement.md) | Optional | - | -| `Quantity` | `*int` | Optional | - | -| `PrevQuantity` | `*int` | Optional | - | -| `Recurring` | `*bool` | Optional | When `true`, the line item's MRR value will contribute to the `plan` breakout. When `false`, the line item contributes to the `usage` breakout. | - -## Example (as JSON) - -```json -{ - "product_id": 156, - "component_id": 68, - "price_point_id": 164, - "name": "name6", - "mrr": 154 -} -``` - + +# Movement Line Item + +## Structure + +`MovementLineItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProductId` | `*int` | Optional | - | +| `ComponentId` | `*int` | Optional | For Product (or "baseline") line items, this field will have a value of `0`. | +| `PricePointId` | `*int` | Optional | - | +| `Name` | `*string` | Optional | - | +| `Mrr` | `*int` | Optional | - | +| `MrrMovements` | [`[]models.MRRMovement`](../../doc/models/mrr-movement.md) | Optional | - | +| `Quantity` | `*int` | Optional | - | +| `PrevQuantity` | `*int` | Optional | - | +| `Recurring` | `*bool` | Optional | When `true`, the line item's MRR value will contribute to the `plan` breakout. When `false`, the line item contributes to the `usage` breakout. | + +## Example (as JSON) + +```json +{ + "product_id": 156, + "component_id": 68, + "price_point_id": 164, + "name": "name6", + "mrr": 154 +} +``` + diff --git a/doc/models/movement.md b/doc/models/movement.md index f765072c..33dd743d 100644 --- a/doc/models/movement.md +++ b/doc/models/movement.md @@ -1,33 +1,33 @@ - -# Movement - -## Structure - -`Movement` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Timestamp` | `*time.Time` | Optional | - | -| `AmountInCents` | `*int64` | Optional | - | -| `AmountFormatted` | `*string` | Optional | - | -| `Description` | `*string` | Optional | - | -| `Category` | `*string` | Optional | - | -| `Breakouts` | [`*models.Breakouts`](../../doc/models/breakouts.md) | Optional | - | -| `LineItems` | [`[]models.MovementLineItem`](../../doc/models/movement-line-item.md) | Optional | - | -| `SubscriptionId` | `*int` | Optional | - | -| `SubscriberName` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "timestamp": "2016-03-13T12:52:32.123Z", - "amount_in_cents": 174, - "amount_formatted": "amount_formatted4", - "description": "description2", - "category": "category0" -} -``` - + +# Movement + +## Structure + +`Movement` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Timestamp` | `*time.Time` | Optional | - | +| `AmountInCents` | `*int64` | Optional | - | +| `AmountFormatted` | `*string` | Optional | - | +| `Description` | `*string` | Optional | - | +| `Category` | `*string` | Optional | - | +| `Breakouts` | [`*models.Breakouts`](../../doc/models/breakouts.md) | Optional | - | +| `LineItems` | [`[]models.MovementLineItem`](../../doc/models/movement-line-item.md) | Optional | - | +| `SubscriptionId` | `*int` | Optional | - | +| `SubscriberName` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "timestamp": "2016-03-13T12:52:32.123Z", + "amount_in_cents": 174, + "amount_formatted": "amount_formatted4", + "description": "description2", + "category": "category0" +} +``` + diff --git a/doc/models/mrr-movement.md b/doc/models/mrr-movement.md index eb21eb18..ad2e4ff7 100644 --- a/doc/models/mrr-movement.md +++ b/doc/models/mrr-movement.md @@ -1,27 +1,27 @@ - -# MRR Movement - -## Structure - -`MRRMovement` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Amount` | `*int` | Optional | - | -| `Category` | `*string` | Optional | - | -| `SubscriberDelta` | `*int` | Optional | - | -| `LeadDelta` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "amount": 210, - "category": "category0", - "subscriber_delta": 170, - "lead_delta": 198 -} -``` - + +# MRR Movement + +## Structure + +`MRRMovement` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Amount` | `*int` | Optional | - | +| `Category` | `*string` | Optional | - | +| `SubscriberDelta` | `*int` | Optional | - | +| `LeadDelta` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "amount": 210, + "category": "category0", + "subscriber_delta": 170, + "lead_delta": 198 +} +``` + diff --git a/doc/models/mrr-response.md b/doc/models/mrr-response.md index 14ead27c..27883856 100644 --- a/doc/models/mrr-response.md +++ b/doc/models/mrr-response.md @@ -1,32 +1,32 @@ - -# MRR Response - -## Structure - -`MRRResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Mrr` | [`models.MRR`](../../doc/models/mrr.md) | Required | - | - -## Example (as JSON) - -```json -{ - "mrr": { - "amount_in_cents": 198, - "amount_formatted": "amount_formatted6", - "currency": "currency4", - "currency_symbol": "currency_symbol2", - "breakouts": { - "plan_amount_in_cents": 254, - "plan_amount_formatted": "plan_amount_formatted0", - "usage_amount_in_cents": 106, - "usage_amount_formatted": "usage_amount_formatted8" - } - } -} -``` - + +# MRR Response + +## Structure + +`MRRResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Mrr` | [`models.MRR`](../../doc/models/mrr.md) | Required | - | + +## Example (as JSON) + +```json +{ + "mrr": { + "amount_in_cents": 198, + "amount_formatted": "amount_formatted6", + "currency": "currency4", + "currency_symbol": "currency_symbol2", + "breakouts": { + "plan_amount_in_cents": 254, + "plan_amount_formatted": "plan_amount_formatted0", + "usage_amount_in_cents": 106, + "usage_amount_formatted": "usage_amount_formatted8" + } + } +} +``` + diff --git a/doc/models/mrr.md b/doc/models/mrr.md index 8a79b26b..35d6b94d 100644 --- a/doc/models/mrr.md +++ b/doc/models/mrr.md @@ -1,35 +1,35 @@ - -# MRR - -## Structure - -`MRR` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `AmountInCents` | `*int64` | Optional | - | -| `AmountFormatted` | `*string` | Optional | - | -| `Currency` | `*string` | Optional | - | -| `CurrencySymbol` | `*string` | Optional | - | -| `Breakouts` | [`*models.Breakouts`](../../doc/models/breakouts.md) | Optional | - | -| `AtTime` | `*time.Time` | Optional | ISO8601 timestamp | - -## Example (as JSON) - -```json -{ - "amount_in_cents": 208, - "amount_formatted": "amount_formatted2", - "currency": "currency0", - "currency_symbol": "currency_symbol8", - "breakouts": { - "plan_amount_in_cents": 254, - "plan_amount_formatted": "plan_amount_formatted0", - "usage_amount_in_cents": 106, - "usage_amount_formatted": "usage_amount_formatted8" - } -} -``` - + +# MRR + +## Structure + +`MRR` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `AmountInCents` | `*int64` | Optional | - | +| `AmountFormatted` | `*string` | Optional | - | +| `Currency` | `*string` | Optional | - | +| `CurrencySymbol` | `*string` | Optional | - | +| `Breakouts` | [`*models.Breakouts`](../../doc/models/breakouts.md) | Optional | - | +| `AtTime` | `*time.Time` | Optional | ISO8601 timestamp | + +## Example (as JSON) + +```json +{ + "amount_in_cents": 208, + "amount_formatted": "amount_formatted2", + "currency": "currency0", + "currency_symbol": "currency_symbol8", + "breakouts": { + "plan_amount_in_cents": 254, + "plan_amount_formatted": "plan_amount_formatted0", + "usage_amount_in_cents": 106, + "usage_amount_formatted": "usage_amount_formatted8" + } +} +``` + diff --git a/doc/models/multi-invoice-payment-response.md b/doc/models/multi-invoice-payment-response.md index 8302cf03..dbc04ecf 100644 --- a/doc/models/multi-invoice-payment-response.md +++ b/doc/models/multi-invoice-payment-response.md @@ -1,42 +1,42 @@ - -# Multi Invoice Payment Response - -## Structure - -`MultiInvoicePaymentResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Payment` | [`models.MultiInvoicePayment`](../../doc/models/multi-invoice-payment.md) | Required | - | - -## Example (as JSON) - -```json -{ - "payment": { - "transaction_id": 224, - "total_amount": "total_amount2", - "currency_code": "currency_code2", - "applications": [ - { - "invoice_uid": "invoice_uid8", - "application_uid": "application_uid8", - "applied_amount": "applied_amount0" - }, - { - "invoice_uid": "invoice_uid8", - "application_uid": "application_uid8", - "applied_amount": "applied_amount0" - }, - { - "invoice_uid": "invoice_uid8", - "application_uid": "application_uid8", - "applied_amount": "applied_amount0" - } - ] - } -} -``` - + +# Multi Invoice Payment Response + +## Structure + +`MultiInvoicePaymentResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Payment` | [`models.MultiInvoicePayment`](../../doc/models/multi-invoice-payment.md) | Required | - | + +## Example (as JSON) + +```json +{ + "payment": { + "transaction_id": 224, + "total_amount": "total_amount2", + "currency_code": "currency_code2", + "applications": [ + { + "invoice_uid": "invoice_uid8", + "application_uid": "application_uid8", + "applied_amount": "applied_amount0" + }, + { + "invoice_uid": "invoice_uid8", + "application_uid": "application_uid8", + "applied_amount": "applied_amount0" + }, + { + "invoice_uid": "invoice_uid8", + "application_uid": "application_uid8", + "applied_amount": "applied_amount0" + } + ] + } +} +``` + diff --git a/doc/models/multi-invoice-payment.md b/doc/models/multi-invoice-payment.md index 19015da6..cff26b17 100644 --- a/doc/models/multi-invoice-payment.md +++ b/doc/models/multi-invoice-payment.md @@ -1,33 +1,33 @@ - -# Multi Invoice Payment - -## Structure - -`MultiInvoicePayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TransactionId` | `*int` | Optional | The numeric ID of the transaction. | -| `TotalAmount` | `*string` | Optional | Dollar amount of the sum of the paid invoices. | -| `CurrencyCode` | `*string` | Optional | The ISO 4217 currency code (3 character string) representing the currency of invoice transaction. | -| `Applications` | [`[]models.InvoicePaymentApplication`](../../doc/models/invoice-payment-application.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "transaction_id": 144, - "total_amount": "total_amount2", - "currency_code": "currency_code2", - "applications": [ - { - "invoice_uid": "invoice_uid8", - "application_uid": "application_uid8", - "applied_amount": "applied_amount0" - } - ] -} -``` - + +# Multi Invoice Payment + +## Structure + +`MultiInvoicePayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TransactionId` | `*int` | Optional | The numeric ID of the transaction. | +| `TotalAmount` | `*string` | Optional | Dollar amount of the sum of the paid invoices. | +| `CurrencyCode` | `*string` | Optional | The ISO 4217 currency code (3 character string) representing the currency of invoice transaction. | +| `Applications` | [`[]models.InvoicePaymentApplication`](../../doc/models/invoice-payment-application.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "transaction_id": 144, + "total_amount": "total_amount2", + "currency_code": "currency_code2", + "applications": [ + { + "invoice_uid": "invoice_uid8", + "application_uid": "application_uid8", + "applied_amount": "applied_amount0" + } + ] +} +``` + diff --git a/doc/models/nested-subscription-group.md b/doc/models/nested-subscription-group.md index e17d50c3..91481466 100644 --- a/doc/models/nested-subscription-group.md +++ b/doc/models/nested-subscription-group.md @@ -1,27 +1,27 @@ - -# Nested Subscription Group - -## Structure - -`NestedSubscriptionGroup` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | The UID for the group | -| `Scheme` | `*int` | Optional | Whether the group is configured to rely on a primary subscription for billing. At this time, it will always be 1. | -| `PrimarySubscriptionId` | `*int` | Optional | The subscription ID of the primary within the group. Applicable to scheme 1. | -| `Primary` | `*bool` | Optional | A boolean indicating whether the subscription is the primary in the group. Applicable to scheme 1. | - -## Example (as JSON) - -```json -{ - "uid": "uid2", - "scheme": 62, - "primary_subscription_id": 10, - "primary": false -} -``` - + +# Nested Subscription Group + +## Structure + +`NestedSubscriptionGroup` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | The UID for the group | +| `Scheme` | `*int` | Optional | Whether the group is configured to rely on a primary subscription for billing. At this time, it will always be 1. | +| `PrimarySubscriptionId` | `*int` | Optional | The subscription ID of the primary within the group. Applicable to scheme 1. | +| `Primary` | `*bool` | Optional | A boolean indicating whether the subscription is the primary in the group. Applicable to scheme 1. | + +## Example (as JSON) + +```json +{ + "uid": "uid2", + "scheme": 62, + "primary_subscription_id": 10, + "primary": false +} +``` + diff --git a/doc/models/net-terms.md b/doc/models/net-terms.md index 1ea81d91..a5e286c4 100644 --- a/doc/models/net-terms.md +++ b/doc/models/net-terms.md @@ -1,29 +1,29 @@ - -# Net Terms - -## Structure - -`NetTerms` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `DefaultNetTerms` | `*int` | Optional | **Default**: `0` | -| `AutomaticNetTerms` | `*int` | Optional | **Default**: `0` | -| `RemittanceNetTerms` | `*int` | Optional | **Default**: `0` | -| `NetTermsOnRemittanceSignupsEnabled` | `*bool` | Optional | **Default**: `false` | -| `CustomNetTermsEnabled` | `*bool` | Optional | **Default**: `false` | - -## Example (as JSON) - -```json -{ - "default_net_terms": 0, - "automatic_net_terms": 0, - "remittance_net_terms": 0, - "net_terms_on_remittance_signups_enabled": false, - "custom_net_terms_enabled": false -} -``` - + +# Net Terms + +## Structure + +`NetTerms` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `DefaultNetTerms` | `*int` | Optional | **Default**: `0` | +| `AutomaticNetTerms` | `*int` | Optional | **Default**: `0` | +| `RemittanceNetTerms` | `*int` | Optional | **Default**: `0` | +| `NetTermsOnRemittanceSignupsEnabled` | `*bool` | Optional | **Default**: `false` | +| `CustomNetTermsEnabled` | `*bool` | Optional | **Default**: `false` | + +## Example (as JSON) + +```json +{ + "default_net_terms": 0, + "automatic_net_terms": 0, + "remittance_net_terms": 0, + "net_terms_on_remittance_signups_enabled": false, + "custom_net_terms_enabled": false +} +``` + diff --git a/doc/models/offer-discount.md b/doc/models/offer-discount.md index 84d5baf5..5516795c 100644 --- a/doc/models/offer-discount.md +++ b/doc/models/offer-discount.md @@ -1,25 +1,25 @@ - -# Offer Discount - -## Structure - -`OfferDiscount` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CouponCode` | `*string` | Optional | - | -| `CouponId` | `*int` | Optional | - | -| `CouponName` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "coupon_code": "coupon_code8", - "coupon_id": 86, - "coupon_name": "coupon_name4" -} -``` - + +# Offer Discount + +## Structure + +`OfferDiscount` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CouponCode` | `*string` | Optional | - | +| `CouponId` | `*int` | Optional | - | +| `CouponName` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "coupon_code": "coupon_code8", + "coupon_id": 86, + "coupon_name": "coupon_name4" +} +``` + diff --git a/doc/models/offer-item.md b/doc/models/offer-item.md index 4894ccc2..af75c492 100644 --- a/doc/models/offer-item.md +++ b/doc/models/offer-item.md @@ -1,34 +1,34 @@ - -# Offer Item - -## Structure - -`OfferItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ComponentId` | `*int` | Optional | - | -| `PricePointId` | `*int` | Optional | - | -| `StartingQuantity` | `*string` | Optional | - | -| `Editable` | `*bool` | Optional | - | -| `ComponentUnitPrice` | `*string` | Optional | - | -| `ComponentName` | `*string` | Optional | - | -| `PricePointName` | `*string` | Optional | - | -| `CurrencyPrices` | [`[]models.CurrencyPrice`](../../doc/models/currency-price.md) | Optional | - | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of '30' coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | - -## Example (as JSON) - -```json -{ - "component_id": 216, - "price_point_id": 16, - "starting_quantity": "starting_quantity0", - "editable": false, - "component_unit_price": "component_unit_price8" -} -``` - + +# Offer Item + +## Structure + +`OfferItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ComponentId` | `*int` | Optional | - | +| `PricePointId` | `*int` | Optional | - | +| `StartingQuantity` | `*string` | Optional | - | +| `Editable` | `*bool` | Optional | - | +| `ComponentUnitPrice` | `*string` | Optional | - | +| `ComponentName` | `*string` | Optional | - | +| `PricePointName` | `*string` | Optional | - | +| `CurrencyPrices` | [`[]models.CurrencyPrice`](../../doc/models/currency-price.md) | Optional | - | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of '30' coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | + +## Example (as JSON) + +```json +{ + "component_id": 216, + "price_point_id": 16, + "starting_quantity": "starting_quantity0", + "editable": false, + "component_unit_price": "component_unit_price8" +} +``` + diff --git a/doc/models/offer-response.md b/doc/models/offer-response.md index 21b52066..4c5480eb 100644 --- a/doc/models/offer-response.md +++ b/doc/models/offer-response.md @@ -1,27 +1,27 @@ - -# Offer Response - -## Structure - -`OfferResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Offer` | [`*models.Offer`](../../doc/models/offer.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "offer": { - "id": 28, - "site_id": 210, - "product_family_id": 224, - "product_id": 30, - "product_price_point_id": 150 - } -} -``` - + +# Offer Response + +## Structure + +`OfferResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Offer` | [`*models.Offer`](../../doc/models/offer.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "offer": { + "id": 28, + "site_id": 210, + "product_family_id": 224, + "product_id": 30, + "product_price_point_id": 150 + } +} +``` + diff --git a/doc/models/offer-signup-page.md b/doc/models/offer-signup-page.md index b97b7b6b..49ce4440 100644 --- a/doc/models/offer-signup-page.md +++ b/doc/models/offer-signup-page.md @@ -1,30 +1,30 @@ - -# Offer Signup Page - -## Structure - -`OfferSignupPage` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Nickname` | `*string` | Optional | - | -| `Enabled` | `*bool` | Optional | - | -| `ReturnUrl` | `*string` | Optional | - | -| `ReturnParams` | `*string` | Optional | - | -| `Url` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 50, - "nickname": "nickname8", - "enabled": false, - "return_url": "return_url2", - "return_params": "return_params0" -} -``` - + +# Offer Signup Page + +## Structure + +`OfferSignupPage` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Nickname` | `*string` | Optional | - | +| `Enabled` | `*bool` | Optional | - | +| `ReturnUrl` | `*string` | Optional | - | +| `ReturnParams` | `*string` | Optional | - | +| `Url` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 50, + "nickname": "nickname8", + "enabled": false, + "return_url": "return_url2", + "return_params": "return_params0" +} +``` + diff --git a/doc/models/offer.md b/doc/models/offer.md index 1f17ba38..54f2e2ab 100644 --- a/doc/models/offer.md +++ b/doc/models/offer.md @@ -1,43 +1,43 @@ - -# Offer - -## Structure - -`Offer` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `SiteId` | `*int` | Optional | - | -| `ProductFamilyId` | `*int` | Optional | - | -| `ProductId` | `*int` | Optional | - | -| `ProductPricePointId` | `*int` | Optional | - | -| `ProductRevisableNumber` | `*int` | Optional | - | -| `Name` | `*string` | Optional | - | -| `Handle` | `*string` | Optional | - | -| `Description` | `Optional[string]` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `UpdatedAt` | `*time.Time` | Optional | - | -| `ArchivedAt` | `Optional[time.Time]` | Optional | - | -| `OfferItems` | [`[]models.OfferItem`](../../doc/models/offer-item.md) | Optional | - | -| `OfferDiscounts` | [`[]models.OfferDiscount`](../../doc/models/offer-discount.md) | Optional | - | -| `ProductFamilyName` | `*string` | Optional | - | -| `ProductName` | `*string` | Optional | - | -| `ProductPricePointName` | `*string` | Optional | - | -| `ProductPriceInCents` | `*int64` | Optional | - | -| `OfferSignupPages` | [`[]models.OfferSignupPage`](../../doc/models/offer-signup-page.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 154, - "site_id": 80, - "product_family_id": 158, - "product_id": 96, - "product_price_point_id": 20 -} -``` - + +# Offer + +## Structure + +`Offer` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `SiteId` | `*int` | Optional | - | +| `ProductFamilyId` | `*int` | Optional | - | +| `ProductId` | `*int` | Optional | - | +| `ProductPricePointId` | `*int` | Optional | - | +| `ProductRevisableNumber` | `*int` | Optional | - | +| `Name` | `*string` | Optional | - | +| `Handle` | `*string` | Optional | - | +| `Description` | `models.Optional[string]` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `UpdatedAt` | `*time.Time` | Optional | - | +| `ArchivedAt` | `models.Optional[time.Time]` | Optional | - | +| `OfferItems` | [`[]models.OfferItem`](../../doc/models/offer-item.md) | Optional | - | +| `OfferDiscounts` | [`[]models.OfferDiscount`](../../doc/models/offer-discount.md) | Optional | - | +| `ProductFamilyName` | `*string` | Optional | - | +| `ProductName` | `*string` | Optional | - | +| `ProductPricePointName` | `*string` | Optional | - | +| `ProductPriceInCents` | `*int64` | Optional | - | +| `OfferSignupPages` | [`[]models.OfferSignupPage`](../../doc/models/offer-signup-page.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 154, + "site_id": 80, + "product_family_id": 158, + "product_id": 96, + "product_price_point_id": 20 +} +``` + diff --git a/doc/models/on-off-component.md b/doc/models/on-off-component.md index 8cab833d..05f334af 100644 --- a/doc/models/on-off-component.md +++ b/doc/models/on-off-component.md @@ -1,85 +1,58 @@ - -# On Off Component - -## Structure - -`OnOffComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `string` | Required | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | -| `Description` | `*string` | Optional | A description for the component that will be displayed to the user on the hosted signup page. | -| `Handle` | `*string` | Optional | A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'.
**Constraints**: *Pattern*: `^[a-z0-9][a-z0-9\-_:.]*$` | -| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | -| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `PricePoints` | [`[]models.ComponentPricePointItem`](../../doc/models/component-price-point-item.md) | Optional | - | -| `UnitPrice` | `*interface{}` | Optional | The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 | -| `TaxCode` | `*string` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | -| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | -| `PriceInCents` | `*string` | Optional | deprecated May 2011 - use unit_price instead | -| `DisplayOnHostedPage` | `*bool` | Optional | - | -| `AllowFractionalQuantities` | `*bool` | Optional | - | -| `PublicSignupPageIds` | `[]int` | Optional | - | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. | - -## Example (as JSON) - -```json -{ - "name": "name2", - "description": "description2", - "handle": "handle8", - "taxable": false, - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ], - "upgrade_charge": "prorated" -} -``` - + +# On Off Component + +## Structure + +`OnOffComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | +| `Description` | `*string` | Optional | A description for the component that will be displayed to the user on the hosted signup page. | +| `Handle` | `*string` | Optional | A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'.
**Constraints**: *Pattern*: `^[a-z0-9][a-z0-9\-_:.]*$` | +| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `PricePoints` | [`[]models.ComponentPricePointItem`](../../doc/models/component-price-point-item.md) | Optional | - | +| `UnitPrice` | [`*models.OnOffComponentUnitPrice`](../../doc/models/containers/on-off-component-unit-price.md) | Optional | This is a container for one-of cases. | +| `TaxCode` | `*string` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | +| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | +| `PriceInCents` | `*string` | Optional | deprecated May 2011 - use unit_price instead | +| `DisplayOnHostedPage` | `*bool` | Optional | - | +| `AllowFractionalQuantities` | `*bool` | Optional | - | +| `PublicSignupPageIds` | `[]int` | Optional | - | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. | + +## Example (as JSON) + +```json +{ + "name": "name2", + "description": "description2", + "handle": "handle8", + "taxable": false, + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "upgrade_charge": "prorated" +} +``` + diff --git a/doc/models/organization-address.md b/doc/models/organization-address.md index e048b1f3..38ac40f9 100644 --- a/doc/models/organization-address.md +++ b/doc/models/organization-address.md @@ -1,32 +1,32 @@ - -# Organization Address - -## Structure - -`OrganizationAddress` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Street` | `Optional[string]` | Optional | - | -| `Line2` | `Optional[string]` | Optional | - | -| `City` | `Optional[string]` | Optional | - | -| `State` | `Optional[string]` | Optional | - | -| `Zip` | `Optional[string]` | Optional | - | -| `Country` | `Optional[string]` | Optional | - | -| `Name` | `Optional[string]` | Optional | - | -| `Phone` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "street": "street4", - "line2": "line28", - "city": "city4", - "state": "state0", - "zip": "zip2" -} -``` - + +# Organization Address + +## Structure + +`OrganizationAddress` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Street` | `models.Optional[string]` | Optional | - | +| `Line2` | `models.Optional[string]` | Optional | - | +| `City` | `models.Optional[string]` | Optional | - | +| `State` | `models.Optional[string]` | Optional | - | +| `Zip` | `models.Optional[string]` | Optional | - | +| `Country` | `models.Optional[string]` | Optional | - | +| `Name` | `models.Optional[string]` | Optional | - | +| `Phone` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "street": "street4", + "line2": "line28", + "city": "city4", + "state": "state0", + "zip": "zip2" +} +``` + diff --git a/doc/models/origin-invoice.md b/doc/models/origin-invoice.md index c99b6738..c36f090b 100644 --- a/doc/models/origin-invoice.md +++ b/doc/models/origin-invoice.md @@ -1,23 +1,23 @@ - -# Origin Invoice - -## Structure - -`OriginInvoice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | The UID of the invoice serving as an origin invoice. | -| `Number` | `*string` | Optional | The number of the invoice serving as an origin invoice. | - -## Example (as JSON) - -```json -{ - "uid": "uid0", - "number": "number8" -} -``` - + +# Origin Invoice + +## Structure + +`OriginInvoice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | The UID of the invoice serving as an origin invoice. | +| `Number` | `*string` | Optional | The number of the invoice serving as an origin invoice. | + +## Example (as JSON) + +```json +{ + "uid": "uid0", + "number": "number8" +} +``` + diff --git a/doc/models/overage-pricing.md b/doc/models/overage-pricing.md index 0f9fccb9..9ea7444f 100644 --- a/doc/models/overage-pricing.md +++ b/doc/models/overage-pricing.md @@ -1,66 +1,39 @@ - -# Overage Pricing - -## Structure - -`OveragePricing` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] -} -``` - + +# Overage Pricing + +## Structure + +`OveragePricing` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ] +} +``` + diff --git a/doc/models/override-subscription-request.md b/doc/models/override-subscription-request.md index 0a809fe0..3ac3df60 100644 --- a/doc/models/override-subscription-request.md +++ b/doc/models/override-subscription-request.md @@ -1,27 +1,27 @@ - -# Override Subscription Request - -## Structure - -`OverrideSubscriptionRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Subscription` | [`models.OverrideSubscription`](../../doc/models/override-subscription.md) | Required | - | - -## Example (as JSON) - -```json -{ - "subscription": { - "activated_at": "2016-03-13T12:52:32.123Z", - "canceled_at": "2016-03-13T12:52:32.123Z", - "cancellation_message": "cancellation_message2", - "expires_at": "2016-03-13T12:52:32.123Z", - "current_period_starts_at": "2016-03-13T12:52:32.123Z" - } -} -``` - + +# Override Subscription Request + +## Structure + +`OverrideSubscriptionRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Subscription` | [`models.OverrideSubscription`](../../doc/models/override-subscription.md) | Required | - | + +## Example (as JSON) + +```json +{ + "subscription": { + "activated_at": "2016-03-13T12:52:32.123Z", + "canceled_at": "2016-03-13T12:52:32.123Z", + "cancellation_message": "cancellation_message2", + "expires_at": "2016-03-13T12:52:32.123Z", + "current_period_starts_at": "2016-03-13T12:52:32.123Z" + } +} +``` + diff --git a/doc/models/override-subscription.md b/doc/models/override-subscription.md index 273fc1f2..9c2eb3bf 100644 --- a/doc/models/override-subscription.md +++ b/doc/models/override-subscription.md @@ -1,29 +1,29 @@ - -# Override Subscription - -## Structure - -`OverrideSubscription` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ActivatedAt` | `*time.Time` | Optional | Can be used to record an external signup date. Chargify uses this field to record when a subscription first goes active (either at signup or at trial end). Only ISO8601 format is supported. | -| `CanceledAt` | `*time.Time` | Optional | Can be used to record an external cancellation date. Chargify sets this field automatically when a subscription is canceled, whether by request or via dunning. Only ISO8601 format is supported. | -| `CancellationMessage` | `*string` | Optional | Can be used to record a reason for the original cancellation. | -| `ExpiresAt` | `*time.Time` | Optional | Can be used to record an external expiration date. Chargify sets this field automatically when a subscription expires (ceases billing) after a prescribed amount of time. Only ISO8601 format is supported. | -| `CurrentPeriodStartsAt` | `*time.Time` | Optional | Can only be used when a subscription is unbilled, which happens when a future initial billing date is passed at subscription creation. The value passed must be before the current date and time. Allows you to set when the period started so mid period component allocations have the correct proration. Only ISO8601 format is supported. | - -## Example (as JSON) - -```json -{ - "activated_at": "2016-03-13T12:52:32.123Z", - "canceled_at": "2016-03-13T12:52:32.123Z", - "cancellation_message": "cancellation_message4", - "expires_at": "2016-03-13T12:52:32.123Z", - "current_period_starts_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Override Subscription + +## Structure + +`OverrideSubscription` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ActivatedAt` | `*time.Time` | Optional | Can be used to record an external signup date. Chargify uses this field to record when a subscription first goes active (either at signup or at trial end). Only ISO8601 format is supported. | +| `CanceledAt` | `*time.Time` | Optional | Can be used to record an external cancellation date. Chargify sets this field automatically when a subscription is canceled, whether by request or via dunning. Only ISO8601 format is supported. | +| `CancellationMessage` | `*string` | Optional | Can be used to record a reason for the original cancellation. | +| `ExpiresAt` | `*time.Time` | Optional | Can be used to record an external expiration date. Chargify sets this field automatically when a subscription expires (ceases billing) after a prescribed amount of time. Only ISO8601 format is supported. | +| `CurrentPeriodStartsAt` | `*time.Time` | Optional | Can only be used when a subscription is unbilled, which happens when a future initial billing date is passed at subscription creation. The value passed must be before the current date and time. Allows you to set when the period started so mid period component allocations have the correct proration. Only ISO8601 format is supported. | + +## Example (as JSON) + +```json +{ + "activated_at": "2016-03-13T12:52:32.123Z", + "canceled_at": "2016-03-13T12:52:32.123Z", + "cancellation_message": "cancellation_message4", + "expires_at": "2016-03-13T12:52:32.123Z", + "current_period_starts_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/paginated-metadata.md b/doc/models/paginated-metadata.md index c1254534..6c0e82d7 100644 --- a/doc/models/paginated-metadata.md +++ b/doc/models/paginated-metadata.md @@ -1,44 +1,44 @@ - -# Paginated Metadata - -## Structure - -`PaginatedMetadata` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TotalCount` | `*int` | Optional | - | -| `CurrentPage` | `*int` | Optional | - | -| `TotalPages` | `*int` | Optional | - | -| `PerPage` | `*int` | Optional | - | -| `Metadata` | [`[]models.Metadata`](../../doc/models/metadata.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "total_count": 26, - "current_page": 2, - "total_pages": 14, - "per_page": 20, - "metadata": [ - { - "id": 50, - "value": "value8", - "resource_id": 134, - "name": "name6", - "deleted_at": "2016-03-13T12:52:32.123Z" - }, - { - "id": 50, - "value": "value8", - "resource_id": 134, - "name": "name6", - "deleted_at": "2016-03-13T12:52:32.123Z" - } - ] -} -``` - + +# Paginated Metadata + +## Structure + +`PaginatedMetadata` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TotalCount` | `*int` | Optional | - | +| `CurrentPage` | `*int` | Optional | - | +| `TotalPages` | `*int` | Optional | - | +| `PerPage` | `*int` | Optional | - | +| `Metadata` | [`[]models.Metadata`](../../doc/models/metadata.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "total_count": 26, + "current_page": 2, + "total_pages": 14, + "per_page": 20, + "metadata": [ + { + "id": 50, + "value": "value8", + "resource_id": 134, + "name": "name6", + "deleted_at": "2016-03-13T12:52:32.123Z" + }, + { + "id": 50, + "value": "value8", + "resource_id": 134, + "name": "name6", + "deleted_at": "2016-03-13T12:52:32.123Z" + } + ] +} +``` + diff --git a/doc/models/paid-invoice.md b/doc/models/paid-invoice.md index e763abff..fe00e4e3 100644 --- a/doc/models/paid-invoice.md +++ b/doc/models/paid-invoice.md @@ -1,27 +1,27 @@ - -# Paid Invoice - -## Structure - -`PaidInvoice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `InvoiceId` | `*string` | Optional | The uid of the paid invoice | -| `Status` | [`*models.InvoiceStatus`](../../doc/models/invoice-status.md) | Optional | The current status of the invoice. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. | -| `DueAmount` | `*string` | Optional | The remaining due amount on the invoice | -| `PaidAmount` | `*string` | Optional | The total amount paid on this invoice (including any prior payments) | - -## Example (as JSON) - -```json -{ - "invoice_id": "invoice_id6", - "status": "draft", - "due_amount": "due_amount8", - "paid_amount": "paid_amount8" -} -``` - + +# Paid Invoice + +## Structure + +`PaidInvoice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `InvoiceId` | `*string` | Optional | The uid of the paid invoice | +| `Status` | [`*models.InvoiceStatus`](../../doc/models/invoice-status.md) | Optional | The current status of the invoice. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. | +| `DueAmount` | `*string` | Optional | The remaining due amount on the invoice | +| `PaidAmount` | `*string` | Optional | The total amount paid on this invoice (including any prior payments) | + +## Example (as JSON) + +```json +{ + "invoice_id": "invoice_id6", + "status": "draft", + "due_amount": "due_amount8", + "paid_amount": "paid_amount8" +} +``` + diff --git a/doc/models/pause-request.md b/doc/models/pause-request.md index 728f1d7b..64018ab5 100644 --- a/doc/models/pause-request.md +++ b/doc/models/pause-request.md @@ -1,25 +1,25 @@ - -# Pause Request - -Allows to pause a Subscription - -## Structure - -`PauseRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Hold` | [`*models.AutoResume`](../../doc/models/auto-resume.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "hold": { - "automatically_resume_at": "2016-03-13T12:52:32.123Z" - } -} -``` - + +# Pause Request + +Allows to pause a Subscription + +## Structure + +`PauseRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Hold` | [`*models.AutoResume`](../../doc/models/auto-resume.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "hold": { + "automatically_resume_at": "2016-03-13T12:52:32.123Z" + } +} +``` + diff --git a/doc/models/payer-attributes.md b/doc/models/payer-attributes.md index 36cf0f62..3d76a863 100644 --- a/doc/models/payer-attributes.md +++ b/doc/models/payer-attributes.md @@ -1,46 +1,46 @@ - -# Payer Attributes - -## Structure - -`PayerAttributes` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `FirstName` | `*string` | Optional | - | -| `LastName` | `*string` | Optional | - | -| `Email` | `*string` | Optional | - | -| `CcEmails` | `*string` | Optional | - | -| `Organization` | `*string` | Optional | - | -| `Reference` | `*string` | Optional | - | -| `Address` | `*string` | Optional | - | -| `Address2` | `*string` | Optional | - | -| `City` | `*string` | Optional | - | -| `State` | `*string` | Optional | - | -| `Zip` | `*string` | Optional | - | -| `Country` | `*string` | Optional | - | -| `Phone` | `*string` | Optional | - | -| `Locale` | `*string` | Optional | - | -| `VatNumber` | `*string` | Optional | - | -| `TaxExempt` | `*string` | Optional | - | -| `TaxExemptReason` | `*string` | Optional | - | -| `Metafields` | `map[string]string` | Optional | (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. | - -## Example (as JSON) - -```json -{ - "metafields": { - "custom_field_name_1": "custom_field_value_1", - "custom_field_name_2": "custom_field_value_2" - }, - "first_name": "first_name4", - "last_name": "last_name2", - "email": "email2", - "cc_emails": "cc_emails4", - "organization": "organization8" -} -``` - + +# Payer Attributes + +## Structure + +`PayerAttributes` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FirstName` | `*string` | Optional | - | +| `LastName` | `*string` | Optional | - | +| `Email` | `*string` | Optional | - | +| `CcEmails` | `*string` | Optional | - | +| `Organization` | `*string` | Optional | - | +| `Reference` | `*string` | Optional | - | +| `Address` | `*string` | Optional | - | +| `Address2` | `*string` | Optional | - | +| `City` | `*string` | Optional | - | +| `State` | `*string` | Optional | - | +| `Zip` | `*string` | Optional | - | +| `Country` | `*string` | Optional | - | +| `Phone` | `*string` | Optional | - | +| `Locale` | `*string` | Optional | - | +| `VatNumber` | `*string` | Optional | - | +| `TaxExempt` | `*bool` | Optional | - | +| `TaxExemptReason` | `*string` | Optional | - | +| `Metafields` | `map[string]string` | Optional | (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. | + +## Example (as JSON) + +```json +{ + "metafields": { + "custom_field_name_1": "custom_field_value_1", + "custom_field_name_2": "custom_field_value_2" + }, + "first_name": "first_name4", + "last_name": "last_name2", + "email": "email2", + "cc_emails": "cc_emails4", + "organization": "organization8" +} +``` + diff --git a/doc/models/payer-error.md b/doc/models/payer-error.md index f9a1a1ce..35f6854d 100644 --- a/doc/models/payer-error.md +++ b/doc/models/payer-error.md @@ -1,34 +1,34 @@ - -# Payer Error - -## Structure - -`PayerError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `LastName` | `[]string` | Optional | - | -| `FirstName` | `[]string` | Optional | - | -| `Email` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "last_name": [ - "last_name1", - "last_name2", - "last_name3" - ], - "first_name": [ - "first_name4", - "first_name5" - ], - "email": [ - "email4" - ] -} -``` - + +# Payer Error + +## Structure + +`PayerError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `LastName` | `[]string` | Optional | - | +| `FirstName` | `[]string` | Optional | - | +| `Email` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "last_name": [ + "last_name1", + "last_name2", + "last_name3" + ], + "first_name": [ + "first_name4", + "first_name5" + ], + "email": [ + "email4" + ] +} +``` + diff --git a/doc/models/payment-collection-method-changed.md b/doc/models/payment-collection-method-changed.md new file mode 100644 index 00000000..dacd8f21 --- /dev/null +++ b/doc/models/payment-collection-method-changed.md @@ -0,0 +1,23 @@ + +# Payment Collection Method Changed + +## Structure + +`PaymentCollectionMethodChanged` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PreviousValue` | `string` | Required | - | +| `CurrentValue` | `string` | Required | - | + +## Example (as JSON) + +```json +{ + "previous_value": "previous_value4", + "current_value": "current_value2" +} +``` + diff --git a/doc/models/payment-for-allocation.md b/doc/models/payment-for-allocation.md index 4ffac3e9..343ba68b 100644 --- a/doc/models/payment-for-allocation.md +++ b/doc/models/payment-for-allocation.md @@ -1,29 +1,29 @@ - -# Payment for Allocation - -Information for captured payment, if applicable - -## Structure - -`PaymentForAllocation` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `AmountInCents` | `*int64` | Optional | - | -| `Success` | `*bool` | Optional | - | -| `Memo` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 72, - "amount_in_cents": 158, - "success": false, - "memo": "memo6" -} -``` - + +# Payment for Allocation + +Information for captured payment, if applicable + +## Structure + +`PaymentForAllocation` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `AmountInCents` | `*int64` | Optional | - | +| `Success` | `*bool` | Optional | - | +| `Memo` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 72, + "amount_in_cents": 158, + "success": false, + "memo": "memo6" +} +``` + diff --git a/doc/models/payment-method-apple-pay.md b/doc/models/payment-method-apple-pay.md index 5c153d78..239351e9 100644 --- a/doc/models/payment-method-apple-pay.md +++ b/doc/models/payment-method-apple-pay.md @@ -1,21 +1,21 @@ - -# Payment Method Apple Pay - -## Structure - -`PaymentMethodApplePay` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Type` | [`models.InvoiceEventPaymentMethod`](../../doc/models/invoice-event-payment-method.md) | Required | - | - -## Example (as JSON) - -```json -{ - "type": "credit_card" -} -``` - + +# Payment Method Apple Pay + +## Structure + +`PaymentMethodApplePay` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Type` | [`models.InvoiceEventPaymentMethod`](../../doc/models/invoice-event-payment-method.md) | Required | - | + +## Example (as JSON) + +```json +{ + "type": "credit_card" +} +``` + diff --git a/doc/models/payment-method-bank-account.md b/doc/models/payment-method-bank-account.md index 44e2ff11..986381b7 100644 --- a/doc/models/payment-method-bank-account.md +++ b/doc/models/payment-method-bank-account.md @@ -1,25 +1,25 @@ - -# Payment Method Bank Account - -## Structure - -`PaymentMethodBankAccount` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `MaskedAccountNumber` | `string` | Required | - | -| `MaskedRoutingNumber` | `string` | Required | - | -| `Type` | [`models.InvoiceEventPaymentMethod`](../../doc/models/invoice-event-payment-method.md) | Required | - | - -## Example (as JSON) - -```json -{ - "masked_account_number": "masked_account_number2", - "masked_routing_number": "masked_routing_number2", - "type": "paypal_account" -} -``` - + +# Payment Method Bank Account + +## Structure + +`PaymentMethodBankAccount` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `MaskedAccountNumber` | `string` | Required | - | +| `MaskedRoutingNumber` | `string` | Required | - | +| `Type` | [`models.InvoiceEventPaymentMethod`](../../doc/models/invoice-event-payment-method.md) | Required | - | + +## Example (as JSON) + +```json +{ + "masked_account_number": "masked_account_number2", + "masked_routing_number": "masked_routing_number2", + "type": "paypal_account" +} +``` + diff --git a/doc/models/payment-method-credit-card.md b/doc/models/payment-method-credit-card.md index 0c467719..c6255690 100644 --- a/doc/models/payment-method-credit-card.md +++ b/doc/models/payment-method-credit-card.md @@ -1,29 +1,29 @@ - -# Payment Method Credit Card - -## Structure - -`PaymentMethodCreditCard` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CardBrand` | `string` | Required | - | -| `CardExpiration` | `*string` | Optional | - | -| `LastFour` | `Optional[string]` | Optional | - | -| `MaskedCardNumber` | `string` | Required | - | -| `Type` | [`models.InvoiceEventPaymentMethod`](../../doc/models/invoice-event-payment-method.md) | Required | - | - -## Example (as JSON) - -```json -{ - "card_brand": "card_brand4", - "card_expiration": "card_expiration2", - "last_four": "last_four4", - "masked_card_number": "masked_card_number0", - "type": "external" -} -``` - + +# Payment Method Credit Card + +## Structure + +`PaymentMethodCreditCard` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CardBrand` | `string` | Required | - | +| `CardExpiration` | `*string` | Optional | - | +| `LastFour` | `models.Optional[string]` | Optional | - | +| `MaskedCardNumber` | `string` | Required | - | +| `Type` | [`models.InvoiceEventPaymentMethod`](../../doc/models/invoice-event-payment-method.md) | Required | - | + +## Example (as JSON) + +```json +{ + "card_brand": "card_brand4", + "card_expiration": "card_expiration2", + "last_four": "last_four4", + "masked_card_number": "masked_card_number0", + "type": "external" +} +``` + diff --git a/doc/models/payment-method-external.md b/doc/models/payment-method-external.md index d13b6ee2..63478975 100644 --- a/doc/models/payment-method-external.md +++ b/doc/models/payment-method-external.md @@ -1,27 +1,27 @@ - -# Payment Method External - -## Structure - -`PaymentMethodExternal` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Details` | `*string` | Required | - | -| `Kind` | `string` | Required | - | -| `Memo` | `*string` | Required | - | -| `Type` | [`models.InvoiceEventPaymentMethod`](../../doc/models/invoice-event-payment-method.md) | Required | - | - -## Example (as JSON) - -```json -{ - "details": "details4", - "kind": "kind2", - "memo": "memo8", - "type": "bank_account" -} -``` - + +# Payment Method External + +## Structure + +`PaymentMethodExternal` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Details` | `*string` | Required | - | +| `Kind` | `string` | Required | - | +| `Memo` | `*string` | Required | - | +| `Type` | [`models.InvoiceEventPaymentMethod`](../../doc/models/invoice-event-payment-method.md) | Required | - | + +## Example (as JSON) + +```json +{ + "details": "details4", + "kind": "kind2", + "memo": "memo8", + "type": "bank_account" +} +``` + diff --git a/doc/models/payment-method-paypal.md b/doc/models/payment-method-paypal.md index c4e1f798..55f33b5c 100644 --- a/doc/models/payment-method-paypal.md +++ b/doc/models/payment-method-paypal.md @@ -1,23 +1,23 @@ - -# Payment Method Paypal - -## Structure - -`PaymentMethodPaypal` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Email` | `string` | Required | - | -| `Type` | [`models.InvoiceEventPaymentMethod`](../../doc/models/invoice-event-payment-method.md) | Required | - | - -## Example (as JSON) - -```json -{ - "email": "email2", - "type": "bank_account" -} -``` - + +# Payment Method Paypal + +## Structure + +`PaymentMethodPaypal` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Email` | `string` | Required | - | +| `Type` | [`models.InvoiceEventPaymentMethod`](../../doc/models/invoice-event-payment-method.md) | Required | - | + +## Example (as JSON) + +```json +{ + "email": "email2", + "type": "bank_account" +} +``` + diff --git a/doc/models/payment-profile-attributes.md b/doc/models/payment-profile-attributes.md index 5e3a57f9..5386ab64 100644 --- a/doc/models/payment-profile-attributes.md +++ b/doc/models/payment-profile-attributes.md @@ -1,51 +1,51 @@ - -# Payment Profile Attributes - -alias to credit_card_attributes - -## Structure - -`PaymentProfileAttributes` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ChargifyToken` | `*string` | Optional | (Optional) Token received after sending billing informations using chargify.js. This token must be passed as a sole attribute of `payment_profile_attributes` (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) | -| `Id` | `*int` | Optional | - | -| `PaymentType` | `*string` | Optional | - | -| `FirstName` | `*string` | Optional | (Optional) First name on card or bank account. If omitted, the first_name from customer attributes will be used. | -| `LastName` | `*string` | Optional | (Optional) Last name on card or bank account. If omitted, the last_name from customer attributes will be used. | -| `MaskedCardNumber` | `*string` | Optional | - | -| `FullNumber` | `*string` | Optional | The full credit card number (string representation, i.e. 5424000000000015) | -| `CardType` | [`*models.CardType`](../../doc/models/card-type.md) | Optional | (Optional, used only for Subscription Import) If you know the card type (i.e. Visa, MC, etc) you may supply it here so that we may display the card type in the UI. | -| `ExpirationMonth` | `*interface{}` | Optional | (Optional when performing a Subscription Import via vault_token, required otherwise) The 1- or 2-digit credit card expiration month, as an integer or string, i.e. 5 | -| `ExpirationYear` | `*interface{}` | Optional | (Optional when performing a Subscription Import via vault_token, required otherwise) The 4-digit credit card expiration year, as an integer or string, i.e. 2012 | -| `BillingAddress` | `*string` | Optional | (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. | -| `BillingAddress2` | `Optional[string]` | Optional | (Optional) Second line of the customer’s billing address i.e. Apt. 100 | -| `BillingCity` | `*string` | Optional | (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. | -| `BillingState` | `*string` | Optional | (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. | -| `BillingCountry` | `*string` | Optional | (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. | -| `BillingZip` | `*string` | Optional | (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. | -| `CurrentVault` | [`*models.CurrentVault`](../../doc/models/current-vault.md) | Optional | (Optional, used only for Subscription Import) The vault that stores the payment profile with the provided vault_token. | -| `VaultToken` | `*string` | Optional | (Optional, used only for Subscription Import) The “token” provided by your vault storage for an already stored payment profile | -| `CustomerVaultToken` | `*string` | Optional | (Optional, used only for Subscription Import) (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token | -| `CustomerId` | `*int` | Optional | - | -| `PaypalEmail` | `*string` | Optional | - | -| `PaymentMethodNonce` | `*string` | Optional | (Required for Square unless importing with vault_token and customer_vault_token) The nonce generated by the Square Javascript library (SqPaymentForm) | -| `GatewayHandle` | `*string` | Optional | (Optional) This attribute is only available if MultiGateway feature is enabled for your Site. This feature is in the Private Beta currently. gateway_handle is used to directly select a gateway where a payment profile will be stored in. Every connected gateway must have a unique gateway handle specified. Read [Multigateway description](https://chargify.zendesk.com/hc/en-us/articles/4407761759643#connecting-with-multiple-gateways) to learn more about new concepts that MultiGateway introduces and the default behavior when this attribute is not passed. | -| `Cvv` | `*string` | Optional | (Optional, may be required by your gateway settings) The 3- or 4-digit Card Verification Value. This value is merely passed through to the payment gateway. | -| `LastFour` | `*string` | Optional | (Optional, used only for Subscription Import) If you have the last 4 digits of the credit card number, you may supply them here so that we may create a masked card number (i.e. XXXX-XXXX-XXXX-1234) for display in the UI. Last 4 digits are required for refunds in Auth.Net. | - -## Example (as JSON) - -```json -{ - "chargify_token": "chargify_token8", - "id": 80, - "payment_type": "payment_type0", - "first_name": "first_name0", - "last_name": "last_name8" -} -``` - + +# Payment Profile Attributes + +alias to credit_card_attributes + +## Structure + +`PaymentProfileAttributes` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ChargifyToken` | `*string` | Optional | (Optional) Token received after sending billing informations using chargify.js. This token must be passed as a sole attribute of `payment_profile_attributes` (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) | +| `Id` | `*int` | Optional | - | +| `PaymentType` | `*string` | Optional | - | +| `FirstName` | `*string` | Optional | (Optional) First name on card or bank account. If omitted, the first_name from customer attributes will be used. | +| `LastName` | `*string` | Optional | (Optional) Last name on card or bank account. If omitted, the last_name from customer attributes will be used. | +| `MaskedCardNumber` | `*string` | Optional | - | +| `FullNumber` | `*string` | Optional | The full credit card number (string representation, i.e. 5424000000000015) | +| `CardType` | [`*models.CardType`](../../doc/models/card-type.md) | Optional | (Optional, used only for Subscription Import) If you know the card type (i.e. Visa, MC, etc) you may supply it here so that we may display the card type in the UI. | +| `ExpirationMonth` | [`*models.PaymentProfileAttributesExpirationMonth`](../../doc/models/containers/payment-profile-attributes-expiration-month.md) | Optional | This is a container for one-of cases. | +| `ExpirationYear` | [`*models.PaymentProfileAttributesExpirationYear`](../../doc/models/containers/payment-profile-attributes-expiration-year.md) | Optional | This is a container for one-of cases. | +| `BillingAddress` | `*string` | Optional | (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. | +| `BillingAddress2` | `models.Optional[string]` | Optional | (Optional) Second line of the customer’s billing address i.e. Apt. 100 | +| `BillingCity` | `*string` | Optional | (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. | +| `BillingState` | `*string` | Optional | (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. | +| `BillingCountry` | `*string` | Optional | (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. | +| `BillingZip` | `*string` | Optional | (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. | +| `CurrentVault` | [`*models.CurrentVault`](../../doc/models/current-vault.md) | Optional | (Optional, used only for Subscription Import) The vault that stores the payment profile with the provided vault_token. | +| `VaultToken` | `*string` | Optional | (Optional, used only for Subscription Import) The “token” provided by your vault storage for an already stored payment profile | +| `CustomerVaultToken` | `*string` | Optional | (Optional, used only for Subscription Import) (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token | +| `CustomerId` | `*int` | Optional | - | +| `PaypalEmail` | `*string` | Optional | - | +| `PaymentMethodNonce` | `*string` | Optional | (Required for Square unless importing with vault_token and customer_vault_token) The nonce generated by the Square Javascript library (SqPaymentForm) | +| `GatewayHandle` | `*string` | Optional | (Optional) This attribute is only available if MultiGateway feature is enabled for your Site. This feature is in the Private Beta currently. gateway_handle is used to directly select a gateway where a payment profile will be stored in. Every connected gateway must have a unique gateway handle specified. Read [Multigateway description](https://chargify.zendesk.com/hc/en-us/articles/4407761759643#connecting-with-multiple-gateways) to learn more about new concepts that MultiGateway introduces and the default behavior when this attribute is not passed. | +| `Cvv` | `*string` | Optional | (Optional, may be required by your gateway settings) The 3- or 4-digit Card Verification Value. This value is merely passed through to the payment gateway. | +| `LastFour` | `*string` | Optional | (Optional, used only for Subscription Import) If you have the last 4 digits of the credit card number, you may supply them here so that we may create a masked card number (i.e. XXXX-XXXX-XXXX-1234) for display in the UI. Last 4 digits are required for refunds in Auth.Net. | + +## Example (as JSON) + +```json +{ + "chargify_token": "chargify_token8", + "id": 80, + "payment_type": "payment_type0", + "first_name": "first_name0", + "last_name": "last_name8" +} +``` + diff --git a/doc/models/payment-profile-response.md b/doc/models/payment-profile-response.md index 240afb48..87d0d014 100644 --- a/doc/models/payment-profile-response.md +++ b/doc/models/payment-profile-response.md @@ -1,24 +1,30 @@ - -# Payment Profile Response - -## Structure - -`PaymentProfileResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PaymentProfile` | `interface{}` | Required | - | - -## Example (as JSON) - -```json -{ - "payment_profile": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Payment Profile Response + +## Structure + +`PaymentProfileResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PaymentProfile` | [`models.PaymentProfileResponsePaymentProfile`](../../doc/models/containers/payment-profile-response-payment-profile.md) | Required | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "payment_profile": { + "masked_bank_routing_number": "masked_bank_routing_number8", + "masked_bank_account_number": "masked_bank_account_number8", + "verified": false, + "id": 188, + "first_name": "first_name6", + "last_name": "last_name4", + "customer_id": 226, + "current_vault": "authorizenet" + } +} +``` + diff --git a/doc/models/payment-related-events.md b/doc/models/payment-related-events.md new file mode 100644 index 00000000..6cc2fbbf --- /dev/null +++ b/doc/models/payment-related-events.md @@ -0,0 +1,23 @@ + +# Payment Related Events + +## Structure + +`PaymentRelatedEvents` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProductId` | `int` | Required | - | +| `AccountTransactionId` | `int` | Required | - | + +## Example (as JSON) + +```json +{ + "product_id": 42, + "account_transaction_id": 58 +} +``` + diff --git a/doc/models/payment-type.md b/doc/models/payment-type.md index 1ad97626..7b0cd1d6 100644 --- a/doc/models/payment-type.md +++ b/doc/models/payment-type.md @@ -1,15 +1,15 @@ - -# Payment Type - -## Enumeration - -`PaymentType` - -## Fields - -| Name | -| --- | -| `CREDITCARD` | -| `BANKACCOUNT` | -| `PAYPALACCOUNT` | - + +# Payment Type + +## Enumeration + +`PaymentType` + +## Fields + +| Name | +| --- | +| `CREDITCARD` | +| `BANKACCOUNT` | +| `PAYPALACCOUNT` | + diff --git a/doc/models/pending-cancellation-change.md b/doc/models/pending-cancellation-change.md new file mode 100644 index 00000000..868d7e3b --- /dev/null +++ b/doc/models/pending-cancellation-change.md @@ -0,0 +1,23 @@ + +# Pending Cancellation Change + +## Structure + +`PendingCancellationChange` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CancellationState` | `string` | Required | - | +| `CancelsAt` | `time.Time` | Required | - | + +## Example (as JSON) + +```json +{ + "cancellation_state": "cancellation_state8", + "cancels_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/portal-management-link.md b/doc/models/portal-management-link.md index 47643217..845a08a8 100644 --- a/doc/models/portal-management-link.md +++ b/doc/models/portal-management-link.md @@ -1,30 +1,30 @@ - -# Portal Management Link - -## Structure - -`PortalManagementLink` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Url` | `*string` | Optional | - | -| `FetchCount` | `*int` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `NewLinkAvailableAt` | `*time.Time` | Optional | - | -| `ExpiresAt` | `*time.Time` | Optional | - | -| `LastInviteSentAt` | `Optional[time.Time]` | Optional | - | - -## Example (as JSON) - -```json -{ - "url": "url0", - "fetch_count": 222, - "created_at": "2016-03-13T12:52:32.123Z", - "new_link_available_at": "2016-03-13T12:52:32.123Z", - "expires_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Portal Management Link + +## Structure + +`PortalManagementLink` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Url` | `*string` | Optional | - | +| `FetchCount` | `*int` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `NewLinkAvailableAt` | `*time.Time` | Optional | - | +| `ExpiresAt` | `*time.Time` | Optional | - | +| `LastInviteSentAt` | `models.Optional[time.Time]` | Optional | - | + +## Example (as JSON) + +```json +{ + "url": "url0", + "fetch_count": 222, + "created_at": "2016-03-13T12:52:32.123Z", + "new_link_available_at": "2016-03-13T12:52:32.123Z", + "expires_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/prepaid-component-price-point.md b/doc/models/prepaid-component-price-point.md index 9f3e291b..6082e389 100644 --- a/doc/models/prepaid-component-price-point.md +++ b/doc/models/prepaid-component-price-point.md @@ -1,76 +1,49 @@ - -# Prepaid Component Price Point - -## Structure - -`PrepaidComponentPricePoint` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `*string` | Optional | - | -| `Handle` | `*string` | Optional | - | -| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | - | -| `OveragePricing` | [`*models.OveragePricing`](../../doc/models/overage-pricing.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "name": "name8", - "handle": "handle4", - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ], - "overage_pricing": { - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - } -} -``` - + +# Prepaid Component Price Point + +## Structure + +`PrepaidComponentPricePoint` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `*string` | Optional | - | +| `Handle` | `*string` | Optional | - | +| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | - | +| `OveragePricing` | [`*models.OveragePricing`](../../doc/models/overage-pricing.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name8", + "handle": "handle4", + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "overage_pricing": { + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ] + } +} +``` + diff --git a/doc/models/prepaid-configuration-response.md b/doc/models/prepaid-configuration-response.md index bc684839..05c59574 100644 --- a/doc/models/prepaid-configuration-response.md +++ b/doc/models/prepaid-configuration-response.md @@ -1,27 +1,27 @@ - -# Prepaid Configuration Response - -## Structure - -`PrepaidConfigurationResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PrepaidConfiguration` | [`models.PrepaidConfiguration`](../../doc/models/prepaid-configuration.md) | Required | - | - -## Example (as JSON) - -```json -{ - "prepaid_configuration": { - "id": 142, - "initial_funding_amount_in_cents": 74, - "replenish_to_amount_in_cents": 76, - "auto_replenish": false, - "replenish_threshold_amount_in_cents": 20 - } -} -``` - + +# Prepaid Configuration Response + +## Structure + +`PrepaidConfigurationResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PrepaidConfiguration` | [`models.PrepaidConfiguration`](../../doc/models/prepaid-configuration.md) | Required | - | + +## Example (as JSON) + +```json +{ + "prepaid_configuration": { + "id": 142, + "initial_funding_amount_in_cents": 74, + "replenish_to_amount_in_cents": 76, + "auto_replenish": false, + "replenish_threshold_amount_in_cents": 20 + } +} +``` + diff --git a/doc/models/prepaid-configuration.md b/doc/models/prepaid-configuration.md index 0c3b72a3..dd2f4bd9 100644 --- a/doc/models/prepaid-configuration.md +++ b/doc/models/prepaid-configuration.md @@ -1,29 +1,29 @@ - -# Prepaid Configuration - -## Structure - -`PrepaidConfiguration` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `InitialFundingAmountInCents` | `*int64` | Optional | - | -| `ReplenishToAmountInCents` | `*int64` | Optional | - | -| `AutoReplenish` | `*bool` | Optional | - | -| `ReplenishThresholdAmountInCents` | `*int64` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 156, - "initial_funding_amount_in_cents": 88, - "replenish_to_amount_in_cents": 166, - "auto_replenish": false, - "replenish_threshold_amount_in_cents": 222 -} -``` - + +# Prepaid Configuration + +## Structure + +`PrepaidConfiguration` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `InitialFundingAmountInCents` | `*int64` | Optional | - | +| `ReplenishToAmountInCents` | `*int64` | Optional | - | +| `AutoReplenish` | `*bool` | Optional | - | +| `ReplenishThresholdAmountInCents` | `*int64` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 156, + "initial_funding_amount_in_cents": 88, + "replenish_to_amount_in_cents": 166, + "auto_replenish": false, + "replenish_threshold_amount_in_cents": 222 +} +``` + diff --git a/doc/models/prepaid-subscription-balance-changed.md b/doc/models/prepaid-subscription-balance-changed.md new file mode 100644 index 00000000..899cb62c --- /dev/null +++ b/doc/models/prepaid-subscription-balance-changed.md @@ -0,0 +1,27 @@ + +# Prepaid Subscription Balance Changed + +## Structure + +`PrepaidSubscriptionBalanceChanged` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Reason` | `string` | Required | - | +| `CurrentAccountBalanceInCents` | `int64` | Required | - | +| `PrepaymentAccountBalanceInCents` | `int64` | Required | - | +| `CurrentUsageAmountInCents` | `int64` | Required | - | + +## Example (as JSON) + +```json +{ + "reason": "reason8", + "current_account_balance_in_cents": 250, + "prepayment_account_balance_in_cents": 44, + "current_usage_amount_in_cents": 242 +} +``` + diff --git a/doc/models/prepaid-usage-allocation-detail.md b/doc/models/prepaid-usage-allocation-detail.md new file mode 100644 index 00000000..95863462 --- /dev/null +++ b/doc/models/prepaid-usage-allocation-detail.md @@ -0,0 +1,25 @@ + +# Prepaid Usage Allocation Detail + +## Structure + +`PrepaidUsageAllocationDetail` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `AllocationId` | `*int` | Optional | - | +| `ChargeId` | `*int` | Optional | - | +| `UsageQuantity` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "allocation_id": 72, + "charge_id": 30, + "usage_quantity": 212 +} +``` + diff --git a/doc/models/prepaid-usage-component.md b/doc/models/prepaid-usage-component.md index ccbd91b4..3727ead0 100644 --- a/doc/models/prepaid-usage-component.md +++ b/doc/models/prepaid-usage-component.md @@ -1,47 +1,47 @@ - -# Prepaid Usage Component - -## Structure - -`PrepaidUsageComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `string` | Required | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | -| `UnitName` | `*string` | Optional | The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item | -| `Description` | `*string` | Optional | A description for the component that will be displayed to the user on the hosted signup page. | -| `Handle` | `*string` | Optional | A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'.
**Constraints**: *Pattern*: `^[a-z0-9][a-z0-9\-_:.]*$` | -| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | -| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#general-price-bracket-rules) for an overview of how price brackets work for different pricing schemes. | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `PricePoints` | [`[]models.PrepaidComponentPricePoint`](../../doc/models/prepaid-component-price-point.md) | Optional | - | -| `UnitPrice` | `*interface{}` | Optional | The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 | -| `TaxCode` | `*string` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | -| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | -| `PriceInCents` | `*string` | Optional | deprecated May 2011 - use unit_price instead | -| `OveragePricing` | [`*models.OveragePricing`](../../doc/models/overage-pricing.md) | Optional | - | -| `RolloverPrepaidRemainder` | `*bool` | Optional | Boolean which controls whether or not remaining units should be rolled over to the next period | -| `RenewPrepaidAllocation` | `*bool` | Optional | Boolean which controls whether or not the allocated quantity should be renewed at the beginning of each period | -| `ExpirationInterval` | `*float64` | Optional | (only for prepaid usage components where rollover_prepaid_remainder is true) The number of `expiration_interval_unit`s after which rollover amounts should expire | -| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | - | -| `DisplayOnHostedPage` | `*bool` | Optional | - | -| `AllowFractionalQuantities` | `*bool` | Optional | - | -| `PublicSignupPageIds` | `[]int` | Optional | - | - -## Example (as JSON) - -```json -{ - "name": "name2", - "unit_name": "unit_name4", - "description": "description8", - "handle": "handle8", - "taxable": false, - "pricing_scheme": "stairstep" -} -``` - + +# Prepaid Usage Component + +## Structure + +`PrepaidUsageComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | +| `UnitName` | `*string` | Optional | The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item | +| `Description` | `*string` | Optional | A description for the component that will be displayed to the user on the hosted signup page. | +| `Handle` | `*string` | Optional | A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'.
**Constraints**: *Pattern*: `^[a-z0-9][a-z0-9\-_:.]*$` | +| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | +| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#general-price-bracket-rules) for an overview of how price brackets work for different pricing schemes. | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `PricePoints` | [`[]models.PrepaidComponentPricePoint`](../../doc/models/prepaid-component-price-point.md) | Optional | - | +| `UnitPrice` | [`*models.PrepaidUsageComponentUnitPrice`](../../doc/models/containers/prepaid-usage-component-unit-price.md) | Optional | This is a container for one-of cases. | +| `TaxCode` | `*string` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | +| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | +| `PriceInCents` | `*string` | Optional | deprecated May 2011 - use unit_price instead | +| `OveragePricing` | [`*models.OveragePricing`](../../doc/models/overage-pricing.md) | Optional | - | +| `RolloverPrepaidRemainder` | `*bool` | Optional | Boolean which controls whether or not remaining units should be rolled over to the next period | +| `RenewPrepaidAllocation` | `*bool` | Optional | Boolean which controls whether or not the allocated quantity should be renewed at the beginning of each period | +| `ExpirationInterval` | `*float64` | Optional | (only for prepaid usage components where rollover_prepaid_remainder is true) The number of `expiration_interval_unit`s after which rollover amounts should expire | +| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | - | +| `DisplayOnHostedPage` | `*bool` | Optional | - | +| `AllowFractionalQuantities` | `*bool` | Optional | - | +| `PublicSignupPageIds` | `[]int` | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name2", + "unit_name": "unit_name4", + "description": "description8", + "handle": "handle8", + "taxable": false, + "pricing_scheme": "stairstep" +} +``` + diff --git a/doc/models/prepaid-usage.md b/doc/models/prepaid-usage.md new file mode 100644 index 00000000..dc37c81f --- /dev/null +++ b/doc/models/prepaid-usage.md @@ -0,0 +1,45 @@ + +# Prepaid Usage + +## Structure + +`PrepaidUsage` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PreviousUnitBalance` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `PreviousOverageUnitBalance` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `NewUnitBalance` | `int` | Required | - | +| `NewOverageUnitBalance` | `int` | Required | - | +| `UsageQuantity` | `int` | Required | - | +| `OverageUsageQuantity` | `int` | Required | - | +| `ComponentId` | `int` | Required | - | +| `ComponentHandle` | `string` | Required | - | +| `Memo` | `string` | Required | - | +| `AllocationDetails` | [`[]models.PrepaidUsageAllocationDetail`](../../doc/models/prepaid-usage-allocation-detail.md) | Required | - | + +## Example (as JSON) + +```json +{ + "previous_unit_balance": "previous_unit_balance0", + "previous_overage_unit_balance": "previous_overage_unit_balance4", + "new_unit_balance": 252, + "new_overage_unit_balance": 224, + "usage_quantity": 214, + "overage_usage_quantity": 106, + "component_id": 176, + "component_handle": "component_handle4", + "memo": "memo8", + "allocation_details": [ + { + "allocation_id": 18, + "charge_id": 84, + "usage_quantity": 10 + } + ] +} +``` + diff --git a/doc/models/prepayment-account-balance-changed.md b/doc/models/prepayment-account-balance-changed.md new file mode 100644 index 00000000..62c11b0b --- /dev/null +++ b/doc/models/prepayment-account-balance-changed.md @@ -0,0 +1,27 @@ + +# Prepayment Account Balance Changed + +## Structure + +`PrepaymentAccountBalanceChanged` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Reason` | `string` | Required | - | +| `PrepaymentAccountBalanceInCents` | `int64` | Required | - | +| `PrepaymentBalanceChangeInCents` | `int64` | Required | - | +| `CurrencyCode` | `string` | Required | - | + +## Example (as JSON) + +```json +{ + "reason": "reason4", + "prepayment_account_balance_in_cents": 182, + "prepayment_balance_change_in_cents": 206, + "currency_code": "currency_code4" +} +``` + diff --git a/doc/models/prepayment-aggregated-error.md b/doc/models/prepayment-aggregated-error.md index c3e713ee..c8373346 100644 --- a/doc/models/prepayment-aggregated-error.md +++ b/doc/models/prepayment-aggregated-error.md @@ -1,36 +1,36 @@ - -# Prepayment Aggregated Error - -## Structure - -`PrepaymentAggregatedError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `AmountInCents` | `[]string` | Optional | - | -| `Base` | `[]string` | Optional | - | -| `External` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "amount_in_cents": [ - "amount_in_cents7", - "amount_in_cents6", - "amount_in_cents5" - ], - "base": [ - "base7", - "base8" - ], - "external": [ - "external0", - "external1", - "external2" - ] -} -``` - + +# Prepayment Aggregated Error + +## Structure + +`PrepaymentAggregatedError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `AmountInCents` | `[]string` | Optional | - | +| `Base` | `[]string` | Optional | - | +| `External` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "amount_in_cents": [ + "amount_in_cents7", + "amount_in_cents6", + "amount_in_cents5" + ], + "base": [ + "base7", + "base8" + ], + "external": [ + "external0", + "external1", + "external2" + ] +} +``` + diff --git a/doc/models/prepayment-method.md b/doc/models/prepayment-method.md index 94a46974..0e9e85b2 100644 --- a/doc/models/prepayment-method.md +++ b/doc/models/prepayment-method.md @@ -1,19 +1,19 @@ - -# Prepayment Method - -## Enumeration - -`PrepaymentMethod` - -## Fields - -| Name | -| --- | -| `CHECK` | -| `CASH` | -| `MONEYORDER` | -| `ACH` | -| `PAYPALACCOUNT` | -| `CREDITCARD` | -| `OTHER` | - + +# Prepayment Method + +## Enumeration + +`PrepaymentMethod` + +## Fields + +| Name | +| --- | +| `CHECK` | +| `CASH` | +| `MONEYORDER` | +| `ACH` | +| `PAYPALACCOUNT` | +| `CREDITCARD` | +| `OTHER` | + diff --git a/doc/models/prepayment-response.md b/doc/models/prepayment-response.md index 825b9f77..ad1794e1 100644 --- a/doc/models/prepayment-response.md +++ b/doc/models/prepayment-response.md @@ -1,32 +1,32 @@ - -# Prepayment Response - -## Structure - -`PrepaymentResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Prepayment` | [`models.Prepayment`](../../doc/models/prepayment.md) | Required | - | - -## Example (as JSON) - -```json -{ - "prepayment": { - "id": 38, - "subscription_id": 148, - "amount_in_cents": 124, - "remaining_amount_in_cents": 182, - "refunded_amount_in_cents": 132, - "details": "details8", - "external": false, - "memo": "memo2", - "payment_type": "credit_card", - "created_at": "2016-03-13T12:52:32.123Z" - } -} -``` - + +# Prepayment Response + +## Structure + +`PrepaymentResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Prepayment` | [`models.Prepayment`](../../doc/models/prepayment.md) | Required | - | + +## Example (as JSON) + +```json +{ + "prepayment": { + "id": 38, + "subscription_id": 148, + "amount_in_cents": 124, + "remaining_amount_in_cents": 182, + "refunded_amount_in_cents": 132, + "details": "details8", + "external": false, + "memo": "memo2", + "payment_type": "credit_card", + "created_at": "2016-03-13T12:52:32.123Z" + } +} +``` + diff --git a/doc/models/prepayment.md b/doc/models/prepayment.md index 6beff1aa..5817f349 100644 --- a/doc/models/prepayment.md +++ b/doc/models/prepayment.md @@ -1,39 +1,39 @@ - -# Prepayment - -## Structure - -`Prepayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `int` | Required | - | -| `SubscriptionId` | `int` | Required | - | -| `AmountInCents` | `int64` | Required | - | -| `RemainingAmountInCents` | `int64` | Required | - | -| `RefundedAmountInCents` | `*int64` | Optional | - | -| `Details` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `External` | `bool` | Required | - | -| `Memo` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `PaymentType` | [`*models.PrepaymentMethod`](../../doc/models/prepayment-method.md) | Optional | The payment type of the prepayment. | -| `CreatedAt` | `time.Time` | Required | - | - -## Example (as JSON) - -```json -{ - "id": 50, - "subscription_id": 160, - "amount_in_cents": 120, - "remaining_amount_in_cents": 194, - "refunded_amount_in_cents": 144, - "details": "details4", - "external": false, - "memo": "memo8", - "payment_type": "cash", - "created_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Prepayment + +## Structure + +`Prepayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `int` | Required | - | +| `SubscriptionId` | `int` | Required | - | +| `AmountInCents` | `int64` | Required | - | +| `RemainingAmountInCents` | `int64` | Required | - | +| `RefundedAmountInCents` | `*int64` | Optional | - | +| `Details` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `External` | `bool` | Required | - | +| `Memo` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `PaymentType` | [`*models.PrepaymentMethod`](../../doc/models/prepayment-method.md) | Optional | The payment type of the prepayment. | +| `CreatedAt` | `time.Time` | Required | - | + +## Example (as JSON) + +```json +{ + "id": 50, + "subscription_id": 160, + "amount_in_cents": 120, + "remaining_amount_in_cents": 194, + "refunded_amount_in_cents": 144, + "details": "details4", + "external": false, + "memo": "memo8", + "payment_type": "cash", + "created_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/prepayments-response.md b/doc/models/prepayments-response.md index 886bb216..5ff6dbe0 100644 --- a/doc/models/prepayments-response.md +++ b/doc/models/prepayments-response.md @@ -1,46 +1,46 @@ - -# Prepayments Response - -## Structure - -`PrepaymentsResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Prepayments` | [`[]models.Prepayment`](../../doc/models/prepayment.md) | Optional | **Constraints**: *Unique Items Required* | - -## Example (as JSON) - -```json -{ - "prepayments": [ - { - "id": 76, - "subscription_id": 186, - "amount_in_cents": 94, - "remaining_amount_in_cents": 220, - "refunded_amount_in_cents": 170, - "details": "details6", - "external": false, - "memo": "memo0", - "payment_type": "cash", - "created_at": "2016-03-13T12:52:32.123Z" - }, - { - "id": 76, - "subscription_id": 186, - "amount_in_cents": 94, - "remaining_amount_in_cents": 220, - "refunded_amount_in_cents": 170, - "details": "details6", - "external": false, - "memo": "memo0", - "payment_type": "cash", - "created_at": "2016-03-13T12:52:32.123Z" - } - ] -} -``` - + +# Prepayments Response + +## Structure + +`PrepaymentsResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Prepayments` | [`[]models.Prepayment`](../../doc/models/prepayment.md) | Optional | **Constraints**: *Unique Items Required* | + +## Example (as JSON) + +```json +{ + "prepayments": [ + { + "id": 76, + "subscription_id": 186, + "amount_in_cents": 94, + "remaining_amount_in_cents": 220, + "refunded_amount_in_cents": 170, + "details": "details6", + "external": false, + "memo": "memo0", + "payment_type": "cash", + "created_at": "2016-03-13T12:52:32.123Z" + }, + { + "id": 76, + "subscription_id": 186, + "amount_in_cents": 94, + "remaining_amount_in_cents": 220, + "refunded_amount_in_cents": 170, + "details": "details6", + "external": false, + "memo": "memo0", + "payment_type": "cash", + "created_at": "2016-03-13T12:52:32.123Z" + } + ] +} +``` + diff --git a/doc/models/preview-allocations-request.md b/doc/models/preview-allocations-request.md index 6ad6025f..d59987d5 100644 --- a/doc/models/preview-allocations-request.md +++ b/doc/models/preview-allocations-request.md @@ -1,36 +1,36 @@ - -# Preview Allocations Request - -## Structure - -`PreviewAllocationsRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Allocations` | [`[]models.CreateAllocation`](../../doc/models/create-allocation.md) | Required | - | -| `EffectiveProrationDate` | `*time.Time` | Optional | To calculate proration amounts for a future time. Only within a current subscription period. Only ISO8601 format is supported. | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | - -## Example (as JSON) - -```json -{ - "allocations": [ - { - "quantity": 26.48, - "component_id": 242, - "memo": "memo6", - "proration_downgrade_scheme": "proration_downgrade_scheme0", - "proration_upgrade_scheme": "proration_upgrade_scheme2", - "accrue_charge": false - } - ], - "effective_proration_date": "2023-12-01", - "upgrade_charge": "none", - "downgrade_credit": "prorated" -} -``` - + +# Preview Allocations Request + +## Structure + +`PreviewAllocationsRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Allocations` | [`[]models.CreateAllocation`](../../doc/models/create-allocation.md) | Required | - | +| `EffectiveProrationDate` | `*time.Time` | Optional | To calculate proration amounts for a future time. Only within a current subscription period. Only ISO8601 format is supported. | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | + +## Example (as JSON) + +```json +{ + "allocations": [ + { + "quantity": 26.48, + "component_id": 242, + "memo": "memo6", + "proration_downgrade_scheme": "proration_downgrade_scheme0", + "proration_upgrade_scheme": "proration_upgrade_scheme2", + "accrue_charge": false + } + ], + "effective_proration_date": "2023-12-01", + "upgrade_charge": "none", + "downgrade_credit": "prorated" +} +``` + diff --git a/doc/models/price-point-type.md b/doc/models/price-point-type.md index 33e8f050..b9ac10e5 100644 --- a/doc/models/price-point-type.md +++ b/doc/models/price-point-type.md @@ -1,21 +1,21 @@ - -# Price Point Type - + +# Price Point Type + Price point type. We expose the following types: 1. **default**: a price point that is marked as a default price for a certain product. 2. **custom**: a custom price point. -3. **catalog**: a price point that is **not** marked as a default price for a certain product and is **not** a custom one. - -## Enumeration - -`PricePointType` - -## Fields - -| Name | -| --- | -| `CATALOG` | -| `ENUMDEFAULT` | -| `CUSTOM` | - +3. **catalog**: a price point that is **not** marked as a default price for a certain product and is **not** a custom one. + +## Enumeration + +`PricePointType` + +## Fields + +| Name | +| --- | +| `CATALOG` | +| `ENUMDEFAULT` | +| `CUSTOM` | + diff --git a/doc/models/price-point.md b/doc/models/price-point.md index 78bef318..b0c52126 100644 --- a/doc/models/price-point.md +++ b/doc/models/price-point.md @@ -1,52 +1,43 @@ - -# Price Point - -## Structure - -`PricePoint` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `*string` | Optional | - | -| `Handle` | `*string` | Optional | - | -| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | - | -| `UseSiteExchangeRate` | `*bool` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site.
**Default**: `true` | -| `TaxIncluded` | `*bool` | Optional | Whether or not the price point includes tax | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this price point, either month or day. This property is only available for sites with Multifrequency enabled. | -| `OveragePricing` | [`*models.OveragePricing`](../../doc/models/overage-pricing.md) | Optional | - | -| `RolloverPrepaidRemainder` | `*bool` | Optional | Boolean which controls whether or not remaining units should be rolled over to the next period | -| `RenewPrepaidAllocation` | `*bool` | Optional | Boolean which controls whether or not the allocated quantity should be renewed at the beginning of each period | -| `ExpirationInterval` | `*float64` | Optional | (only for prepaid usage components where rollover_prepaid_remainder is true) The number of `expiration_interval_unit`s after which rollover amounts should expire | -| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "use_site_exchange_rate": true, - "name": "name0", - "handle": "handle6", - "pricing_scheme": "per_unit", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] -} -``` - + +# Price Point + +## Structure + +`PricePoint` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `*string` | Optional | - | +| `Handle` | `*string` | Optional | - | +| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | - | +| `UseSiteExchangeRate` | `*bool` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site.
**Default**: `true` | +| `TaxIncluded` | `*bool` | Optional | Whether or not the price point includes tax | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this price point, either month or day. This property is only available for sites with Multifrequency enabled. | +| `OveragePricing` | [`*models.OveragePricing`](../../doc/models/overage-pricing.md) | Optional | - | +| `RolloverPrepaidRemainder` | `*bool` | Optional | Boolean which controls whether or not remaining units should be rolled over to the next period | +| `RenewPrepaidAllocation` | `*bool` | Optional | Boolean which controls whether or not the allocated quantity should be renewed at the beginning of each period | +| `ExpirationInterval` | `*float64` | Optional | (only for prepaid usage components where rollover_prepaid_remainder is true) The number of `expiration_interval_unit`s after which rollover amounts should expire | +| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "use_site_exchange_rate": true, + "name": "name0", + "handle": "handle6", + "pricing_scheme": "per_unit", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ] +} +``` + diff --git a/doc/models/price.md b/doc/models/price.md index bde623a0..b5d568bc 100644 --- a/doc/models/price.md +++ b/doc/models/price.md @@ -1,34 +1,25 @@ - -# Price - -## Structure - -`Price` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `StartingQuantity` | `interface{}` | Required | - | -| `EndingQuantity` | `Optional[interface{}]` | Optional | - | -| `UnitPrice` | `interface{}` | Required | The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 | - -## Example (as JSON) - -```json -{ - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Price + +## Structure + +`Price` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `StartingQuantity` | [`models.PriceStartingQuantity`](../../doc/models/containers/price-starting-quantity.md) | Required | This is a container for one-of cases. | +| `EndingQuantity` | [`models.Optional[models.PriceEndingQuantity]`](../../doc/models/containers/price-ending-quantity.md) | Optional | This is a container for one-of cases. | +| `UnitPrice` | [`models.PriceUnitPrice`](../../doc/models/containers/price-unit-price.md) | Required | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "starting_quantity": 40, + "ending_quantity": 14, + "unit_price": 125.12 +} +``` + diff --git a/doc/models/pricing-scheme.md b/doc/models/pricing-scheme.md index 96c0ecb8..1d1e20b4 100644 --- a/doc/models/pricing-scheme.md +++ b/doc/models/pricing-scheme.md @@ -1,18 +1,18 @@ - -# Pricing Scheme - -The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - -## Enumeration - -`PricingScheme` - -## Fields - -| Name | -| --- | -| `STAIRSTEP` | -| `VOLUME` | -| `PERUNIT` | -| `TIERED` | - + +# Pricing Scheme + +The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + +## Enumeration + +`PricingScheme` + +## Fields + +| Name | +| --- | +| `STAIRSTEP` | +| `VOLUME` | +| `PERUNIT` | +| `TIERED` | + diff --git a/doc/models/product-family-response.md b/doc/models/product-family-response.md index c488a2f5..aca1547e 100644 --- a/doc/models/product-family-response.md +++ b/doc/models/product-family-response.md @@ -1,27 +1,27 @@ - -# Product Family Response - -## Structure - -`ProductFamilyResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ProductFamily` | [`*models.ProductFamily`](../../doc/models/product-family.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "product_family": { - "id": 14, - "name": "name0", - "handle": "handle6", - "accounting_code": "accounting_code6", - "description": "description0" - } -} -``` - + +# Product Family Response + +## Structure + +`ProductFamilyResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProductFamily` | [`*models.ProductFamily`](../../doc/models/product-family.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "product_family": { + "id": 14, + "name": "name0", + "handle": "handle6", + "accounting_code": "accounting_code6", + "description": "description0" + } +} +``` + diff --git a/doc/models/product-family.md b/doc/models/product-family.md index 5b6e0304..c443ac6d 100644 --- a/doc/models/product-family.md +++ b/doc/models/product-family.md @@ -1,31 +1,31 @@ - -# Product Family - -## Structure - -`ProductFamily` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Name` | `*string` | Optional | - | -| `Handle` | `*string` | Optional | - | -| `AccountingCode` | `Optional[string]` | Optional | - | -| `Description` | `Optional[string]` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `UpdatedAt` | `*time.Time` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 194, - "name": "name2", - "handle": "handle8", - "accounting_code": "accounting_code8", - "description": "description8" -} -``` - + +# Product Family + +## Structure + +`ProductFamily` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Name` | `*string` | Optional | - | +| `Handle` | `*string` | Optional | - | +| `AccountingCode` | `models.Optional[string]` | Optional | - | +| `Description` | `models.Optional[string]` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `UpdatedAt` | `*time.Time` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 194, + "name": "name2", + "handle": "handle8", + "accounting_code": "accounting_code8", + "description": "description8" +} +``` + diff --git a/doc/models/product-price-point-error-response-exception.md b/doc/models/product-price-point-error-response-exception.md index 59e72006..a7e795ab 100644 --- a/doc/models/product-price-point-error-response-exception.md +++ b/doc/models/product-price-point-error-response-exception.md @@ -1,41 +1,41 @@ - -# Product Price Point Error Response Exception - -## Structure - -`ProductPricePointErrorResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`models.ProductPricePointErrors`](../../doc/models/product-price-point-errors.md) | Required | - | - -## Example (as JSON) - -```json -{ - "errors": { - "price_point": "can't be blank", - "interval": [ - "Recurring Interval: cannot be blank.", - "Recurring Interval: must be greater than or equal to 1." - ], - "interval_unit": [ - "Interval unit: cannot be blank.", - "Interval unit: must be 'month' or 'day'." - ], - "name": [ - "Name: cannot be blank." - ], - "price": [ - "Price: is not a number.", - "Price: must be greater than or equal to 0." - ], - "price_in_cents": [ - "Price in cents: cannot be blank." - ] - } -} -``` - + +# Product Price Point Error Response Exception + +## Structure + +`ProductPricePointErrorResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`models.ProductPricePointErrors`](../../doc/models/product-price-point-errors.md) | Required | - | + +## Example (as JSON) + +```json +{ + "errors": { + "price_point": "can't be blank", + "interval": [ + "Recurring Interval: cannot be blank.", + "Recurring Interval: must be greater than or equal to 1." + ], + "interval_unit": [ + "Interval unit: cannot be blank.", + "Interval unit: must be 'month' or 'day'." + ], + "name": [ + "Name: cannot be blank." + ], + "price": [ + "Price: is not a number.", + "Price: must be greater than or equal to 0." + ], + "price_in_cents": [ + "Price in cents: cannot be blank." + ] + } +} +``` + diff --git a/doc/models/product-price-point-errors.md b/doc/models/product-price-point-errors.md index 66de068f..cb829781 100644 --- a/doc/models/product-price-point-errors.md +++ b/doc/models/product-price-point-errors.md @@ -1,44 +1,44 @@ - -# Product Price Point Errors - -## Structure - -`ProductPricePointErrors` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoint` | `*string` | Optional | - | -| `Interval` | `[]string` | Optional | - | -| `IntervalUnit` | `[]string` | Optional | - | -| `Name` | `[]string` | Optional | - | -| `Price` | `[]string` | Optional | - | -| `PriceInCents` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "price_point": "can't be blank", - "interval": [ - "Recurring Interval: cannot be blank.", - "Recurring Interval: must be greater than or equal to 1." - ], - "interval_unit": [ - "Interval unit: cannot be blank.", - "Interval unit: must be 'month' or 'day'." - ], - "name": [ - "Name: cannot be blank." - ], - "price": [ - "Price: is not a number.", - "Price: must be greater than or equal to 0." - ], - "price_in_cents": [ - "Price in cents: cannot be blank." - ] -} -``` - + +# Product Price Point Errors + +## Structure + +`ProductPricePointErrors` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoint` | `*string` | Optional | - | +| `Interval` | `[]string` | Optional | - | +| `IntervalUnit` | `[]string` | Optional | - | +| `Name` | `[]string` | Optional | - | +| `Price` | `[]string` | Optional | - | +| `PriceInCents` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "price_point": "can't be blank", + "interval": [ + "Recurring Interval: cannot be blank.", + "Recurring Interval: must be greater than or equal to 1." + ], + "interval_unit": [ + "Interval unit: cannot be blank.", + "Interval unit: must be 'month' or 'day'." + ], + "name": [ + "Name: cannot be blank." + ], + "price": [ + "Price: is not a number.", + "Price: must be greater than or equal to 0." + ], + "price_in_cents": [ + "Price in cents: cannot be blank." + ] +} +``` + diff --git a/doc/models/product-price-point-response.md b/doc/models/product-price-point-response.md index 2d7c2b2e..78b744b1 100644 --- a/doc/models/product-price-point-response.md +++ b/doc/models/product-price-point-response.md @@ -1,27 +1,27 @@ - -# Product Price Point Response - -## Structure - -`ProductPricePointResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoint` | [`models.ProductPricePoint`](../../doc/models/product-price-point.md) | Required | - | - -## Example (as JSON) - -```json -{ - "price_point": { - "id": 248, - "name": "name0", - "handle": "handle6", - "price_in_cents": 196, - "interval": 44 - } -} -``` - + +# Product Price Point Response + +## Structure + +`ProductPricePointResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoint` | [`models.ProductPricePoint`](../../doc/models/product-price-point.md) | Required | - | + +## Example (as JSON) + +```json +{ + "price_point": { + "id": 248, + "name": "name0", + "handle": "handle6", + "price_in_cents": 196, + "interval": 44 + } +} +``` + diff --git a/doc/models/product-price-point.md b/doc/models/product-price-point.md index a24ccc1d..af9f3a46 100644 --- a/doc/models/product-price-point.md +++ b/doc/models/product-price-point.md @@ -1,48 +1,48 @@ - -# Product Price Point - -## Structure - -`ProductPricePoint` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Name` | `*string` | Optional | The product price point name | -| `Handle` | `*string` | Optional | The product price point API handle | -| `PriceInCents` | `*int64` | Optional | The product price point price, in integer cents | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product price point would renew every 30 days | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this product price point, either month or day | -| `TrialPriceInCents` | `*int64` | Optional | The product price point trial price, in integer cents | -| `TrialInterval` | `*int` | Optional | The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product price point trial would last 30 days | -| `TrialIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the trial interval unit for this product price point, either month or day | -| `TrialType` | `*string` | Optional | - | -| `IntroductoryOffer` | `*bool` | Optional | reserved for future use | -| `InitialChargeInCents` | `*int64` | Optional | The product price point initial charge, in integer cents | -| `InitialChargeAfterTrial` | `*bool` | Optional | - | -| `ExpirationInterval` | `*int` | Optional | The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product price point would expire after 30 days | -| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the expiration interval unit for this product price point, either month or day | -| `ProductId` | `*int` | Optional | The product id this price point belongs to | -| `ArchivedAt` | `Optional[time.Time]` | Optional | Timestamp indicating when this price point was archived | -| `CreatedAt` | `*time.Time` | Optional | Timestamp indicating when this price point was created | -| `UpdatedAt` | `*time.Time` | Optional | Timestamp indicating when this price point was last updated | -| `UseSiteExchangeRate` | `*bool` | Optional | Whether or not to use the site's exchange rate or define your own pricing when your site has multiple currencies defined. | -| `Type` | [`*models.PricePointType`](../../doc/models/price-point-type.md) | Optional | The type of price point | -| `TaxIncluded` | `*bool` | Optional | Whether or not the price point includes tax | -| `SubscriptionId` | `Optional[int]` | Optional | The subscription id this price point belongs to | -| `CurrencyPrices` | [`[]models.CurrencyPrice`](../../doc/models/currency-price.md) | Optional | An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. | - -## Example (as JSON) - -```json -{ - "id": 196, - "name": "name6", - "handle": "handle2", - "price_in_cents": 248, - "interval": 8 -} -``` - + +# Product Price Point + +## Structure + +`ProductPricePoint` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Name` | `*string` | Optional | The product price point name | +| `Handle` | `*string` | Optional | The product price point API handle | +| `PriceInCents` | `*int64` | Optional | The product price point price, in integer cents | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product price point would renew every 30 days | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this product price point, either month or day | +| `TrialPriceInCents` | `*int64` | Optional | The product price point trial price, in integer cents | +| `TrialInterval` | `*int` | Optional | The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product price point trial would last 30 days | +| `TrialIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the trial interval unit for this product price point, either month or day | +| `TrialType` | `*string` | Optional | - | +| `IntroductoryOffer` | `*bool` | Optional | reserved for future use | +| `InitialChargeInCents` | `*int64` | Optional | The product price point initial charge, in integer cents | +| `InitialChargeAfterTrial` | `*bool` | Optional | - | +| `ExpirationInterval` | `*int` | Optional | The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product price point would expire after 30 days | +| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the expiration interval unit for this product price point, either month or day | +| `ProductId` | `*int` | Optional | The product id this price point belongs to | +| `ArchivedAt` | `models.Optional[time.Time]` | Optional | Timestamp indicating when this price point was archived | +| `CreatedAt` | `*time.Time` | Optional | Timestamp indicating when this price point was created | +| `UpdatedAt` | `*time.Time` | Optional | Timestamp indicating when this price point was last updated | +| `UseSiteExchangeRate` | `*bool` | Optional | Whether or not to use the site's exchange rate or define your own pricing when your site has multiple currencies defined. | +| `Type` | [`*models.PricePointType`](../../doc/models/price-point-type.md) | Optional | The type of price point | +| `TaxIncluded` | `*bool` | Optional | Whether or not the price point includes tax | +| `SubscriptionId` | `models.Optional[int]` | Optional | The subscription id this price point belongs to | +| `CurrencyPrices` | [`[]models.CurrencyPrice`](../../doc/models/currency-price.md) | Optional | An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. | + +## Example (as JSON) + +```json +{ + "id": 196, + "name": "name6", + "handle": "handle2", + "price_in_cents": 248, + "interval": 8 +} +``` + diff --git a/doc/models/product-response.md b/doc/models/product-response.md index fd0a2285..d9682796 100644 --- a/doc/models/product-response.md +++ b/doc/models/product-response.md @@ -1,27 +1,27 @@ - -# Product Response - -## Structure - -`ProductResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Product` | [`models.Product`](../../doc/models/product.md) | Required | - | - -## Example (as JSON) - -```json -{ - "product": { - "id": 134, - "name": "name0", - "handle": "handle6", - "description": "description0", - "accounting_code": "accounting_code6" - } -} -``` - + +# Product Response + +## Structure + +`ProductResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Product` | [`models.Product`](../../doc/models/product.md) | Required | - | + +## Example (as JSON) + +```json +{ + "product": { + "id": 134, + "name": "name0", + "handle": "handle6", + "description": "description0", + "accounting_code": "accounting_code6" + } +} +``` + diff --git a/doc/models/product.md b/doc/models/product.md index e04037f5..d29d42f8 100644 --- a/doc/models/product.md +++ b/doc/models/product.md @@ -1,61 +1,61 @@ - -# Product - -## Structure - -`Product` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Name` | `*string` | Optional | The product name | -| `Handle` | `Optional[string]` | Optional | The product API handle | -| `Description` | `Optional[string]` | Optional | The product description | -| `AccountingCode` | `Optional[string]` | Optional | E.g. Internal ID or SKU Number | -| `RequestCreditCard` | `*bool` | Optional | Deprecated value that can be ignored unless you have legacy hosted pages. For Public Signup Page users, please read this attribute from under the signup page. | -| `ExpirationInterval` | `Optional[int]` | Optional | A numerical interval for the length a subscription to this product will run before it expires. See the description of interval for a description of how this value is coupled with an interval unit to calculate the full interval | -| `ExpirationIntervalUnit` | [`Optional[models.ExtendedIntervalUnit]`](../../doc/models/extended-interval-unit.md) | Optional | A string representing the expiration interval unit for this product, either month or day | -| `CreatedAt` | `*time.Time` | Optional | Timestamp indicating when this product was created | -| `UpdatedAt` | `*time.Time` | Optional | Timestamp indicating when this product was last updated | -| `PriceInCents` | `*int64` | Optional | The product price, in integer cents | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product would renew every 30 days | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this product, either month or day | -| `InitialChargeInCents` | `Optional[int64]` | Optional | The up front charge you have specified. | -| `TrialPriceInCents` | `Optional[int64]` | Optional | The price of the trial period for a subscription to this product, in integer cents. | -| `TrialInterval` | `Optional[int]` | Optional | A numerical interval for the length of the trial period of a subscription to this product. See the description of interval for a description of how this value is coupled with an interval unit to calculate the full interval | -| `TrialIntervalUnit` | [`Optional[models.IntervalUnit]`](../../doc/models/interval-unit.md) | Optional | A string representing the trial interval unit for this product, either month or day | -| `ArchivedAt` | `Optional[time.Time]` | Optional | Timestamp indicating when this product was archived | -| `RequireCreditCard` | `*bool` | Optional | Boolean that controls whether a payment profile is required to be entered for customers wishing to sign up on this product. | -| `ReturnParams` | `Optional[string]` | Optional | - | -| `Taxable` | `*bool` | Optional | - | -| `UpdateReturnUrl` | `Optional[string]` | Optional | The url to which a customer will be returned after a successful account update | -| `InitialChargeAfterTrial` | `*bool` | Optional | - | -| `VersionNumber` | `*int` | Optional | The version of the product | -| `UpdateReturnParams` | `Optional[string]` | Optional | The parameters will append to the url after a successful account update. See [help documentation](https://help.chargify.com/products/product-editing.html#return-parameters-after-account-update) | -| `ProductFamily` | [`*models.ProductFamily`](../../doc/models/product-family.md) | Optional | - | -| `PublicSignupPages` | [`[]models.PublicSignupPage`](../../doc/models/public-signup-page.md) | Optional | - | -| `ProductPricePointName` | `*string` | Optional | - | -| `RequestBillingAddress` | `*bool` | Optional | A boolean indicating whether to request a billing address on any Self-Service Pages that are used by subscribers of this product. | -| `RequireBillingAddress` | `*bool` | Optional | A boolean indicating whether a billing address is required to add a payment profile, especially at signup. | -| `RequireShippingAddress` | `*bool` | Optional | A boolean indicating whether a shipping address is required for the customer, especially at signup. | -| `TaxCode` | `Optional[string]` | Optional | A string representing the tax code related to the product type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | -| `DefaultProductPricePointId` | `*int` | Optional | - | -| `UseSiteExchangeRate` | `Optional[bool]` | Optional | - | -| `ItemCategory` | `Optional[string]` | Optional | One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other | -| `ProductPricePointId` | `*int` | Optional | - | -| `ProductPricePointHandle` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 180, - "name": "name4", - "handle": "handle0", - "description": "description4", - "accounting_code": "accounting_code0" -} -``` - + +# Product + +## Structure + +`Product` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Name` | `*string` | Optional | The product name | +| `Handle` | `models.Optional[string]` | Optional | The product API handle | +| `Description` | `models.Optional[string]` | Optional | The product description | +| `AccountingCode` | `models.Optional[string]` | Optional | E.g. Internal ID or SKU Number | +| `RequestCreditCard` | `*bool` | Optional | Deprecated value that can be ignored unless you have legacy hosted pages. For Public Signup Page users, please read this attribute from under the signup page. | +| `ExpirationInterval` | `models.Optional[int]` | Optional | A numerical interval for the length a subscription to this product will run before it expires. See the description of interval for a description of how this value is coupled with an interval unit to calculate the full interval | +| `ExpirationIntervalUnit` | [`models.Optional[models.ProductExpirationIntervalUnit]`](../../doc/models/containers/product-expiration-interval-unit.md) | Optional | This is a container for one-of cases. | +| `CreatedAt` | `*time.Time` | Optional | Timestamp indicating when this product was created | +| `UpdatedAt` | `*time.Time` | Optional | Timestamp indicating when this product was last updated | +| `PriceInCents` | `*int64` | Optional | The product price, in integer cents | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product would renew every 30 days | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this product, either month or day | +| `InitialChargeInCents` | `models.Optional[int64]` | Optional | The up front charge you have specified. | +| `TrialPriceInCents` | `models.Optional[int64]` | Optional | The price of the trial period for a subscription to this product, in integer cents. | +| `TrialInterval` | `models.Optional[int]` | Optional | A numerical interval for the length of the trial period of a subscription to this product. See the description of interval for a description of how this value is coupled with an interval unit to calculate the full interval | +| `TrialIntervalUnit` | [`models.Optional[models.ProductTrialIntervalUnit]`](../../doc/models/containers/product-trial-interval-unit.md) | Optional | This is a container for one-of cases. | +| `ArchivedAt` | `models.Optional[time.Time]` | Optional | Timestamp indicating when this product was archived | +| `RequireCreditCard` | `*bool` | Optional | Boolean that controls whether a payment profile is required to be entered for customers wishing to sign up on this product. | +| `ReturnParams` | `models.Optional[string]` | Optional | - | +| `Taxable` | `*bool` | Optional | - | +| `UpdateReturnUrl` | `models.Optional[string]` | Optional | The url to which a customer will be returned after a successful account update | +| `InitialChargeAfterTrial` | `*bool` | Optional | - | +| `VersionNumber` | `*int` | Optional | The version of the product | +| `UpdateReturnParams` | `models.Optional[string]` | Optional | The parameters will append to the url after a successful account update. See [help documentation](https://help.chargify.com/products/product-editing.html#return-parameters-after-account-update) | +| `ProductFamily` | [`*models.ProductFamily`](../../doc/models/product-family.md) | Optional | - | +| `PublicSignupPages` | [`[]models.PublicSignupPage`](../../doc/models/public-signup-page.md) | Optional | - | +| `ProductPricePointName` | `*string` | Optional | - | +| `RequestBillingAddress` | `*bool` | Optional | A boolean indicating whether to request a billing address on any Self-Service Pages that are used by subscribers of this product. | +| `RequireBillingAddress` | `*bool` | Optional | A boolean indicating whether a billing address is required to add a payment profile, especially at signup. | +| `RequireShippingAddress` | `*bool` | Optional | A boolean indicating whether a shipping address is required for the customer, especially at signup. | +| `TaxCode` | `models.Optional[string]` | Optional | A string representing the tax code related to the product type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | +| `DefaultProductPricePointId` | `*int` | Optional | - | +| `UseSiteExchangeRate` | `models.Optional[bool]` | Optional | - | +| `ItemCategory` | `models.Optional[string]` | Optional | One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other | +| `ProductPricePointId` | `*int` | Optional | - | +| `ProductPricePointHandle` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 180, + "name": "name4", + "handle": "handle0", + "description": "description4", + "accounting_code": "accounting_code0" +} +``` + diff --git a/doc/models/proforma-bad-request-error-response-exception.md b/doc/models/proforma-bad-request-error-response-exception.md index f01c7d37..0467104d 100644 --- a/doc/models/proforma-bad-request-error-response-exception.md +++ b/doc/models/proforma-bad-request-error-response-exception.md @@ -1,28 +1,28 @@ - -# Proforma Bad Request Error Response Exception - -## Structure - -`ProformaBadRequestErrorResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`*models.ProformaError`](../../doc/models/proforma-error.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": { - "subscription": { - "base": [ - "base3", - "base4" - ] - } - } -} -``` - + +# Proforma Bad Request Error Response Exception + +## Structure + +`ProformaBadRequestErrorResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`*models.ProformaError`](../../doc/models/proforma-error.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": { + "subscription": { + "base": [ + "base3", + "base4" + ] + } + } +} +``` + diff --git a/doc/models/proforma-error.md b/doc/models/proforma-error.md index ad45ed07..8125de2c 100644 --- a/doc/models/proforma-error.md +++ b/doc/models/proforma-error.md @@ -1,26 +1,26 @@ - -# Proforma Error - -## Structure - -`ProformaError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Subscription` | [`*models.BaseStringError`](../../doc/models/base-string-error.md) | Optional | The error is base if it is not directly associated with a single attribute. | - -## Example (as JSON) - -```json -{ - "subscription": { - "base": [ - "base3", - "base4" - ] - } -} -``` - + +# Proforma Error + +## Structure + +`ProformaError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Subscription` | [`*models.BaseStringError`](../../doc/models/base-string-error.md) | Optional | The error is base if it is not directly associated with a single attribute. | + +## Example (as JSON) + +```json +{ + "subscription": { + "base": [ + "base3", + "base4" + ] + } +} +``` + diff --git a/doc/models/proforma-invoice-credit.md b/doc/models/proforma-invoice-credit.md index c29573c4..9e65caaf 100644 --- a/doc/models/proforma-invoice-credit.md +++ b/doc/models/proforma-invoice-credit.md @@ -1,27 +1,27 @@ - -# Proforma Invoice Credit - -## Structure - -`ProformaInvoiceCredit` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `Memo` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `OriginalAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `AppliedAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | - -## Example (as JSON) - -```json -{ - "uid": "uid8", - "memo": "memo2", - "original_amount": "original_amount2", - "applied_amount": "applied_amount0" -} -``` - + +# Proforma Invoice Credit + +## Structure + +`ProformaInvoiceCredit` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `Memo` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `OriginalAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `AppliedAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | + +## Example (as JSON) + +```json +{ + "uid": "uid8", + "memo": "memo2", + "original_amount": "original_amount2", + "applied_amount": "applied_amount0" +} +``` + diff --git a/doc/models/proforma-invoice-discount-source-type.md b/doc/models/proforma-invoice-discount-source-type.md index 4b3d7ce3..9ca7d08f 100644 --- a/doc/models/proforma-invoice-discount-source-type.md +++ b/doc/models/proforma-invoice-discount-source-type.md @@ -1,14 +1,14 @@ - -# Proforma Invoice Discount Source Type - -## Enumeration - -`ProformaInvoiceDiscountSourceType` - -## Fields - -| Name | -| --- | -| `COUPON` | -| `REFERRAL` | - + +# Proforma Invoice Discount Source Type + +## Enumeration + +`ProformaInvoiceDiscountSourceType` + +## Fields + +| Name | +| --- | +| `COUPON` | +| `REFERRAL` | + diff --git a/doc/models/proforma-invoice-discount.md b/doc/models/proforma-invoice-discount.md index b3df666d..9628eb1c 100644 --- a/doc/models/proforma-invoice-discount.md +++ b/doc/models/proforma-invoice-discount.md @@ -1,32 +1,32 @@ - -# Proforma Invoice Discount - -## Structure - -`ProformaInvoiceDiscount` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `Title` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `Code` | `*string` | Optional | - | -| `SourceType` | [`*models.ProformaInvoiceDiscountSourceType`](../../doc/models/proforma-invoice-discount-source-type.md) | Optional | - | -| `DiscountType` | [`*models.InvoiceDiscountType`](../../doc/models/invoice-discount-type.md) | Optional | - | -| `EligibleAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `DiscountAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `LineItemBreakouts` | [`[]models.InvoiceDiscountBreakout`](../../doc/models/invoice-discount-breakout.md) | Optional | **Constraints**: *Minimum Items*: `1`, *Unique Items Required* | - -## Example (as JSON) - -```json -{ - "uid": "uid2", - "title": "title8", - "code": "code0", - "source_type": "Coupon", - "discount_type": "percentage" -} -``` - + +# Proforma Invoice Discount + +## Structure + +`ProformaInvoiceDiscount` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `Title` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `Code` | `*string` | Optional | - | +| `SourceType` | [`*models.ProformaInvoiceDiscountSourceType`](../../doc/models/proforma-invoice-discount-source-type.md) | Optional | - | +| `DiscountType` | [`*models.InvoiceDiscountType`](../../doc/models/invoice-discount-type.md) | Optional | - | +| `EligibleAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `DiscountAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `LineItemBreakouts` | [`[]models.InvoiceDiscountBreakout`](../../doc/models/invoice-discount-breakout.md) | Optional | **Constraints**: *Minimum Items*: `1`, *Unique Items Required* | + +## Example (as JSON) + +```json +{ + "uid": "uid2", + "title": "title8", + "code": "code0", + "source_type": "Coupon", + "discount_type": "percentage" +} +``` + diff --git a/doc/models/proforma-invoice-issued.md b/doc/models/proforma-invoice-issued.md new file mode 100644 index 00000000..73364017 --- /dev/null +++ b/doc/models/proforma-invoice-issued.md @@ -0,0 +1,49 @@ + +# Proforma Invoice Issued + +## Structure + +`ProformaInvoiceIssued` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `string` | Required | - | +| `Number` | `string` | Required | - | +| `Role` | `string` | Required | - | +| `DeliveryDate` | `time.Time` | Required | - | +| `CreatedAt` | `time.Time` | Required | - | +| `DueAmount` | `string` | Required | - | +| `PaidAmount` | `string` | Required | - | +| `TaxAmount` | `string` | Required | - | +| `TotalAmount` | `string` | Required | - | +| `ProductName` | `string` | Required | - | +| `LineItems` | [`[]models.InvoiceLineItemEventData`](../../doc/models/invoice-line-item-event-data.md) | Required | - | + +## Example (as JSON) + +```json +{ + "uid": "uid0", + "number": "number2", + "role": "role6", + "delivery_date": "2016-03-13T12:52:32.123Z", + "created_at": "2016-03-13T12:52:32.123Z", + "due_amount": "due_amount2", + "paid_amount": "paid_amount8", + "tax_amount": "tax_amount6", + "total_amount": "total_amount6", + "product_name": "product_name6", + "line_items": [ + { + "uid": "uid8", + "title": "title4", + "description": "description8", + "quantity": 102, + "quantity_delta": 204 + } + ] +} +``` + diff --git a/doc/models/proforma-invoice-payment.md b/doc/models/proforma-invoice-payment.md index 0e899c5e..471fb799 100644 --- a/doc/models/proforma-invoice-payment.md +++ b/doc/models/proforma-invoice-payment.md @@ -1,27 +1,27 @@ - -# Proforma Invoice Payment - -## Structure - -`ProformaInvoicePayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Memo` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `OriginalAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `AppliedAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `Prepayment` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "memo": "memo4", - "original_amount": "original_amount4", - "applied_amount": "applied_amount8", - "prepayment": false -} -``` - + +# Proforma Invoice Payment + +## Structure + +`ProformaInvoicePayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Memo` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `OriginalAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `AppliedAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `Prepayment` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "memo": "memo4", + "original_amount": "original_amount4", + "applied_amount": "applied_amount8", + "prepayment": false +} +``` + diff --git a/doc/models/proforma-invoice-role.md b/doc/models/proforma-invoice-role.md index fbc4fc25..29561623 100644 --- a/doc/models/proforma-invoice-role.md +++ b/doc/models/proforma-invoice-role.md @@ -1,18 +1,18 @@ - -# Proforma Invoice Role - -'proforma' value is deprecated in favor of proforma_adhoc and proforma_automatic - -## Enumeration - -`ProformaInvoiceRole` - -## Fields - -| Name | -| --- | -| `UNSET` | -| `PROFORMA` | -| `PROFORMAADHOC` | -| `PROFORMAAUTOMATIC` | - + +# Proforma Invoice Role + +'proforma' value is deprecated in favor of proforma_adhoc and proforma_automatic + +## Enumeration + +`ProformaInvoiceRole` + +## Fields + +| Name | +| --- | +| `UNSET` | +| `PROFORMA` | +| `PROFORMAADHOC` | +| `PROFORMAAUTOMATIC` | + diff --git a/doc/models/proforma-invoice-status.md b/doc/models/proforma-invoice-status.md index a52e624a..73e3ddef 100644 --- a/doc/models/proforma-invoice-status.md +++ b/doc/models/proforma-invoice-status.md @@ -1,15 +1,15 @@ - -# Proforma Invoice Status - -## Enumeration - -`ProformaInvoiceStatus` - -## Fields - -| Name | -| --- | -| `DRAFT` | -| `VOIDED` | -| `ARCHIVED` | - + +# Proforma Invoice Status + +## Enumeration + +`ProformaInvoiceStatus` + +## Fields + +| Name | +| --- | +| `DRAFT` | +| `VOIDED` | +| `ARCHIVED` | + diff --git a/doc/models/proforma-invoice-tax-source-type.md b/doc/models/proforma-invoice-tax-source-type.md index e9071ba3..fab176de 100644 --- a/doc/models/proforma-invoice-tax-source-type.md +++ b/doc/models/proforma-invoice-tax-source-type.md @@ -1,14 +1,14 @@ - -# Proforma Invoice Tax Source Type - -## Enumeration - -`ProformaInvoiceTaxSourceType` - -## Fields - -| Name | -| --- | -| `TAX` | -| `AVALARA` | - + +# Proforma Invoice Tax Source Type + +## Enumeration + +`ProformaInvoiceTaxSourceType` + +## Fields + +| Name | +| --- | +| `TAX` | +| `AVALARA` | + diff --git a/doc/models/proforma-invoice-tax.md b/doc/models/proforma-invoice-tax.md index 27989a13..9e84ad6e 100644 --- a/doc/models/proforma-invoice-tax.md +++ b/doc/models/proforma-invoice-tax.md @@ -1,31 +1,31 @@ - -# Proforma Invoice Tax - -## Structure - -`ProformaInvoiceTax` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `Title` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `SourceType` | [`*models.ProformaInvoiceTaxSourceType`](../../doc/models/proforma-invoice-tax-source-type.md) | Optional | - | -| `Percentage` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `TaxableAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `TaxAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | -| `LineItemBreakouts` | [`[]models.InvoiceTaxBreakout`](../../doc/models/invoice-tax-breakout.md) | Optional | **Constraints**: *Minimum Items*: `1`, *Unique Items Required* | - -## Example (as JSON) - -```json -{ - "uid": "uid8", - "title": "title4", - "source_type": "Tax", - "percentage": "percentage6", - "taxable_amount": "taxable_amount2" -} -``` - + +# Proforma Invoice Tax + +## Structure + +`ProformaInvoiceTax` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `Title` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `SourceType` | [`*models.ProformaInvoiceTaxSourceType`](../../doc/models/proforma-invoice-tax-source-type.md) | Optional | - | +| `Percentage` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `TaxableAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `TaxAmount` | `*string` | Optional | **Constraints**: *Minimum Length*: `1` | +| `LineItemBreakouts` | [`[]models.InvoiceTaxBreakout`](../../doc/models/invoice-tax-breakout.md) | Optional | **Constraints**: *Minimum Items*: `1`, *Unique Items Required* | + +## Example (as JSON) + +```json +{ + "uid": "uid8", + "title": "title4", + "source_type": "Tax", + "percentage": "percentage6", + "taxable_amount": "taxable_amount2" +} +``` + diff --git a/doc/models/proforma-invoice.md b/doc/models/proforma-invoice.md index e2000f2f..8e247a8e 100644 --- a/doc/models/proforma-invoice.md +++ b/doc/models/proforma-invoice.md @@ -1,61 +1,61 @@ - -# Proforma Invoice - -## Structure - -`ProformaInvoice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `SiteId` | `*int` | Optional | - | -| `CustomerId` | `Optional[int]` | Optional | - | -| `SubscriptionId` | `Optional[int]` | Optional | - | -| `Number` | `Optional[int]` | Optional | - | -| `SequenceNumber` | `Optional[int]` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `DeliveryDate` | `*time.Time` | Optional | - | -| `Status` | [`*models.ProformaInvoiceStatus`](../../doc/models/proforma-invoice-status.md) | Optional | - | -| `CollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | -| `PaymentInstructions` | `*string` | Optional | - | -| `Currency` | `*string` | Optional | - | -| `ConsolidationLevel` | [`*models.InvoiceConsolidationLevel`](../../doc/models/invoice-consolidation-level.md) | Optional | Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values:

* "none": A normal invoice with no consolidation.
* "child": An invoice segment which has been combined into a consolidated invoice.
* "parent": A consolidated invoice, whose contents are composed of invoice segments.

"Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments.

See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). | -| `ProductName` | `*string` | Optional | - | -| `ProductFamilyName` | `*string` | Optional | - | -| `Role` | [`*models.ProformaInvoiceRole`](../../doc/models/proforma-invoice-role.md) | Optional | 'proforma' value is deprecated in favor of proforma_adhoc and proforma_automatic | -| `Seller` | [`*models.InvoiceSeller`](../../doc/models/invoice-seller.md) | Optional | Information about the seller (merchant) listed on the masthead of the invoice. | -| `Customer` | [`*models.InvoiceCustomer`](../../doc/models/invoice-customer.md) | Optional | Information about the customer who is owner or recipient the invoiced subscription. | -| `Memo` | `*string` | Optional | - | -| `BillingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | - | -| `ShippingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | - | -| `SubtotalAmount` | `*string` | Optional | - | -| `DiscountAmount` | `*string` | Optional | - | -| `TaxAmount` | `*string` | Optional | - | -| `TotalAmount` | `*string` | Optional | - | -| `CreditAmount` | `*string` | Optional | - | -| `PaidAmount` | `*string` | Optional | - | -| `RefundAmount` | `*string` | Optional | - | -| `DueAmount` | `*string` | Optional | - | -| `LineItems` | [`[]models.InvoiceLineItem`](../../doc/models/invoice-line-item.md) | Optional | - | -| `Discounts` | [`[]models.ProformaInvoiceDiscount`](../../doc/models/proforma-invoice-discount.md) | Optional | - | -| `Taxes` | [`[]models.ProformaInvoiceTax`](../../doc/models/proforma-invoice-tax.md) | Optional | - | -| `Credits` | [`[]models.ProformaInvoiceCredit`](../../doc/models/proforma-invoice-credit.md) | Optional | - | -| `Payments` | [`[]models.ProformaInvoicePayment`](../../doc/models/proforma-invoice-payment.md) | Optional | - | -| `CustomFields` | [`[]models.InvoiceCustomField`](../../doc/models/invoice-custom-field.md) | Optional | - | -| `PublicUrl` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "collection_method": "automatic", - "uid": "uid6", - "site_id": 196, - "customer_id": 52, - "subscription_id": 124, - "number": 0 -} -``` - + +# Proforma Invoice + +## Structure + +`ProformaInvoice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `SiteId` | `*int` | Optional | - | +| `CustomerId` | `models.Optional[int]` | Optional | - | +| `SubscriptionId` | `models.Optional[int]` | Optional | - | +| `Number` | `models.Optional[int]` | Optional | - | +| `SequenceNumber` | `models.Optional[int]` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `DeliveryDate` | `*time.Time` | Optional | - | +| `Status` | [`*models.ProformaInvoiceStatus`](../../doc/models/proforma-invoice-status.md) | Optional | - | +| `CollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | +| `PaymentInstructions` | `*string` | Optional | - | +| `Currency` | `*string` | Optional | - | +| `ConsolidationLevel` | [`*models.InvoiceConsolidationLevel`](../../doc/models/invoice-consolidation-level.md) | Optional | Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values:

* "none": A normal invoice with no consolidation.
* "child": An invoice segment which has been combined into a consolidated invoice.
* "parent": A consolidated invoice, whose contents are composed of invoice segments.

"Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments.

See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). | +| `ProductName` | `*string` | Optional | - | +| `ProductFamilyName` | `*string` | Optional | - | +| `Role` | [`*models.ProformaInvoiceRole`](../../doc/models/proforma-invoice-role.md) | Optional | 'proforma' value is deprecated in favor of proforma_adhoc and proforma_automatic | +| `Seller` | [`*models.InvoiceSeller`](../../doc/models/invoice-seller.md) | Optional | Information about the seller (merchant) listed on the masthead of the invoice. | +| `Customer` | [`*models.InvoiceCustomer`](../../doc/models/invoice-customer.md) | Optional | Information about the customer who is owner or recipient the invoiced subscription. | +| `Memo` | `*string` | Optional | - | +| `BillingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | - | +| `ShippingAddress` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | - | +| `SubtotalAmount` | `*string` | Optional | - | +| `DiscountAmount` | `*string` | Optional | - | +| `TaxAmount` | `*string` | Optional | - | +| `TotalAmount` | `*string` | Optional | - | +| `CreditAmount` | `*string` | Optional | - | +| `PaidAmount` | `*string` | Optional | - | +| `RefundAmount` | `*string` | Optional | - | +| `DueAmount` | `*string` | Optional | - | +| `LineItems` | [`[]models.InvoiceLineItem`](../../doc/models/invoice-line-item.md) | Optional | - | +| `Discounts` | [`[]models.ProformaInvoiceDiscount`](../../doc/models/proforma-invoice-discount.md) | Optional | - | +| `Taxes` | [`[]models.ProformaInvoiceTax`](../../doc/models/proforma-invoice-tax.md) | Optional | - | +| `Credits` | [`[]models.ProformaInvoiceCredit`](../../doc/models/proforma-invoice-credit.md) | Optional | - | +| `Payments` | [`[]models.ProformaInvoicePayment`](../../doc/models/proforma-invoice-payment.md) | Optional | - | +| `CustomFields` | [`[]models.InvoiceCustomField`](../../doc/models/invoice-custom-field.md) | Optional | - | +| `PublicUrl` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "collection_method": "automatic", + "uid": "uid6", + "site_id": 196, + "customer_id": 52, + "subscription_id": 124, + "number": 0 +} +``` + diff --git a/doc/models/proration.md b/doc/models/proration.md index bb199af6..3b71324d 100644 --- a/doc/models/proration.md +++ b/doc/models/proration.md @@ -1,21 +1,21 @@ - -# Proration - -## Structure - -`Proration` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PreservePeriod` | `*bool` | Optional | The alternative to sending preserve_period as a direct attribute to migration | - -## Example (as JSON) - -```json -{ - "preserve_period": false -} -``` - + +# Proration + +## Structure + +`Proration` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PreservePeriod` | `*bool` | Optional | The alternative to sending preserve_period as a direct attribute to migration | + +## Example (as JSON) + +```json +{ + "preserve_period": false +} +``` + diff --git a/doc/models/public-key.md b/doc/models/public-key.md index 2f38a16d..08a9df38 100644 --- a/doc/models/public-key.md +++ b/doc/models/public-key.md @@ -1,25 +1,25 @@ - -# Public Key - -## Structure - -`PublicKey` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PublicKey` | `*string` | Optional | - | -| `RequiresSecurityToken` | `*bool` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | - -## Example (as JSON) - -```json -{ - "public_key": "public_key8", - "requires_security_token": false, - "created_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Public Key + +## Structure + +`PublicKey` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PublicKey` | `*string` | Optional | - | +| `RequiresSecurityToken` | `*bool` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | + +## Example (as JSON) + +```json +{ + "public_key": "public_key8", + "requires_security_token": false, + "created_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/public-signup-page.md b/doc/models/public-signup-page.md index 4cf3ffe4..103d2081 100644 --- a/doc/models/public-signup-page.md +++ b/doc/models/public-signup-page.md @@ -1,27 +1,27 @@ - -# Public Signup Page - -## Structure - -`PublicSignupPage` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | The id of the signup page (public_signup_pages only) | -| `ReturnUrl` | `Optional[string]` | Optional | The url to which a customer will be returned after a successful signup (public_signup_pages only) | -| `ReturnParams` | `Optional[string]` | Optional | The params to be appended to the return_url (public_signup_pages only) | -| `Url` | `*string` | Optional | The url where the signup page can be viewed (public_signup_pages only) | - -## Example (as JSON) - -```json -{ - "id": 6, - "return_url": "return_url0", - "return_params": "return_params2", - "url": "url8" -} -``` - + +# Public Signup Page + +## Structure + +`PublicSignupPage` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | The id of the signup page (public_signup_pages only) | +| `ReturnUrl` | `models.Optional[string]` | Optional | The url to which a customer will be returned after a successful signup (public_signup_pages only) | +| `ReturnParams` | `models.Optional[string]` | Optional | The params to be appended to the return_url (public_signup_pages only) | +| `Url` | `*string` | Optional | The url where the signup page can be viewed (public_signup_pages only) | + +## Example (as JSON) + +```json +{ + "id": 6, + "return_url": "return_url0", + "return_params": "return_params2", + "url": "url8" +} +``` + diff --git a/doc/models/quantity-based-component.md b/doc/models/quantity-based-component.md index f0b5d3c4..670d48f4 100644 --- a/doc/models/quantity-based-component.md +++ b/doc/models/quantity-based-component.md @@ -1,62 +1,53 @@ - -# Quantity Based Component - -## Structure - -`QuantityBasedComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `string` | Required | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | -| `UnitName` | `string` | Required | The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item | -| `Description` | `*string` | Optional | A description for the component that will be displayed to the user on the hosted signup page. | -| `Handle` | `*string` | Optional | A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'.
**Constraints**: *Pattern*: `^[a-z0-9][a-z0-9\-_:.]*$` | -| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | -| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `PricePoints` | [`[]models.ComponentPricePointItem`](../../doc/models/component-price-point-item.md) | Optional | - | -| `UnitPrice` | `*interface{}` | Optional | The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 | -| `TaxCode` | `*string` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | -| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | -| `PriceInCents` | `*string` | Optional | deprecated May 2011 - use unit_price instead | -| `Recurring` | `*bool` | Optional | - | -| `DisplayOnHostedPage` | `*bool` | Optional | - | -| `AllowFractionalQuantities` | `*bool` | Optional | - | -| `PublicSignupPageIds` | `[]int` | Optional | - | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. | - -## Example (as JSON) - -```json -{ - "name": "name8", - "unit_name": "unit_name0", - "description": "description8", - "handle": "handle4", - "taxable": false, - "pricing_scheme": "per_unit", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ], - "upgrade_charge": "full" -} -``` - + +# Quantity Based Component + +## Structure + +`QuantityBasedComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `string` | Required | A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". | +| `UnitName` | `string` | Required | The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item | +| `Description` | `*string` | Optional | A description for the component that will be displayed to the user on the hosted signup page. | +| `Handle` | `*string` | Optional | A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'.
**Constraints**: *Pattern*: `^[a-z0-9][a-z0-9\-_:.]*$` | +| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | +| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `PricePoints` | [`[]models.ComponentPricePointItem`](../../doc/models/component-price-point-item.md) | Optional | - | +| `UnitPrice` | [`*models.QuantityBasedComponentUnitPrice`](../../doc/models/containers/quantity-based-component-unit-price.md) | Optional | This is a container for one-of cases. | +| `TaxCode` | `*string` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | +| `HideDateRangeOnInvoice` | `*bool` | Optional | (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. | +| `PriceInCents` | `*string` | Optional | deprecated May 2011 - use unit_price instead | +| `Recurring` | `*bool` | Optional | - | +| `DisplayOnHostedPage` | `*bool` | Optional | - | +| `AllowFractionalQuantities` | `*bool` | Optional | - | +| `PublicSignupPageIds` | `[]int` | Optional | - | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. | + +## Example (as JSON) + +```json +{ + "name": "name8", + "unit_name": "unit_name0", + "description": "description8", + "handle": "handle4", + "taxable": false, + "pricing_scheme": "per_unit", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "upgrade_charge": "full" +} +``` + diff --git a/doc/models/reactivate-subscription-group-request.md b/doc/models/reactivate-subscription-group-request.md index af3c977f..3326b405 100644 --- a/doc/models/reactivate-subscription-group-request.md +++ b/doc/models/reactivate-subscription-group-request.md @@ -1,23 +1,23 @@ - -# Reactivate Subscription Group Request - -## Structure - -`ReactivateSubscriptionGroupRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Resume` | `*bool` | Optional | - | -| `ResumeMembers` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "resume": false, - "resume_members": false -} -``` - + +# Reactivate Subscription Group Request + +## Structure + +`ReactivateSubscriptionGroupRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Resume` | `*bool` | Optional | - | +| `ResumeMembers` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "resume": false, + "resume_members": false +} +``` + diff --git a/doc/models/reactivate-subscription-group-response.md b/doc/models/reactivate-subscription-group-response.md index edd84e5d..b2256cd3 100644 --- a/doc/models/reactivate-subscription-group-response.md +++ b/doc/models/reactivate-subscription-group-response.md @@ -1,36 +1,36 @@ - -# Reactivate Subscription Group Response - -## Structure - -`ReactivateSubscriptionGroupResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `Scheme` | `*int` | Optional | - | -| `CustomerId` | `*int` | Optional | - | -| `PaymentProfileId` | `*int` | Optional | - | -| `SubscriptionIds` | `[]int` | Optional | - | -| `PrimarySubscriptionId` | `*int` | Optional | - | -| `NextAssessmentAt` | `*time.Time` | Optional | - | -| `State` | `*string` | Optional | - | -| `CancelAtEndOfPeriod` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "uid": "uid4", - "scheme": 66, - "customer_id": 86, - "payment_profile_id": 250, - "subscription_ids": [ - 196, - 197 - ] -} -``` - + +# Reactivate Subscription Group Response + +## Structure + +`ReactivateSubscriptionGroupResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `Scheme` | `*int` | Optional | - | +| `CustomerId` | `*int` | Optional | - | +| `PaymentProfileId` | `*int` | Optional | - | +| `SubscriptionIds` | `[]int` | Optional | - | +| `PrimarySubscriptionId` | `*int` | Optional | - | +| `NextAssessmentAt` | `*time.Time` | Optional | - | +| `State` | `*string` | Optional | - | +| `CancelAtEndOfPeriod` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "uid": "uid4", + "scheme": 66, + "customer_id": 86, + "payment_profile_id": 250, + "subscription_ids": [ + 196, + 197 + ] +} +``` + diff --git a/doc/models/reactivate-subscription-request.md b/doc/models/reactivate-subscription-request.md index ad50084e..3b494bf3 100644 --- a/doc/models/reactivate-subscription-request.md +++ b/doc/models/reactivate-subscription-request.md @@ -1,32 +1,32 @@ - -# Reactivate Subscription Request - -## Structure - -`ReactivateSubscriptionRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CalendarBilling` | [`*models.ReactivationBilling`](../../doc/models/reactivation-billing.md) | Optional | These values are only applicable to subscriptions using calendar billing | -| `IncludeTrial` | `*bool` | Optional | If `true` is sent, the reactivated Subscription will include a trial if one is available. If `false` is sent, the trial period will be ignored. | -| `PreserveBalance` | `*bool` | Optional | If `true` is passed, the existing subscription balance will NOT be cleared/reset before adding the additional reactivation charges. | -| `CouponCode` | `*string` | Optional | The coupon code to be applied during reactivation. | -| `UseCreditsAndPrepayments` | `*bool` | Optional | If true is sent, Chargify will use service credits and prepayments upon reactivation. If false is sent, the service credits and prepayments will be ignored. | -| `Resume` | `*interface{}` | Optional | If `true`, Chargify will attempt to resume the subscription's billing period. if not resumable, the subscription will be reactivated with a new billing period. If `false`: Chargify will only attempt to reactivate the subscription. | - -## Example (as JSON) - -```json -{ - "calendar_billing": { - "reactivation_charge": "prorated" - }, - "include_trial": false, - "preserve_balance": false, - "coupon_code": "coupon_code6", - "use_credits_and_prepayments": false -} -``` - + +# Reactivate Subscription Request + +## Structure + +`ReactivateSubscriptionRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CalendarBilling` | [`*models.ReactivationBilling`](../../doc/models/reactivation-billing.md) | Optional | These values are only applicable to subscriptions using calendar billing | +| `IncludeTrial` | `*bool` | Optional | If `true` is sent, the reactivated Subscription will include a trial if one is available. If `false` is sent, the trial period will be ignored. | +| `PreserveBalance` | `*bool` | Optional | If `true` is passed, the existing subscription balance will NOT be cleared/reset before adding the additional reactivation charges. | +| `CouponCode` | `*string` | Optional | The coupon code to be applied during reactivation. | +| `UseCreditsAndPrepayments` | `*bool` | Optional | If true is sent, Chargify will use service credits and prepayments upon reactivation. If false is sent, the service credits and prepayments will be ignored. | +| `Resume` | [`*models.ReactivateSubscriptionRequestResume`](../../doc/models/containers/reactivate-subscription-request-resume.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "calendar_billing": { + "reactivation_charge": "prorated" + }, + "include_trial": false, + "preserve_balance": false, + "coupon_code": "coupon_code6", + "use_credits_and_prepayments": false +} +``` + diff --git a/doc/models/reactivation-billing.md b/doc/models/reactivation-billing.md index 5683774f..7b63ba59 100644 --- a/doc/models/reactivation-billing.md +++ b/doc/models/reactivation-billing.md @@ -1,23 +1,23 @@ - -# Reactivation Billing - -These values are only applicable to subscriptions using calendar billing - -## Structure - -`ReactivationBilling` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ReactivationCharge` | [`*models.ReactivationCharge`](../../doc/models/reactivation-charge.md) | Optional | You may choose how to handle the reactivation charge for that subscription: 1) `prorated` A prorated charge for the product price will be attempted for to complete the period 2) `immediate` A full-price charge for the product price will be attempted immediately 3) `delayed` A full-price charge for the product price will be attempted at the next renewal
**Default**: `"prorated"` | - -## Example (as JSON) - -```json -{ - "reactivation_charge": "prorated" -} -``` - + +# Reactivation Billing + +These values are only applicable to subscriptions using calendar billing + +## Structure + +`ReactivationBilling` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ReactivationCharge` | [`*models.ReactivationCharge`](../../doc/models/reactivation-charge.md) | Optional | You may choose how to handle the reactivation charge for that subscription: 1) `prorated` A prorated charge for the product price will be attempted for to complete the period 2) `immediate` A full-price charge for the product price will be attempted immediately 3) `delayed` A full-price charge for the product price will be attempted at the next renewal
**Default**: `"prorated"` | + +## Example (as JSON) + +```json +{ + "reactivation_charge": "prorated" +} +``` + diff --git a/doc/models/reactivation-charge.md b/doc/models/reactivation-charge.md index 0e142944..dbe0bc6e 100644 --- a/doc/models/reactivation-charge.md +++ b/doc/models/reactivation-charge.md @@ -1,17 +1,17 @@ - -# Reactivation Charge - -You may choose how to handle the reactivation charge for that subscription: 1) `prorated` A prorated charge for the product price will be attempted for to complete the period 2) `immediate` A full-price charge for the product price will be attempted immediately 3) `delayed` A full-price charge for the product price will be attempted at the next renewal - -## Enumeration - -`ReactivationCharge` - -## Fields - -| Name | -| --- | -| `PRORATED` | -| `IMMEDIATE` | -| `DELAYED` | - + +# Reactivation Charge + +You may choose how to handle the reactivation charge for that subscription: 1) `prorated` A prorated charge for the product price will be attempted for to complete the period 2) `immediate` A full-price charge for the product price will be attempted immediately 3) `delayed` A full-price charge for the product price will be attempted at the next renewal + +## Enumeration + +`ReactivationCharge` + +## Fields + +| Name | +| --- | +| `PRORATED` | +| `IMMEDIATE` | +| `DELAYED` | + diff --git a/doc/models/reason-code-response.md b/doc/models/reason-code-response.md index 738fa76c..c3127b46 100644 --- a/doc/models/reason-code-response.md +++ b/doc/models/reason-code-response.md @@ -1,27 +1,27 @@ - -# Reason Code Response - -## Structure - -`ReasonCodeResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ReasonCode` | [`models.ReasonCode`](../../doc/models/reason-code.md) | Required | - | - -## Example (as JSON) - -```json -{ - "reason_code": { - "id": 240, - "site_id": 166, - "code": "code4", - "description": "description6", - "position": 14 - } -} -``` - + +# Reason Code Response + +## Structure + +`ReasonCodeResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ReasonCode` | [`models.ReasonCode`](../../doc/models/reason-code.md) | Required | - | + +## Example (as JSON) + +```json +{ + "reason_code": { + "id": 240, + "site_id": 166, + "code": "code4", + "description": "description6", + "position": 14 + } +} +``` + diff --git a/doc/models/reason-code.md b/doc/models/reason-code.md index 59541376..7db3b9db 100644 --- a/doc/models/reason-code.md +++ b/doc/models/reason-code.md @@ -1,31 +1,31 @@ - -# Reason Code - -## Structure - -`ReasonCode` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `SiteId` | `*int` | Optional | - | -| `Code` | `*string` | Optional | - | -| `Description` | `*string` | Optional | - | -| `Position` | `*int` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `UpdatedAt` | `*time.Time` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 164, - "site_id": 90, - "code": "code0", - "description": "description2", - "position": 194 -} -``` - + +# Reason Code + +## Structure + +`ReasonCode` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `SiteId` | `*int` | Optional | - | +| `Code` | `*string` | Optional | - | +| `Description` | `*string` | Optional | - | +| `Position` | `*int` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `UpdatedAt` | `*time.Time` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 164, + "site_id": 90, + "code": "code0", + "description": "description2", + "position": 194 +} +``` + diff --git a/doc/models/reason-codes-json-response.md b/doc/models/reason-codes-json-response.md index 36faea37..319fe242 100644 --- a/doc/models/reason-codes-json-response.md +++ b/doc/models/reason-codes-json-response.md @@ -1,21 +1,21 @@ - -# Reason Codes Json Response - -## Structure - -`ReasonCodesJsonResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Ok` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "ok": "ok2" -} -``` - + +# Reason Codes Json Response + +## Structure + +`ReasonCodesJsonResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Ok` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "ok": "ok2" +} +``` + diff --git a/doc/models/record-payment-request.md b/doc/models/record-payment-request.md index 814ea51c..b59bacca 100644 --- a/doc/models/record-payment-request.md +++ b/doc/models/record-payment-request.md @@ -1,26 +1,26 @@ - -# Record Payment Request - -## Structure - -`RecordPaymentRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Payment` | [`models.CreatePayment`](../../doc/models/create-payment.md) | Required | - | - -## Example (as JSON) - -```json -{ - "payment": { - "amount": "amount8", - "memo": "memo0", - "payment_details": "payment_details6", - "payment_method": "cash" - } -} -``` - + +# Record Payment Request + +## Structure + +`RecordPaymentRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Payment` | [`models.CreatePayment`](../../doc/models/create-payment.md) | Required | - | + +## Example (as JSON) + +```json +{ + "payment": { + "amount": "amount8", + "memo": "memo0", + "payment_details": "payment_details6", + "payment_method": "cash" + } +} +``` + diff --git a/doc/models/record-payment-response.md b/doc/models/record-payment-response.md index 042e2563..dd3be61f 100644 --- a/doc/models/record-payment-response.md +++ b/doc/models/record-payment-response.md @@ -1,46 +1,46 @@ - -# Record Payment Response - -## Structure - -`RecordPaymentResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PaidInvoices` | [`[]models.PaidInvoice`](../../doc/models/paid-invoice.md) | Optional | - | -| `Prepayment` | [`Optional[models.InvoicePrePayment]`](../../doc/models/invoice-pre-payment.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "paid_invoices": [ - { - "invoice_id": "invoice_id8", - "status": "draft", - "due_amount": "due_amount0", - "paid_amount": "paid_amount0" - }, - { - "invoice_id": "invoice_id8", - "status": "draft", - "due_amount": "due_amount0", - "paid_amount": "paid_amount0" - }, - { - "invoice_id": "invoice_id8", - "status": "draft", - "due_amount": "due_amount0", - "paid_amount": "paid_amount0" - } - ], - "prepayment": { - "subscription_id": 148, - "amount_in_cents": 124, - "ending_balance_in_cents": 164 - } -} -``` - + +# Record Payment Response + +## Structure + +`RecordPaymentResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PaidInvoices` | [`[]models.PaidInvoice`](../../doc/models/paid-invoice.md) | Optional | - | +| `Prepayment` | [`models.Optional[models.RecordPaymentResponsePrepayment]`](../../doc/models/containers/record-payment-response-prepayment.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "paid_invoices": [ + { + "invoice_id": "invoice_id8", + "status": "draft", + "due_amount": "due_amount0", + "paid_amount": "paid_amount0" + }, + { + "invoice_id": "invoice_id8", + "status": "draft", + "due_amount": "due_amount0", + "paid_amount": "paid_amount0" + }, + { + "invoice_id": "invoice_id8", + "status": "draft", + "due_amount": "due_amount0", + "paid_amount": "paid_amount0" + } + ], + "prepayment": { + "subscription_id": 180, + "amount_in_cents": 100, + "ending_balance_in_cents": 60 + } +} +``` + diff --git a/doc/models/recurring-scheme.md b/doc/models/recurring-scheme.md index c7d81f27..57f596e1 100644 --- a/doc/models/recurring-scheme.md +++ b/doc/models/recurring-scheme.md @@ -1,15 +1,15 @@ - -# Recurring Scheme - -## Enumeration - -`RecurringScheme` - -## Fields - -| Name | -| --- | -| `DONOTRECUR` | -| `RECURINDEFINITELY` | -| `RECURWITHDURATION` | - + +# Recurring Scheme + +## Enumeration + +`RecurringScheme` + +## Fields + +| Name | +| --- | +| `DONOTRECUR` | +| `RECURINDEFINITELY` | +| `RECURWITHDURATION` | + diff --git a/doc/models/referral-code.md b/doc/models/referral-code.md index 326323c5..e91d0c0b 100644 --- a/doc/models/referral-code.md +++ b/doc/models/referral-code.md @@ -1,27 +1,27 @@ - -# Referral Code - -## Structure - -`ReferralCode` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `SiteId` | `*int` | Optional | - | -| `SubscriptionId` | `*int` | Optional | - | -| `Code` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 42, - "site_id": 224, - "subscription_id": 152, - "code": "code6" -} -``` - + +# Referral Code + +## Structure + +`ReferralCode` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `SiteId` | `*int` | Optional | - | +| `SubscriptionId` | `*int` | Optional | - | +| `Code` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 42, + "site_id": 224, + "subscription_id": 152, + "code": "code6" +} +``` + diff --git a/doc/models/referral-validation-response.md b/doc/models/referral-validation-response.md index fe4ea5db..d7e71832 100644 --- a/doc/models/referral-validation-response.md +++ b/doc/models/referral-validation-response.md @@ -1,26 +1,26 @@ - -# Referral Validation Response - -## Structure - -`ReferralValidationResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ReferralCode` | [`*models.ReferralCode`](../../doc/models/referral-code.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "referral_code": { - "id": 46, - "site_id": 228, - "subscription_id": 156, - "code": "code0" - } -} -``` - + +# Referral Validation Response + +## Structure + +`ReferralValidationResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ReferralCode` | [`*models.ReferralCode`](../../doc/models/referral-code.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "referral_code": { + "id": 46, + "site_id": 228, + "subscription_id": 156, + "code": "code0" + } +} +``` + diff --git a/doc/models/refund-consolidated-invoice.md b/doc/models/refund-consolidated-invoice.md new file mode 100644 index 00000000..5f6f345c --- /dev/null +++ b/doc/models/refund-consolidated-invoice.md @@ -0,0 +1,36 @@ + +# Refund Consolidated Invoice + +Refund consolidated invoice + +## Structure + +`RefundConsolidatedInvoice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Memo` | `string` | Required | A description for the refund | +| `PaymentId` | `int` | Required | The ID of the payment to be refunded | +| `SegmentUids` | [`models.RefundConsolidatedInvoiceSegmentUids`](../../doc/models/containers/refund-consolidated-invoice-segment-uids.md) | Required | This is a container for one-of cases. | +| `External` | `*bool` | Optional | Flag that marks refund as external (no money is returned to the customer). Defaults to `false`. | +| `ApplyCredit` | `*bool` | Optional | If set to true, creates credit and applies it to an invoice. Defaults to `false`. | +| `Amount` | `*string` | Optional | The amount of payment to be refunded in decimal format. Example: "10.50". This will default to the full amount of the payment if not provided. | + +## Example (as JSON) + +```json +{ + "memo": "memo0", + "payment_id": 46, + "segment_uids": [ + "String0", + "String1" + ], + "external": false, + "apply_credit": false, + "amount": "amount8" +} +``` + diff --git a/doc/models/refund-invoice-event-data.md b/doc/models/refund-invoice-event-data.md new file mode 100644 index 00000000..b4ddb239 --- /dev/null +++ b/doc/models/refund-invoice-event-data.md @@ -0,0 +1,45 @@ + +# Refund Invoice Event Data + +Example schema for an `refund_invoice` event + +## Structure + +`RefundInvoiceEventData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ApplyCredit` | `bool` | Required | If true, credit was created and applied it to the invoice. | +| `ConsolidationLevel` | [`*models.InvoiceConsolidationLevel`](../../doc/models/invoice-consolidation-level.md) | Optional | Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values:

* "none": A normal invoice with no consolidation.
* "child": An invoice segment which has been combined into a consolidated invoice.
* "parent": A consolidated invoice, whose contents are composed of invoice segments.

"Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments.

See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). | +| `CreditNoteAttributes` | [`models.CreditNote`](../../doc/models/credit-note.md) | Required | - | +| `Memo` | `*string` | Optional | The refund memo. | +| `OriginalAmount` | `*string` | Optional | The full, original amount of the refund. | +| `PaymentId` | `int` | Required | The ID of the payment transaction to be refunded. | +| `RefundAmount` | `string` | Required | The amount of the refund. | +| `RefundId` | `int` | Required | The ID of the refund transaction. | +| `TransactionTime` | `time.Time` | Required | The time the refund was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" | + +## Example (as JSON) + +```json +{ + "apply_credit": false, + "consolidation_level": "parent", + "credit_note_attributes": { + "uid": "uid2", + "site_id": 72, + "customer_id": 184, + "subscription_id": 0, + "number": "number0" + }, + "memo": "memo0", + "original_amount": "original_amount0", + "payment_id": 114, + "refund_amount": "refund_amount8", + "refund_id": 158, + "transaction_time": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/refund-invoice-request.md b/doc/models/refund-invoice-request.md index fab8e351..7e757e15 100644 --- a/doc/models/refund-invoice-request.md +++ b/doc/models/refund-invoice-request.md @@ -1,27 +1,28 @@ - -# Refund Invoice Request - -## Structure - -`RefundInvoiceRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Refund` | [`models.Refund`](../../doc/models/refund.md) | Required | - | - -## Example (as JSON) - -```json -{ - "refund": { - "amount": "amount0", - "memo": "memo2", - "payment_id": 44, - "external": false, - "apply_credit": false - } -} -``` - + +# Refund Invoice Request + +## Structure + +`RefundInvoiceRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Refund` | [`models.RefundInvoiceRequestRefund`](../../doc/models/containers/refund-invoice-request-refund.md) | Required | This is a container for any-of cases. | + +## Example (as JSON) + +```json +{ + "refund": { + "amount": "amount8", + "memo": "memo0", + "payment_id": 0, + "external": false, + "apply_credit": false, + "void_invoice": false + } +} +``` + diff --git a/doc/models/refund-invoice.md b/doc/models/refund-invoice.md new file mode 100644 index 00000000..6fb2cf42 --- /dev/null +++ b/doc/models/refund-invoice.md @@ -0,0 +1,33 @@ + +# Refund Invoice + +Refund an invoice or a segment of a consolidated invoice. + +## Structure + +`RefundInvoice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Amount` | `string` | Required | The amount to be refunded in decimal format as a string. Example: "10.50". Must not exceed the remaining refundable balance of the payment. | +| `Memo` | `string` | Required | A description that will be attached to the refund | +| `PaymentId` | `int` | Required | The ID of the payment to be refunded | +| `External` | `*bool` | Optional | Flag that marks refund as external (no money is returned to the customer). Defaults to `false`. | +| `ApplyCredit` | `*bool` | Optional | If set to true, creates credit and applies it to an invoice. Defaults to `false`. | +| `VoidInvoice` | `*bool` | Optional | If `apply_credit` set to false and refunding full amount, if `void_invoice` set to true, invoice will be voided after refund. Defaults to `false`. | + +## Example (as JSON) + +```json +{ + "amount": "amount8", + "memo": "memo0", + "payment_id": 0, + "external": false, + "apply_credit": false, + "void_invoice": false +} +``` + diff --git a/doc/models/refund-prepayment-aggregated-error.md b/doc/models/refund-prepayment-aggregated-error.md index 8c0ea63d..5de498b1 100644 --- a/doc/models/refund-prepayment-aggregated-error.md +++ b/doc/models/refund-prepayment-aggregated-error.md @@ -1,32 +1,32 @@ - -# Refund Prepayment Aggregated Error - -## Structure - -`RefundPrepaymentAggregatedError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Refund` | [`*models.PrepaymentAggregatedError`](../../doc/models/prepayment-aggregated-error.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "refund": { - "amount_in_cents": [ - "amount_in_cents5" - ], - "base": [ - "base7" - ], - "external": [ - "external0", - "external1" - ] - } -} -``` - + +# Refund Prepayment Aggregated Error + +## Structure + +`RefundPrepaymentAggregatedError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Refund` | [`*models.PrepaymentAggregatedError`](../../doc/models/prepayment-aggregated-error.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "refund": { + "amount_in_cents": [ + "amount_in_cents5" + ], + "base": [ + "base7" + ], + "external": [ + "external0", + "external1" + ] + } +} +``` + diff --git a/doc/models/refund-prepayment-aggregated-errors-response-exception.md b/doc/models/refund-prepayment-aggregated-errors-response-exception.md index 756f4826..39fd5d08 100644 --- a/doc/models/refund-prepayment-aggregated-errors-response-exception.md +++ b/doc/models/refund-prepayment-aggregated-errors-response-exception.md @@ -1,36 +1,36 @@ - -# Refund Prepayment Aggregated Errors Response Exception - -Errors returned on creating a refund prepayment, grouped by field, as arrays of strings. - -## Structure - -`RefundPrepaymentAggregatedErrorsResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`*models.RefundPrepaymentAggregatedError`](../../doc/models/refund-prepayment-aggregated-error.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": { - "refund": { - "amount_in_cents": [ - "amount_in_cents5" - ], - "base": [ - "base7" - ], - "external": [ - "external0", - "external1" - ] - } - } -} -``` - + +# Refund Prepayment Aggregated Errors Response Exception + +Errors returned on creating a refund prepayment, grouped by field, as arrays of strings. + +## Structure + +`RefundPrepaymentAggregatedErrorsResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`*models.RefundPrepaymentAggregatedError`](../../doc/models/refund-prepayment-aggregated-error.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": { + "refund": { + "amount_in_cents": [ + "amount_in_cents5" + ], + "base": [ + "base7" + ], + "external": [ + "external0", + "external1" + ] + } + } +} +``` + diff --git a/doc/models/refund-prepayment-base-errors-response-exception.md b/doc/models/refund-prepayment-base-errors-response-exception.md index e1ddf21f..ae3869f0 100644 --- a/doc/models/refund-prepayment-base-errors-response-exception.md +++ b/doc/models/refund-prepayment-base-errors-response-exception.md @@ -1,32 +1,32 @@ - -# Refund Prepayment Base Errors Response Exception - -Errors returned on creating a refund prepayment when bad request - -## Structure - -`RefundPrepaymentBaseErrorsResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`*models.RefundPrepaymentBaseRefundError`](../../doc/models/refund-prepayment-base-refund-error.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": { - "refund": { - "base": [ - { - "key1": "val1", - "key2": "val2" - } - ] - } - } -} -``` - + +# Refund Prepayment Base Errors Response Exception + +Errors returned on creating a refund prepayment when bad request + +## Structure + +`RefundPrepaymentBaseErrorsResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`*models.RefundPrepaymentBaseRefundError`](../../doc/models/refund-prepayment-base-refund-error.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": { + "refund": { + "base": [ + { + "key1": "val1", + "key2": "val2" + } + ] + } + } +} +``` + diff --git a/doc/models/refund-prepayment-base-refund-error.md b/doc/models/refund-prepayment-base-refund-error.md index f1267ad5..e9658934 100644 --- a/doc/models/refund-prepayment-base-refund-error.md +++ b/doc/models/refund-prepayment-base-refund-error.md @@ -1,28 +1,28 @@ - -# Refund Prepayment Base Refund Error - -## Structure - -`RefundPrepaymentBaseRefundError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Refund` | [`*models.BaseRefundError`](../../doc/models/base-refund-error.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "refund": { - "base": [ - { - "key1": "val1", - "key2": "val2" - } - ] - } -} -``` - + +# Refund Prepayment Base Refund Error + +## Structure + +`RefundPrepaymentBaseRefundError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Refund` | [`*models.BaseRefundError`](../../doc/models/base-refund-error.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "refund": { + "base": [ + { + "key1": "val1", + "key2": "val2" + } + ] + } +} +``` + diff --git a/doc/models/refund-prepayment-request.md b/doc/models/refund-prepayment-request.md index d1f70acb..4d1200c6 100644 --- a/doc/models/refund-prepayment-request.md +++ b/doc/models/refund-prepayment-request.md @@ -1,29 +1,26 @@ - -# Refund Prepayment Request - -## Structure - -`RefundPrepaymentRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Refund` | [`models.RefundPrepayment`](../../doc/models/refund-prepayment.md) | Required | - | - -## Example (as JSON) - -```json -{ - "refund": { - "amount_in_cents": 132, - "amount": { - "key1": "val1", - "key2": "val2" - }, - "memo": "memo2", - "external": false - } -} -``` - + +# Refund Prepayment Request + +## Structure + +`RefundPrepaymentRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Refund` | [`models.RefundPrepayment`](../../doc/models/refund-prepayment.md) | Required | - | + +## Example (as JSON) + +```json +{ + "refund": { + "amount_in_cents": 132, + "amount": "String1", + "memo": "memo2", + "external": false + } +} +``` + diff --git a/doc/models/refund-prepayment.md b/doc/models/refund-prepayment.md index 42b300ef..918fde6b 100644 --- a/doc/models/refund-prepayment.md +++ b/doc/models/refund-prepayment.md @@ -1,30 +1,27 @@ - -# Refund Prepayment - -## Structure - -`RefundPrepayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `AmountInCents` | `int64` | Required | `amount` is not required if you pass `amount_in_cents`. | -| `Amount` | `interface{}` | Required | `amount_in_cents` is not required if you pass `amount`. | -| `Memo` | `string` | Required | **Constraints**: *Minimum Length*: `1` | -| `External` | `*bool` | Optional | Specify the type of refund you wish to initiate. When the prepayment is external, the `external` flag is optional. But if the prepayment was made through a payment profile, the `external` flag is required. | - -## Example (as JSON) - -```json -{ - "amount_in_cents": 110, - "amount": { - "key1": "val1", - "key2": "val2" - }, - "memo": "memo4", - "external": false -} -``` - + +# Refund Prepayment + +## Structure + +`RefundPrepayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `AmountInCents` | `int64` | Required | `amount` is not required if you pass `amount_in_cents`. | +| `Amount` | [`models.RefundPrepaymentAmount`](../../doc/models/containers/refund-prepayment-amount.md) | Required | This is a container for one-of cases. | +| `Memo` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `External` | `*bool` | Optional | Specify the type of refund you wish to initiate. When the prepayment is external, the `external` flag is optional. But if the prepayment was made through a payment profile, the `external` flag is required. | + +## Example (as JSON) + +```json +{ + "amount_in_cents": 110, + "amount": "String3", + "memo": "memo4", + "external": false +} +``` + diff --git a/doc/models/refund-success.md b/doc/models/refund-success.md new file mode 100644 index 00000000..8703318b --- /dev/null +++ b/doc/models/refund-success.md @@ -0,0 +1,25 @@ + +# Refund Success + +## Structure + +`RefundSuccess` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `RefundId` | `int` | Required | - | +| `GatewayTransactionId` | `int` | Required | - | +| `ProductId` | `int` | Required | - | + +## Example (as JSON) + +```json +{ + "refund_id": 12, + "gateway_transaction_id": 182, + "product_id": 168 +} +``` + diff --git a/doc/models/refund.md b/doc/models/refund.md index b5f49712..bdbb0928 100644 --- a/doc/models/refund.md +++ b/doc/models/refund.md @@ -1,31 +1,31 @@ - -# Refund - -## Structure - -`Refund` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Amount` | `*string` | Optional | The amount to be refunded in decimal format as a string. Example: "10.50". Must not exceed the remaining refundable balance of the payment. | -| `Memo` | `*string` | Optional | A description that will be attached to the refund | -| `PaymentId` | `*int` | Optional | The ID of the payment to be refunded | -| `External` | `*bool` | Optional | Flag that marks refund as external (no money is returned to the customer). Defaults to `false`. | -| `ApplyCredit` | `*bool` | Optional | If set to true, creates credit and applies it to an invoice. Defaults to `false`. | -| `VoidInvoice` | `*bool` | Optional | If `apply_credit` set to false and refunding full amount, if `void_invoice` set to true, invoice will be voided after refund. Defaults to `false`. | -| `SegmentUids` | `*interface{}` | Optional | An array of segment uids to refund or the string 'all' to indicate that all segments should be refunded | - -## Example (as JSON) - -```json -{ - "amount": "amount8", - "memo": "memo0", - "payment_id": 130, - "external": false, - "apply_credit": false -} -``` - + +# Refund + +## Structure + +`Refund` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Amount` | `*string` | Optional | The amount to be refunded in decimal format as a string. Example: "10.50". Must not exceed the remaining refundable balance of the payment. | +| `Memo` | `*string` | Optional | A description that will be attached to the refund | +| `PaymentId` | `*int` | Optional | The ID of the payment to be refunded | +| `External` | `*bool` | Optional | Flag that marks refund as external (no money is returned to the customer). Defaults to `false`. | +| `ApplyCredit` | `*bool` | Optional | If set to true, creates credit and applies it to an invoice. Defaults to `false`. | +| `VoidInvoice` | `*bool` | Optional | If `apply_credit` set to false and refunding full amount, if `void_invoice` set to true, invoice will be voided after refund. Defaults to `false`. | +| `SegmentUids` | [`*models.RefundSegmentUids`](../../doc/models/containers/refund-segment-uids.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "amount": "amount8", + "memo": "memo0", + "payment_id": 130, + "external": false, + "apply_credit": false +} +``` + diff --git a/doc/models/remove-payment-event-data.md b/doc/models/remove-payment-event-data.md new file mode 100644 index 00000000..7a100fb0 --- /dev/null +++ b/doc/models/remove-payment-event-data.md @@ -0,0 +1,37 @@ + +# Remove Payment Event Data + +Example schema for an `remove_payment` event + +## Structure + +`RemovePaymentEventData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TransactionId` | `int` | Required | Transaction ID of the original payment that was removed | +| `Memo` | `string` | Required | Memo of the original payment | +| `OriginalAmount` | `*string` | Optional | Full amount of the original payment | +| `AppliedAmount` | `string` | Required | Applied amount of the original payment | +| `TransactionTime` | `time.Time` | Required | Transaction time of the original payment, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" | +| `PaymentMethod` | [`models.InvoiceEventPayment2`](../../doc/models/containers/invoice-event-payment-2.md) | Required | A nested data structure detailing the method of payment | +| `Prepayment` | `bool` | Required | The flag that shows whether the original payment was a prepayment or not | + +## Example (as JSON) + +```json +{ + "transaction_id": 180, + "memo": "memo0", + "original_amount": "original_amount0", + "applied_amount": "applied_amount2", + "transaction_time": "2016-03-13T12:52:32.123Z", + "payment_method": { + "type": "apple_pay" + }, + "prepayment": false +} +``` + diff --git a/doc/models/renewal-preview-component.md b/doc/models/renewal-preview-component.md index 8e9a38cc..285c68a9 100644 --- a/doc/models/renewal-preview-component.md +++ b/doc/models/renewal-preview-component.md @@ -1,31 +1,25 @@ - -# Renewal Preview Component - -## Structure - -`RenewalPreviewComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ComponentId` | `*interface{}` | Optional | Either the component's Chargify id or its handle prefixed with `handle:` | -| `Quantity` | `*int` | Optional | The quantity for which you wish to preview billing. This is useful if you want to preview a predicted, higher usage value than is currently present on the subscription.

This quantity represents:

- Whether or not an on/off component is enabled - use 0 for disabled or 1 for enabled
- The desired allocated_quantity for a quantity-based component
- The desired unit_balance for a metered component
- The desired metric quantity for an events-based component | -| `PricePointId` | `*interface{}` | Optional | Either the component price point's Chargify id or its handle prefixed with `handle:` | - -## Example (as JSON) - -```json -{ - "component_id": { - "key1": "val1", - "key2": "val2" - }, - "quantity": 174, - "price_point_id": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Renewal Preview Component + +## Structure + +`RenewalPreviewComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ComponentId` | [`*models.RenewalPreviewComponentComponentId`](../../doc/models/containers/renewal-preview-component-component-id.md) | Optional | This is a container for one-of cases. | +| `Quantity` | `*int` | Optional | The quantity for which you wish to preview billing. This is useful if you want to preview a predicted, higher usage value than is currently present on the subscription.

This quantity represents:

- Whether or not an on/off component is enabled - use 0 for disabled or 1 for enabled
- The desired allocated_quantity for a quantity-based component
- The desired unit_balance for a metered component
- The desired metric quantity for an events-based component | +| `PricePointId` | [`*models.RenewalPreviewComponentPricePointId`](../../doc/models/containers/renewal-preview-component-price-point-id.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "component_id": "String7", + "quantity": 174, + "price_point_id": "String1" +} +``` + diff --git a/doc/models/renewal-preview-line-item.md b/doc/models/renewal-preview-line-item.md index ab1316c5..34bd5106 100644 --- a/doc/models/renewal-preview-line-item.md +++ b/doc/models/renewal-preview-line-item.md @@ -1,38 +1,38 @@ - -# Renewal Preview Line Item - -## Structure - -`RenewalPreviewLineItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TransactionType` | [`*models.LineItemTransactionType`](../../doc/models/line-item-transaction-type.md) | Optional | A handle for the line item transaction type | -| `Kind` | [`*models.LineItemKind`](../../doc/models/line-item-kind.md) | Optional | A handle for the line item kind | -| `AmountInCents` | `*int64` | Optional | - | -| `Memo` | `*string` | Optional | - | -| `DiscountAmountInCents` | `*int64` | Optional | - | -| `TaxableAmountInCents` | `*int64` | Optional | - | -| `ProductId` | `*int` | Optional | - | -| `ProductName` | `*string` | Optional | - | -| `ComponentId` | `*int` | Optional | - | -| `ComponentHandle` | `*string` | Optional | - | -| `ComponentName` | `*string` | Optional | - | -| `ProductHandle` | `*string` | Optional | - | -| `PeriodRangeStart` | `*string` | Optional | - | -| `PeriodRangeEnd` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "transaction_type": "charge", - "kind": "prepaid_usage_component", - "amount_in_cents": 154, - "memo": "memo0", - "discount_amount_in_cents": 214 -} -``` - + +# Renewal Preview Line Item + +## Structure + +`RenewalPreviewLineItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TransactionType` | [`*models.LineItemTransactionType`](../../doc/models/line-item-transaction-type.md) | Optional | A handle for the line item transaction type | +| `Kind` | [`*models.LineItemKind`](../../doc/models/line-item-kind.md) | Optional | A handle for the line item kind | +| `AmountInCents` | `*int64` | Optional | - | +| `Memo` | `*string` | Optional | - | +| `DiscountAmountInCents` | `*int64` | Optional | - | +| `TaxableAmountInCents` | `*int64` | Optional | - | +| `ProductId` | `*int` | Optional | - | +| `ProductName` | `*string` | Optional | - | +| `ComponentId` | `*int` | Optional | - | +| `ComponentHandle` | `*string` | Optional | - | +| `ComponentName` | `*string` | Optional | - | +| `ProductHandle` | `*string` | Optional | - | +| `PeriodRangeStart` | `*string` | Optional | - | +| `PeriodRangeEnd` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "transaction_type": "charge", + "kind": "prepaid_usage_component", + "amount_in_cents": 154, + "memo": "memo0", + "discount_amount_in_cents": 214 +} +``` + diff --git a/doc/models/renewal-preview-request.md b/doc/models/renewal-preview-request.md index 6f4defca..a45cd9ad 100644 --- a/doc/models/renewal-preview-request.md +++ b/doc/models/renewal-preview-request.md @@ -1,55 +1,37 @@ - -# Renewal Preview Request - -## Structure - -`RenewalPreviewRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Components` | [`[]models.RenewalPreviewComponent`](../../doc/models/renewal-preview-component.md) | Optional | An optional array of component definitions to preview. Providing any component definitions here will override the actual components on the subscription (and their quantities), and the billing preview will contain only these components (in addition to any product base fees). | - -## Example (as JSON) - -```json -{ - "components": [ - { - "component_id": { - "key1": "val1", - "key2": "val2" - }, - "quantity": 210, - "price_point_id": { - "key1": "val1", - "key2": "val2" - } - }, - { - "component_id": { - "key1": "val1", - "key2": "val2" - }, - "quantity": 210, - "price_point_id": { - "key1": "val1", - "key2": "val2" - } - }, - { - "component_id": { - "key1": "val1", - "key2": "val2" - }, - "quantity": 210, - "price_point_id": { - "key1": "val1", - "key2": "val2" - } - } - ] -} -``` - + +# Renewal Preview Request + +## Structure + +`RenewalPreviewRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Components` | [`[]models.RenewalPreviewComponent`](../../doc/models/renewal-preview-component.md) | Optional | An optional array of component definitions to preview. Providing any component definitions here will override the actual components on the subscription (and their quantities), and the billing preview will contain only these components (in addition to any product base fees). | + +## Example (as JSON) + +```json +{ + "components": [ + { + "component_id": "String5", + "quantity": 210, + "price_point_id": "String3" + }, + { + "component_id": "String5", + "quantity": 210, + "price_point_id": "String3" + }, + { + "component_id": "String5", + "quantity": 210, + "price_point_id": "String3" + } + ] +} +``` + diff --git a/doc/models/renewal-preview-response.md b/doc/models/renewal-preview-response.md index f49ac2b4..561abadf 100644 --- a/doc/models/renewal-preview-response.md +++ b/doc/models/renewal-preview-response.md @@ -1,27 +1,27 @@ - -# Renewal Preview Response - -## Structure - -`RenewalPreviewResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `RenewalPreview` | [`models.RenewalPreview`](../../doc/models/renewal-preview.md) | Required | - | - -## Example (as JSON) - -```json -{ - "renewal_preview": { - "next_assessment_at": "2016-03-13T12:52:32.123Z", - "subtotal_in_cents": 132, - "total_tax_in_cents": 0, - "total_discount_in_cents": 250, - "total_in_cents": 20 - } -} -``` - + +# Renewal Preview Response + +## Structure + +`RenewalPreviewResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `RenewalPreview` | [`models.RenewalPreview`](../../doc/models/renewal-preview.md) | Required | - | + +## Example (as JSON) + +```json +{ + "renewal_preview": { + "next_assessment_at": "2016-03-13T12:52:32.123Z", + "subtotal_in_cents": 132, + "total_tax_in_cents": 0, + "total_discount_in_cents": 250, + "total_in_cents": 20 + } +} +``` + diff --git a/doc/models/renewal-preview.md b/doc/models/renewal-preview.md index 62ac1fc5..d5371c29 100644 --- a/doc/models/renewal-preview.md +++ b/doc/models/renewal-preview.md @@ -1,33 +1,33 @@ - -# Renewal Preview - -## Structure - -`RenewalPreview` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `NextAssessmentAt` | `*time.Time` | Optional | The timestamp for the subscription’s next renewal | -| `SubtotalInCents` | `*int64` | Optional | An integer representing the amount of the total pre-tax, pre-discount charges that will be assessed at the next renewal | -| `TotalTaxInCents` | `*int64` | Optional | An integer representing the total tax charges that will be assessed at the next renewal | -| `TotalDiscountInCents` | `*int64` | Optional | An integer representing the amount of the coupon discounts that will be applied to the next renewal | -| `TotalInCents` | `*int64` | Optional | An integer representing the total amount owed, less any discounts, that will be assessed at the next renewal | -| `ExistingBalanceInCents` | `*int64` | Optional | An integer representing the amount of the subscription’s current balance | -| `TotalAmountDueInCents` | `*int64` | Optional | An integer representing the existing_balance_in_cents plus the total_in_cents | -| `UncalculatedTaxes` | `*bool` | Optional | A boolean indicating whether or not additional taxes will be calculated at the time of renewal. This will be true if you are using Avalara and the address of the subscription is in one of your defined taxable regions. | -| `LineItems` | [`[]models.RenewalPreviewLineItem`](../../doc/models/renewal-preview-line-item.md) | Optional | An array of objects representing the individual transactions that will be created at the next renewal | - -## Example (as JSON) - -```json -{ - "next_assessment_at": "2016-03-13T12:52:32.123Z", - "subtotal_in_cents": 160, - "total_tax_in_cents": 28, - "total_discount_in_cents": 34, - "total_in_cents": 48 -} -``` - + +# Renewal Preview + +## Structure + +`RenewalPreview` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `NextAssessmentAt` | `*time.Time` | Optional | The timestamp for the subscription’s next renewal | +| `SubtotalInCents` | `*int64` | Optional | An integer representing the amount of the total pre-tax, pre-discount charges that will be assessed at the next renewal | +| `TotalTaxInCents` | `*int64` | Optional | An integer representing the total tax charges that will be assessed at the next renewal | +| `TotalDiscountInCents` | `*int64` | Optional | An integer representing the amount of the coupon discounts that will be applied to the next renewal | +| `TotalInCents` | `*int64` | Optional | An integer representing the total amount owed, less any discounts, that will be assessed at the next renewal | +| `ExistingBalanceInCents` | `*int64` | Optional | An integer representing the amount of the subscription’s current balance | +| `TotalAmountDueInCents` | `*int64` | Optional | An integer representing the existing_balance_in_cents plus the total_in_cents | +| `UncalculatedTaxes` | `*bool` | Optional | A boolean indicating whether or not additional taxes will be calculated at the time of renewal. This will be true if you are using Avalara and the address of the subscription is in one of your defined taxable regions. | +| `LineItems` | [`[]models.RenewalPreviewLineItem`](../../doc/models/renewal-preview-line-item.md) | Optional | An array of objects representing the individual transactions that will be created at the next renewal | + +## Example (as JSON) + +```json +{ + "next_assessment_at": "2016-03-13T12:52:32.123Z", + "subtotal_in_cents": 160, + "total_tax_in_cents": 28, + "total_discount_in_cents": 34, + "total_in_cents": 48 +} +``` + diff --git a/doc/models/replay-webhooks-request.md b/doc/models/replay-webhooks-request.md index f5f95f60..6160901a 100644 --- a/doc/models/replay-webhooks-request.md +++ b/doc/models/replay-webhooks-request.md @@ -1,23 +1,23 @@ - -# Replay Webhooks Request - -## Structure - -`ReplayWebhooksRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Ids` | `[]int64` | Required | - | - -## Example (as JSON) - -```json -{ - "ids": [ - 15 - ] -} -``` - + +# Replay Webhooks Request + +## Structure + +`ReplayWebhooksRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Ids` | `[]int64` | Required | - | + +## Example (as JSON) + +```json +{ + "ids": [ + 15 + ] +} +``` + diff --git a/doc/models/replay-webhooks-response.md b/doc/models/replay-webhooks-response.md index 42545a27..e3759052 100644 --- a/doc/models/replay-webhooks-response.md +++ b/doc/models/replay-webhooks-response.md @@ -1,21 +1,21 @@ - -# Replay Webhooks Response - -## Structure - -`ReplayWebhooksResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Status` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "status": "status4" -} -``` - + +# Replay Webhooks Response + +## Structure + +`ReplayWebhooksResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Status` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "status": "status4" +} +``` + diff --git a/doc/models/resent-invitation.md b/doc/models/resent-invitation.md index 7433700a..c768ff0b 100644 --- a/doc/models/resent-invitation.md +++ b/doc/models/resent-invitation.md @@ -1,27 +1,27 @@ - -# Resent Invitation - -## Structure - -`ResentInvitation` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `LastSentAt` | `*string` | Optional | - | -| `LastAcceptedAt` | `*string` | Optional | - | -| `SendInviteLinkText` | `*string` | Optional | - | -| `UninvitedCount` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "last_sent_at": "last_sent_at8", - "last_accepted_at": "last_accepted_at8", - "send_invite_link_text": "send_invite_link_text6", - "uninvited_count": 6 -} -``` - + +# Resent Invitation + +## Structure + +`ResentInvitation` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `LastSentAt` | `*string` | Optional | - | +| `LastAcceptedAt` | `*string` | Optional | - | +| `SendInviteLinkText` | `*string` | Optional | - | +| `UninvitedCount` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "last_sent_at": "last_sent_at8", + "last_accepted_at": "last_accepted_at8", + "send_invite_link_text": "send_invite_link_text6", + "uninvited_count": 6 +} +``` + diff --git a/doc/models/resource-type.md b/doc/models/resource-type.md index d71eb927..1490b923 100644 --- a/doc/models/resource-type.md +++ b/doc/models/resource-type.md @@ -1,14 +1,14 @@ - -# Resource Type - -## Enumeration - -`ResourceType` - -## Fields - -| Name | -| --- | -| `SUBSCRIPTIONS` | -| `CUSTOMERS` | - + +# Resource Type + +## Enumeration + +`ResourceType` + +## Fields + +| Name | +| --- | +| `SUBSCRIPTIONS` | +| `CUSTOMERS` | + diff --git a/doc/models/restriction-type.md b/doc/models/restriction-type.md index 0d932a60..816172f6 100644 --- a/doc/models/restriction-type.md +++ b/doc/models/restriction-type.md @@ -1,14 +1,14 @@ - -# Restriction Type - -## Enumeration - -`RestrictionType` - -## Fields - -| Name | -| --- | -| `COMPONENT` | -| `PRODUCT` | - + +# Restriction Type + +## Enumeration + +`RestrictionType` + +## Fields + +| Name | +| --- | +| `COMPONENT` | +| `PRODUCT` | + diff --git a/doc/models/resume-options.md b/doc/models/resume-options.md new file mode 100644 index 00000000..5939a388 --- /dev/null +++ b/doc/models/resume-options.md @@ -0,0 +1,23 @@ + +# Resume Options + +## Structure + +`ResumeOptions` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `RequireResume` | `*bool` | Optional | Chargify will only attempt to resume the subscription's billing period. If not resumable, the subscription will be left in it's current state. | +| `ForgiveBalance` | `*bool` | Optional | Indicates whether or not Chargify should clear the subscription's existing balance before attempting to resume the subscription. If subscription cannot be resumed, the balance will remain as it was before the attempt to resume was made. | + +## Example (as JSON) + +```json +{ + "require_resume": false, + "forgive_balance": false +} +``` + diff --git a/doc/models/resumption-charge.md b/doc/models/resumption-charge.md index c4157754..799f3d35 100644 --- a/doc/models/resumption-charge.md +++ b/doc/models/resumption-charge.md @@ -1,17 +1,17 @@ - -# Resumption Charge - -(For calendar billing subscriptions only) The way that the resumed subscription's charge should be handled - -## Enumeration - -`ResumptionCharge` - -## Fields - -| Name | -| --- | -| `PRORATED` | -| `IMMEDIATE` | -| `DELAYED` | - + +# Resumption Charge + +(For calendar billing subscriptions only) The way that the resumed subscription's charge should be handled + +## Enumeration + +`ResumptionCharge` + +## Fields + +| Name | +| --- | +| `PRORATED` | +| `IMMEDIATE` | +| `DELAYED` | + diff --git a/doc/models/revoked-invitation.md b/doc/models/revoked-invitation.md index 786547fe..1d063e4d 100644 --- a/doc/models/revoked-invitation.md +++ b/doc/models/revoked-invitation.md @@ -1,25 +1,25 @@ - -# Revoked Invitation - -## Structure - -`RevokedInvitation` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `LastSentAt` | `*string` | Optional | - | -| `LastAcceptedAt` | `*string` | Optional | - | -| `UninvitedCount` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "last_sent_at": "last_sent_at2", - "last_accepted_at": "last_accepted_at2", - "uninvited_count": 226 -} -``` - + +# Revoked Invitation + +## Structure + +`RevokedInvitation` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `LastSentAt` | `*string` | Optional | - | +| `LastAcceptedAt` | `*string` | Optional | - | +| `UninvitedCount` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "last_sent_at": "last_sent_at2", + "last_accepted_at": "last_accepted_at2", + "uninvited_count": 226 +} +``` + diff --git a/doc/models/sale-rep-item-mrr.md b/doc/models/sale-rep-item-mrr.md index cb0c39cb..3a10551b 100644 --- a/doc/models/sale-rep-item-mrr.md +++ b/doc/models/sale-rep-item-mrr.md @@ -1,25 +1,25 @@ - -# Sale Rep Item Mrr - -## Structure - -`SaleRepItemMrr` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Mrr` | `*string` | Optional | - | -| `Usage` | `*string` | Optional | - | -| `Recurring` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "mrr": "mrr2", - "usage": "usage0", - "recurring": "recurring4" -} -``` - + +# Sale Rep Item Mrr + +## Structure + +`SaleRepItemMrr` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Mrr` | `*string` | Optional | - | +| `Usage` | `*string` | Optional | - | +| `Recurring` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "mrr": "mrr2", + "usage": "usage0", + "recurring": "recurring4" +} +``` + diff --git a/doc/models/sale-rep-settings.md b/doc/models/sale-rep-settings.md index 60adadc5..1a0d3c23 100644 --- a/doc/models/sale-rep-settings.md +++ b/doc/models/sale-rep-settings.md @@ -1,31 +1,31 @@ - -# Sale Rep Settings - -## Structure - -`SaleRepSettings` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CustomerName` | `*string` | Optional | - | -| `SubscriptionId` | `*int` | Optional | - | -| `SiteLink` | `*string` | Optional | - | -| `SiteName` | `*string` | Optional | - | -| `SubscriptionMrr` | `*string` | Optional | - | -| `SalesRepId` | `*int` | Optional | - | -| `SalesRepName` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "customer_name": "customer_name8", - "subscription_id": 200, - "site_link": "site_link4", - "site_name": "site_name8", - "subscription_mrr": "subscription_mrr6" -} -``` - + +# Sale Rep Settings + +## Structure + +`SaleRepSettings` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CustomerName` | `*string` | Optional | - | +| `SubscriptionId` | `*int` | Optional | - | +| `SiteLink` | `*string` | Optional | - | +| `SiteName` | `*string` | Optional | - | +| `SubscriptionMrr` | `*string` | Optional | - | +| `SalesRepId` | `*int` | Optional | - | +| `SalesRepName` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "customer_name": "customer_name8", + "subscription_id": 200, + "site_link": "site_link4", + "site_name": "site_name8", + "subscription_mrr": "subscription_mrr6" +} +``` + diff --git a/doc/models/sale-rep-subscription.md b/doc/models/sale-rep-subscription.md index bb29bedd..5eb4ab1f 100644 --- a/doc/models/sale-rep-subscription.md +++ b/doc/models/sale-rep-subscription.md @@ -1,34 +1,34 @@ - -# Sale Rep Subscription - -## Structure - -`SaleRepSubscription` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `SiteName` | `*string` | Optional | - | -| `SubscriptionUrl` | `*string` | Optional | - | -| `CustomerName` | `*string` | Optional | - | -| `CreatedAt` | `*string` | Optional | - | -| `Mrr` | `*string` | Optional | - | -| `Usage` | `*string` | Optional | - | -| `Recurring` | `*string` | Optional | - | -| `LastPayment` | `*string` | Optional | - | -| `ChurnDate` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 18, - "site_name": "site_name2", - "subscription_url": "subscription_url6", - "customer_name": "customer_name2", - "created_at": "created_at8" -} -``` - + +# Sale Rep Subscription + +## Structure + +`SaleRepSubscription` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `SiteName` | `*string` | Optional | - | +| `SubscriptionUrl` | `*string` | Optional | - | +| `CustomerName` | `*string` | Optional | - | +| `CreatedAt` | `*string` | Optional | - | +| `Mrr` | `*string` | Optional | - | +| `Usage` | `*string` | Optional | - | +| `Recurring` | `*string` | Optional | - | +| `LastPayment` | `*string` | Optional | - | +| `ChurnDate` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 18, + "site_name": "site_name2", + "subscription_url": "subscription_url6", + "customer_name": "customer_name2", + "created_at": "created_at8" +} +``` + diff --git a/doc/models/sale-rep.md b/doc/models/sale-rep.md index 8c5efacb..0a307eec 100644 --- a/doc/models/sale-rep.md +++ b/doc/models/sale-rep.md @@ -1,44 +1,44 @@ - -# Sale Rep - -## Structure - -`SaleRep` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `FullName` | `*string` | Optional | - | -| `SubscriptionsCount` | `*int` | Optional | - | -| `TestMode` | `*bool` | Optional | - | -| `Subscriptions` | [`[]models.SaleRepSubscription`](../../doc/models/sale-rep-subscription.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 18, - "full_name": "full_name0", - "subscriptions_count": 162, - "test_mode": false, - "subscriptions": [ - { - "id": 202, - "site_name": "site_name8", - "subscription_url": "subscription_url2", - "customer_name": "customer_name8", - "created_at": "created_at4" - }, - { - "id": 202, - "site_name": "site_name8", - "subscription_url": "subscription_url2", - "customer_name": "customer_name8", - "created_at": "created_at4" - } - ] -} -``` - + +# Sale Rep + +## Structure + +`SaleRep` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `FullName` | `*string` | Optional | - | +| `SubscriptionsCount` | `*int` | Optional | - | +| `TestMode` | `*bool` | Optional | - | +| `Subscriptions` | [`[]models.SaleRepSubscription`](../../doc/models/sale-rep-subscription.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 18, + "full_name": "full_name0", + "subscriptions_count": 162, + "test_mode": false, + "subscriptions": [ + { + "id": 202, + "site_name": "site_name8", + "subscription_url": "subscription_url2", + "customer_name": "customer_name8", + "created_at": "created_at4" + }, + { + "id": 202, + "site_name": "site_name8", + "subscription_url": "subscription_url2", + "customer_name": "customer_name8", + "created_at": "created_at4" + } + ] +} +``` + diff --git a/doc/models/segment-price.md b/doc/models/segment-price.md index b9812acc..d89ad4d7 100644 --- a/doc/models/segment-price.md +++ b/doc/models/segment-price.md @@ -1,32 +1,32 @@ - -# Segment Price - -## Structure - -`SegmentPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `ComponentId` | `*int` | Optional | - | -| `StartingQuantity` | `*int` | Optional | - | -| `EndingQuantity` | `Optional[int]` | Optional | - | -| `UnitPrice` | `*string` | Optional | - | -| `PricePointId` | `*int` | Optional | - | -| `FormattedUnitPrice` | `*string` | Optional | - | -| `SegmentId` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 220, - "component_id": 74, - "starting_quantity": 118, - "ending_quantity": 92, - "unit_price": "unit_price0" -} -``` - + +# Segment Price + +## Structure + +`SegmentPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `ComponentId` | `*int` | Optional | - | +| `StartingQuantity` | `*int` | Optional | - | +| `EndingQuantity` | `models.Optional[int]` | Optional | - | +| `UnitPrice` | `*string` | Optional | - | +| `PricePointId` | `*int` | Optional | - | +| `FormattedUnitPrice` | `*string` | Optional | - | +| `SegmentId` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 220, + "component_id": 74, + "starting_quantity": 118, + "ending_quantity": 92, + "unit_price": "unit_price0" +} +``` + diff --git a/doc/models/segment-response.md b/doc/models/segment-response.md index d4d2e5cc..c5282e59 100644 --- a/doc/models/segment-response.md +++ b/doc/models/segment-response.md @@ -1,27 +1,27 @@ - -# Segment Response - -## Structure - -`SegmentResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Segment` | [`*models.Segment`](../../doc/models/segment.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "segment": { - "id": 118, - "component_id": 228, - "price_point_id": 4, - "event_based_billing_metric_id": 56, - "pricing_scheme": "stairstep" - } -} -``` - + +# Segment Response + +## Structure + +`SegmentResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Segment` | [`*models.Segment`](../../doc/models/segment.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "segment": { + "id": 118, + "component_id": 228, + "price_point_id": 4, + "event_based_billing_metric_id": 56, + "pricing_scheme": "stairstep" + } +} +``` + diff --git a/doc/models/segment.md b/doc/models/segment.md index b70df3a8..49a02987 100644 --- a/doc/models/segment.md +++ b/doc/models/segment.md @@ -1,36 +1,36 @@ - -# Segment - -## Structure - -`Segment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `ComponentId` | `*int` | Optional | - | -| `PricePointId` | `*int` | Optional | - | -| `EventBasedBillingMetricId` | `*int` | Optional | - | -| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `SegmentProperty1Value` | `*interface{}` | Optional | - | -| `SegmentProperty2Value` | `*interface{}` | Optional | - | -| `SegmentProperty3Value` | `*interface{}` | Optional | - | -| `SegmentProperty4Value` | `*interface{}` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `UpdatedAt` | `*time.Time` | Optional | - | -| `Prices` | [`[]models.SegmentPrice`](../../doc/models/segment-price.md) | Optional | **Constraints**: *Minimum Items*: `1` | - -## Example (as JSON) - -```json -{ - "id": 6, - "component_id": 116, - "price_point_id": 140, - "event_based_billing_metric_id": 200, - "pricing_scheme": "stairstep" -} -``` - + +# Segment + +## Structure + +`Segment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `ComponentId` | `*int` | Optional | - | +| `PricePointId` | `*int` | Optional | - | +| `EventBasedBillingMetricId` | `*int` | Optional | - | +| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `SegmentProperty1Value` | [`*models.SegmentSegmentProperty1Value`](../../doc/models/containers/segment-segment-property-1-value.md) | Optional | This is a container for one-of cases. | +| `SegmentProperty2Value` | [`*models.SegmentSegmentProperty2Value`](../../doc/models/containers/segment-segment-property-2-value.md) | Optional | This is a container for one-of cases. | +| `SegmentProperty3Value` | [`*models.SegmentSegmentProperty3Value`](../../doc/models/containers/segment-segment-property-3-value.md) | Optional | This is a container for one-of cases. | +| `SegmentProperty4Value` | [`*models.SegmentSegmentProperty4Value`](../../doc/models/containers/segment-segment-property-4-value.md) | Optional | This is a container for one-of cases. | +| `CreatedAt` | `*time.Time` | Optional | - | +| `UpdatedAt` | `*time.Time` | Optional | - | +| `Prices` | [`[]models.SegmentPrice`](../../doc/models/segment-price.md) | Optional | **Constraints**: *Minimum Items*: `1` | + +## Example (as JSON) + +```json +{ + "id": 6, + "component_id": 116, + "price_point_id": 140, + "event_based_billing_metric_id": 200, + "pricing_scheme": "stairstep" +} +``` + diff --git a/doc/models/seller.md b/doc/models/seller.md index 341fa953..2cfc1298 100644 --- a/doc/models/seller.md +++ b/doc/models/seller.md @@ -1,33 +1,33 @@ - -# Seller - -## Structure - -`Seller` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `*string` | Optional | - | -| `Address` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | - | -| `Phone` | `*string` | Optional | - | -| `LogoUrl` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "name": "name6", - "address": { - "street": "street6", - "line2": "line20", - "city": "city6", - "state": "state2", - "zip": "zip0" - }, - "phone": "phone6", - "logo_url": "logo_url4" -} -``` - + +# Seller + +## Structure + +`Seller` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `*string` | Optional | - | +| `Address` | [`*models.InvoiceAddress`](../../doc/models/invoice-address.md) | Optional | - | +| `Phone` | `*string` | Optional | - | +| `LogoUrl` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name6", + "address": { + "street": "street6", + "line2": "line20", + "city": "city6", + "state": "state2", + "zip": "zip0" + }, + "phone": "phone6", + "logo_url": "logo_url4" +} +``` + diff --git a/doc/models/send-invoice-request.md b/doc/models/send-invoice-request.md index 29d0e584..1e7659d5 100644 --- a/doc/models/send-invoice-request.md +++ b/doc/models/send-invoice-request.md @@ -1,33 +1,33 @@ - -# Send Invoice Request - -## Structure - -`SendInvoiceRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `RecipientEmails` | `[]string` | Optional | **Constraints**: *Maximum Items*: `5` | -| `CcRecipientEmails` | `[]string` | Optional | **Constraints**: *Maximum Items*: `5` | -| `BccRecipientEmails` | `[]string` | Optional | **Constraints**: *Maximum Items*: `5` | - -## Example (as JSON) - -```json -{ - "recipient_emails": [ - "recipient_emails3", - "recipient_emails4" - ], - "cc_recipient_emails": [ - "cc_recipient_emails6", - "cc_recipient_emails5" - ], - "bcc_recipient_emails": [ - "bcc_recipient_emails6" - ] -} -``` - + +# Send Invoice Request + +## Structure + +`SendInvoiceRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `RecipientEmails` | `[]string` | Optional | **Constraints**: *Maximum Items*: `5` | +| `CcRecipientEmails` | `[]string` | Optional | **Constraints**: *Maximum Items*: `5` | +| `BccRecipientEmails` | `[]string` | Optional | **Constraints**: *Maximum Items*: `5` | + +## Example (as JSON) + +```json +{ + "recipient_emails": [ + "recipient_emails3", + "recipient_emails4" + ], + "cc_recipient_emails": [ + "cc_recipient_emails6", + "cc_recipient_emails5" + ], + "bcc_recipient_emails": [ + "bcc_recipient_emails6" + ] +} +``` + diff --git a/doc/models/service-credit-response.md b/doc/models/service-credit-response.md index 22efe0d7..1e4af594 100644 --- a/doc/models/service-credit-response.md +++ b/doc/models/service-credit-response.md @@ -1,27 +1,27 @@ - -# Service Credit Response - -## Structure - -`ServiceCreditResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ServiceCredit` | [`models.ServiceCredit`](../../doc/models/service-credit.md) | Required | - | - -## Example (as JSON) - -```json -{ - "service_credit": { - "id": 38, - "amount_in_cents": 124, - "ending_balance_in_cents": 164, - "entry_type": "Credit", - "memo": "memo0" - } -} -``` - + +# Service Credit Response + +## Structure + +`ServiceCreditResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ServiceCredit` | [`models.ServiceCredit`](../../doc/models/service-credit.md) | Required | - | + +## Example (as JSON) + +```json +{ + "service_credit": { + "id": 38, + "amount_in_cents": 124, + "ending_balance_in_cents": 164, + "entry_type": "Credit", + "memo": "memo0" + } +} +``` + diff --git a/doc/models/service-credit-type.md b/doc/models/service-credit-type.md index 7514b30a..e4763845 100644 --- a/doc/models/service-credit-type.md +++ b/doc/models/service-credit-type.md @@ -1,16 +1,16 @@ - -# Service Credit Type - -The type of entry - -## Enumeration - -`ServiceCreditType` - -## Fields - -| Name | -| --- | -| `CREDIT` | -| `DEBIT` | - + +# Service Credit Type + +The type of entry + +## Enumeration + +`ServiceCreditType` + +## Fields + +| Name | +| --- | +| `CREDIT` | +| `DEBIT` | + diff --git a/doc/models/service-credit.md b/doc/models/service-credit.md index d8b5f110..e18a6778 100644 --- a/doc/models/service-credit.md +++ b/doc/models/service-credit.md @@ -1,29 +1,29 @@ - -# Service Credit - -## Structure - -`ServiceCredit` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `AmountInCents` | `*int64` | Optional | The amount in cents of the entry | -| `EndingBalanceInCents` | `*int64` | Optional | The new balance for the credit account | -| `EntryType` | [`*models.ServiceCreditType`](../../doc/models/service-credit-type.md) | Optional | The type of entry | -| `Memo` | `*string` | Optional | The memo attached to the entry | - -## Example (as JSON) - -```json -{ - "id": 216, - "amount_in_cents": 210, - "ending_balance_in_cents": 86, - "entry_type": "Credit", - "memo": "memo2" -} -``` - + +# Service Credit + +## Structure + +`ServiceCredit` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `AmountInCents` | `*int64` | Optional | The amount in cents of the entry | +| `EndingBalanceInCents` | `*int64` | Optional | The new balance for the credit account | +| `EntryType` | [`*models.ServiceCreditType`](../../doc/models/service-credit-type.md) | Optional | The type of entry | +| `Memo` | `*string` | Optional | The memo attached to the entry | + +## Example (as JSON) + +```json +{ + "id": 216, + "amount_in_cents": 210, + "ending_balance_in_cents": 86, + "entry_type": "Credit", + "memo": "memo2" +} +``` + diff --git a/doc/models/shipping-address.md b/doc/models/shipping-address.md index 643994db..d67ee75f 100644 --- a/doc/models/shipping-address.md +++ b/doc/models/shipping-address.md @@ -1,30 +1,30 @@ - -# Shipping Address - -## Structure - -`ShippingAddress` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Street` | `Optional[string]` | Optional | - | -| `Line2` | `Optional[string]` | Optional | - | -| `City` | `Optional[string]` | Optional | - | -| `State` | `Optional[string]` | Optional | - | -| `Zip` | `Optional[string]` | Optional | - | -| `Country` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "street": "street0", - "line2": "line24", - "city": "city0", - "state": "state4", - "zip": "zip6" -} -``` - + +# Shipping Address + +## Structure + +`ShippingAddress` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Street` | `models.Optional[string]` | Optional | - | +| `Line2` | `models.Optional[string]` | Optional | - | +| `City` | `models.Optional[string]` | Optional | - | +| `State` | `models.Optional[string]` | Optional | - | +| `Zip` | `models.Optional[string]` | Optional | - | +| `Country` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "street": "street0", + "line2": "line24", + "city": "city0", + "state": "state4", + "zip": "zip6" +} +``` + diff --git a/doc/models/signup-proforma-preview-response.md b/doc/models/signup-proforma-preview-response.md index 908e6215..66a7d8da 100644 --- a/doc/models/signup-proforma-preview-response.md +++ b/doc/models/signup-proforma-preview-response.md @@ -1,36 +1,36 @@ - -# Signup Proforma Preview Response - -## Structure - -`SignupProformaPreviewResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ProformaInvoicePreview` | [`models.SignupProformaPreview`](../../doc/models/signup-proforma-preview.md) | Required | - | - -## Example (as JSON) - -```json -{ - "proforma_invoice_preview": { - "current_proforma_invoice": { - "uid": "uid6", - "site_id": 72, - "customer_id": 184, - "subscription_id": 0, - "number": 132 - }, - "next_proforma_invoice": { - "uid": "uid8", - "site_id": 212, - "customer_id": 68, - "subscription_id": 140, - "number": 16 - } - } -} -``` - + +# Signup Proforma Preview Response + +## Structure + +`SignupProformaPreviewResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProformaInvoicePreview` | [`models.SignupProformaPreview`](../../doc/models/signup-proforma-preview.md) | Required | - | + +## Example (as JSON) + +```json +{ + "proforma_invoice_preview": { + "current_proforma_invoice": { + "uid": "uid6", + "site_id": 72, + "customer_id": 184, + "subscription_id": 0, + "number": 132 + }, + "next_proforma_invoice": { + "uid": "uid8", + "site_id": 212, + "customer_id": 68, + "subscription_id": 140, + "number": 16 + } + } +} +``` + diff --git a/doc/models/signup-proforma-preview.md b/doc/models/signup-proforma-preview.md index eaa66cbc..b811c7f6 100644 --- a/doc/models/signup-proforma-preview.md +++ b/doc/models/signup-proforma-preview.md @@ -1,35 +1,35 @@ - -# Signup Proforma Preview - -## Structure - -`SignupProformaPreview` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CurrentProformaInvoice` | [`*models.ProformaInvoice`](../../doc/models/proforma-invoice.md) | Optional | - | -| `NextProformaInvoice` | [`*models.ProformaInvoice`](../../doc/models/proforma-invoice.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "current_proforma_invoice": { - "uid": "uid6", - "site_id": 72, - "customer_id": 184, - "subscription_id": 0, - "number": 132 - }, - "next_proforma_invoice": { - "uid": "uid8", - "site_id": 212, - "customer_id": 68, - "subscription_id": 140, - "number": 16 - } -} -``` - + +# Signup Proforma Preview + +## Structure + +`SignupProformaPreview` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrentProformaInvoice` | [`*models.ProformaInvoice`](../../doc/models/proforma-invoice.md) | Optional | - | +| `NextProformaInvoice` | [`*models.ProformaInvoice`](../../doc/models/proforma-invoice.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "current_proforma_invoice": { + "uid": "uid6", + "site_id": 72, + "customer_id": 184, + "subscription_id": 0, + "number": 132 + }, + "next_proforma_invoice": { + "uid": "uid8", + "site_id": 212, + "customer_id": 68, + "subscription_id": 140, + "number": 16 + } +} +``` + diff --git a/doc/models/single-error-response-exception.md b/doc/models/single-error-response-exception.md index 14353407..ce5e9aa6 100644 --- a/doc/models/single-error-response-exception.md +++ b/doc/models/single-error-response-exception.md @@ -1,21 +1,21 @@ - -# Single Error Response Exception - -## Structure - -`SingleErrorResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Error` | `string` | Required | - | - -## Example (as JSON) - -```json -{ - "error": "error2" -} -``` - + +# Single Error Response Exception + +## Structure + +`SingleErrorResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Error` | `string` | Required | - | + +## Example (as JSON) + +```json +{ + "error": "error2" +} +``` + diff --git a/doc/models/single-string-error-response-exception.md b/doc/models/single-string-error-response-exception.md index ff540311..e0725c08 100644 --- a/doc/models/single-string-error-response-exception.md +++ b/doc/models/single-string-error-response-exception.md @@ -1,21 +1,21 @@ - -# Single String Error Response Exception - -## Structure - -`SingleStringErrorResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": "errors4" -} -``` - + +# Single String Error Response Exception + +## Structure + +`SingleStringErrorResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": "errors4" +} +``` + diff --git a/doc/models/site-response.md b/doc/models/site-response.md index febe5822..8990f320 100644 --- a/doc/models/site-response.md +++ b/doc/models/site-response.md @@ -1,27 +1,27 @@ - -# Site Response - -## Structure - -`SiteResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Site` | [`models.Site`](../../doc/models/site.md) | Required | - | - -## Example (as JSON) - -```json -{ - "site": { - "id": 64, - "name": "name4", - "subdomain": "subdomain0", - "currency": "currency4", - "seller_id": 228 - } -} -``` - + +# Site Response + +## Structure + +`SiteResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Site` | [`models.Site`](../../doc/models/site.md) | Required | - | + +## Example (as JSON) + +```json +{ + "site": { + "id": 64, + "name": "name4", + "subdomain": "subdomain0", + "currency": "currency4", + "seller_id": 228 + } +} +``` + diff --git a/doc/models/site-statistics.md b/doc/models/site-statistics.md index c4bb55f5..563430f7 100644 --- a/doc/models/site-statistics.md +++ b/doc/models/site-statistics.md @@ -1,35 +1,35 @@ - -# Site Statistics - -## Structure - -`SiteStatistics` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `TotalSubscriptions` | `*int` | Optional | - | -| `SubscriptionsToday` | `*int` | Optional | - | -| `TotalRevenue` | `*string` | Optional | - | -| `RevenueToday` | `*string` | Optional | - | -| `RevenueThisMonth` | `*string` | Optional | - | -| `RevenueThisYear` | `*string` | Optional | - | -| `TotalCanceledSubscriptions` | `*int` | Optional | - | -| `TotalActiveSubscriptions` | `*int` | Optional | - | -| `TotalPastDueSubscriptions` | `*int` | Optional | - | -| `TotalUnpaidSubscriptions` | `*int` | Optional | - | -| `TotalDunningSubscriptions` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "total_subscriptions": 204, - "subscriptions_today": 134, - "total_revenue": "total_revenue6", - "revenue_today": "revenue_today4", - "revenue_this_month": "revenue_this_month4" -} -``` - + +# Site Statistics + +## Structure + +`SiteStatistics` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `TotalSubscriptions` | `*int` | Optional | - | +| `SubscriptionsToday` | `*int` | Optional | - | +| `TotalRevenue` | `*string` | Optional | - | +| `RevenueToday` | `*string` | Optional | - | +| `RevenueThisMonth` | `*string` | Optional | - | +| `RevenueThisYear` | `*string` | Optional | - | +| `TotalCanceledSubscriptions` | `*int` | Optional | - | +| `TotalActiveSubscriptions` | `*int` | Optional | - | +| `TotalPastDueSubscriptions` | `*int` | Optional | - | +| `TotalUnpaidSubscriptions` | `*int` | Optional | - | +| `TotalDunningSubscriptions` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "total_subscriptions": 204, + "subscriptions_today": 134, + "total_revenue": "total_revenue6", + "revenue_today": "revenue_today4", + "revenue_this_month": "revenue_this_month4" +} +``` + diff --git a/doc/models/site-summary.md b/doc/models/site-summary.md index 234a634e..29e52e9b 100644 --- a/doc/models/site-summary.md +++ b/doc/models/site-summary.md @@ -1,35 +1,35 @@ - -# Site Summary - -## Structure - -`SiteSummary` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SellerName` | `*string` | Optional | - | -| `SiteName` | `*string` | Optional | - | -| `SiteId` | `*int` | Optional | - | -| `SiteCurrency` | `*string` | Optional | - | -| `Stats` | [`*models.SiteStatistics`](../../doc/models/site-statistics.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "seller_name": "seller_name0", - "site_name": "site_name4", - "site_id": 218, - "site_currency": "site_currency6", - "stats": { - "total_subscriptions": 110, - "subscriptions_today": 228, - "total_revenue": "total_revenue6", - "revenue_today": "revenue_today4", - "revenue_this_month": "revenue_this_month4" - } -} -``` - + +# Site Summary + +## Structure + +`SiteSummary` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SellerName` | `*string` | Optional | - | +| `SiteName` | `*string` | Optional | - | +| `SiteId` | `*int` | Optional | - | +| `SiteCurrency` | `*string` | Optional | - | +| `Stats` | [`*models.SiteStatistics`](../../doc/models/site-statistics.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "seller_name": "seller_name0", + "site_name": "site_name4", + "site_id": 218, + "site_currency": "site_currency6", + "stats": { + "total_subscriptions": 110, + "subscriptions_today": 228, + "total_revenue": "total_revenue6", + "revenue_today": "revenue_today4", + "revenue_this_month": "revenue_this_month4" + } +} +``` + diff --git a/doc/models/site.md b/doc/models/site.md index 4e4e439a..9c4bee2a 100644 --- a/doc/models/site.md +++ b/doc/models/site.md @@ -1,40 +1,40 @@ - -# Site - -## Structure - -`Site` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Name` | `*string` | Optional | - | -| `Subdomain` | `*string` | Optional | - | -| `Currency` | `*string` | Optional | - | -| `SellerId` | `*int` | Optional | - | -| `NonPrimaryCurrencies` | `[]string` | Optional | - | -| `RelationshipInvoicingEnabled` | `*bool` | Optional | - | -| `CustomerHierarchyEnabled` | `*bool` | Optional | - | -| `WhopaysEnabled` | `*bool` | Optional | - | -| `WhopaysDefaultPayer` | `*string` | Optional | - | -| `AllocationSettings` | [`*models.AllocationSettings`](../../doc/models/allocation-settings.md) | Optional | - | -| `DefaultPaymentCollectionMethod` | `*string` | Optional | - | -| `OrganizationAddress` | [`*models.OrganizationAddress`](../../doc/models/organization-address.md) | Optional | - | -| `TaxConfiguration` | [`*models.TaxConfiguration`](../../doc/models/tax-configuration.md) | Optional | - | -| `NetTerms` | [`*models.NetTerms`](../../doc/models/net-terms.md) | Optional | - | -| `Test` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 34, - "name": "name0", - "subdomain": "subdomain4", - "currency": "currency0", - "seller_id": 198 -} -``` - + +# Site + +## Structure + +`Site` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Name` | `*string` | Optional | - | +| `Subdomain` | `*string` | Optional | - | +| `Currency` | `*string` | Optional | - | +| `SellerId` | `*int` | Optional | - | +| `NonPrimaryCurrencies` | `[]string` | Optional | - | +| `RelationshipInvoicingEnabled` | `*bool` | Optional | - | +| `CustomerHierarchyEnabled` | `*bool` | Optional | - | +| `WhopaysEnabled` | `*bool` | Optional | - | +| `WhopaysDefaultPayer` | `*string` | Optional | - | +| `AllocationSettings` | [`*models.AllocationSettings`](../../doc/models/allocation-settings.md) | Optional | - | +| `DefaultPaymentCollectionMethod` | `*string` | Optional | - | +| `OrganizationAddress` | [`*models.OrganizationAddress`](../../doc/models/organization-address.md) | Optional | - | +| `TaxConfiguration` | [`*models.TaxConfiguration`](../../doc/models/tax-configuration.md) | Optional | - | +| `NetTerms` | [`*models.NetTerms`](../../doc/models/net-terms.md) | Optional | - | +| `Test` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 34, + "name": "name0", + "subdomain": "subdomain4", + "currency": "currency0", + "seller_id": 198 +} +``` + diff --git a/doc/models/snap-day.md b/doc/models/snap-day.md new file mode 100644 index 00000000..55479f1d --- /dev/null +++ b/doc/models/snap-day.md @@ -0,0 +1,15 @@ + +# Snap Day + +Use for subscriptions with product eligible for calendar billing only. Value can be 1-28 or 'end'. + +## Enumeration + +`SnapDay` + +## Fields + +| Name | +| --- | +| `END` | + diff --git a/doc/models/sorting-direction.md b/doc/models/sorting-direction.md index ae2b3d62..547aa444 100644 --- a/doc/models/sorting-direction.md +++ b/doc/models/sorting-direction.md @@ -1,16 +1,16 @@ - -# Sorting Direction - -Used for sorting results. - -## Enumeration - -`SortingDirection` - -## Fields - -| Name | -| --- | -| `ASC` | -| `DESC` | - + +# Sorting Direction + +Used for sorting results. + +## Enumeration + +`SortingDirection` + +## Fields + +| Name | +| --- | +| `ASC` | +| `DESC` | + diff --git a/doc/models/subscription-add-coupon-error-exception.md b/doc/models/subscription-add-coupon-error-exception.md index df96f1a6..0a276360 100644 --- a/doc/models/subscription-add-coupon-error-exception.md +++ b/doc/models/subscription-add-coupon-error-exception.md @@ -1,38 +1,38 @@ - -# Subscription Add Coupon Error Exception - -## Structure - -`SubscriptionAddCouponErrorException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Codes` | `[]string` | Optional | - | -| `CouponCode` | `[]string` | Optional | - | -| `CouponCodes` | `[]string` | Optional | - | -| `Subscription` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "codes": [ - "codes6", - "codes7", - "codes8" - ], - "coupon_code": [ - "coupon_code8", - "coupon_code7" - ], - "coupon_codes": [ - "coupon_codes2" - ], - "subscription": [ - "subscription8" - ] -} -``` - + +# Subscription Add Coupon Error Exception + +## Structure + +`SubscriptionAddCouponErrorException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Codes` | `[]string` | Optional | - | +| `CouponCode` | `[]string` | Optional | - | +| `CouponCodes` | `[]string` | Optional | - | +| `Subscription` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "codes": [ + "codes6", + "codes7", + "codes8" + ], + "coupon_code": [ + "coupon_code8", + "coupon_code7" + ], + "coupon_codes": [ + "coupon_codes2" + ], + "subscription": [ + "subscription8" + ] +} +``` + diff --git a/doc/models/subscription-component-allocation-error-exception.md b/doc/models/subscription-component-allocation-error-exception.md index 653df7a9..91817c94 100644 --- a/doc/models/subscription-component-allocation-error-exception.md +++ b/doc/models/subscription-component-allocation-error-exception.md @@ -1,26 +1,26 @@ - -# Subscription Component Allocation Error Exception - -## Structure - -`SubscriptionComponentAllocationErrorException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`[]models.SubscriptionComponentAllocationErrorItem`](../../doc/models/subscription-component-allocation-error-item.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": [ - { - "kind": "kind8", - "message": "message0" - } - ] -} -``` - + +# Subscription Component Allocation Error Exception + +## Structure + +`SubscriptionComponentAllocationErrorException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`[]models.SubscriptionComponentAllocationErrorItem`](../../doc/models/subscription-component-allocation-error-item.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": [ + { + "kind": "kind8", + "message": "message0" + } + ] +} +``` + diff --git a/doc/models/subscription-component-allocation-error-item.md b/doc/models/subscription-component-allocation-error-item.md index 8deca32e..663f70cc 100644 --- a/doc/models/subscription-component-allocation-error-item.md +++ b/doc/models/subscription-component-allocation-error-item.md @@ -1,23 +1,23 @@ - -# Subscription Component Allocation Error Item - -## Structure - -`SubscriptionComponentAllocationErrorItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Kind` | `*string` | Optional | - | -| `Message` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "kind": "kind0", - "message": "message8" -} -``` - + +# Subscription Component Allocation Error Item + +## Structure + +`SubscriptionComponentAllocationErrorItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Kind` | `*string` | Optional | - | +| `Message` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "kind": "kind0", + "message": "message8" +} +``` + diff --git a/doc/models/subscription-component-response.md b/doc/models/subscription-component-response.md index 610ac904..f6116672 100644 --- a/doc/models/subscription-component-response.md +++ b/doc/models/subscription-component-response.md @@ -1,27 +1,27 @@ - -# Subscription Component Response - -## Structure - -`SubscriptionComponentResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Component` | [`*models.SubscriptionComponent`](../../doc/models/subscription-component.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "component": { - "id": 80, - "name": "name8", - "kind": "quantity_based_component", - "unit_name": "unit_name0", - "enabled": false - } -} -``` - + +# Subscription Component Response + +## Structure + +`SubscriptionComponentResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Component` | [`*models.SubscriptionComponent`](../../doc/models/subscription-component.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "component": { + "id": 80, + "name": "name8", + "kind": "quantity_based_component", + "unit_name": "unit_name0", + "enabled": false + } +} +``` + diff --git a/doc/models/subscription-component-subscription.md b/doc/models/subscription-component-subscription.md index c44a51f3..aae7b90c 100644 --- a/doc/models/subscription-component-subscription.md +++ b/doc/models/subscription-component-subscription.md @@ -1,25 +1,25 @@ - -# Subscription Component Subscription - -An optional object, will be returned if provided `include=subscription` query param. - -## Structure - -`SubscriptionComponentSubscription` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `State` | [`*models.SubscriptionState`](../../doc/models/subscription-state.md) | Optional | The state of a subscription.

* **Live States**
* `active` - A normal, active subscription. It is not in a trial and is paid and up to date.
* `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state.
* `paused` - An internal state that indicates that your account with Advanced Billing is in arrears.
* **Problem States**
* `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers.
* `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed.
* `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`.
* **End of Life States**
* `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription.
While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance.
* `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period.
* `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.)
* `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time.
* `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state.
* `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details.

See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. | -| `UpdatedAt` | `*time.Time` | Optional | - | - -## Example (as JSON) - -```json -{ - "state": "paused", - "updated_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Subscription Component Subscription + +An optional object, will be returned if provided `include=subscription` query param. + +## Structure + +`SubscriptionComponentSubscription` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `State` | [`*models.SubscriptionState`](../../doc/models/subscription-state.md) | Optional | The state of a subscription.

* **Live States**
* `active` - A normal, active subscription. It is not in a trial and is paid and up to date.
* `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state.
* `paused` - An internal state that indicates that your account with Advanced Billing is in arrears.
* **Problem States**
* `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers.
* `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed.
* `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`.
* **End of Life States**
* `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription.
While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance.
* `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period.
* `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.)
* `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time.
* `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state.
* `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details.

See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. | +| `UpdatedAt` | `*time.Time` | Optional | - | + +## Example (as JSON) + +```json +{ + "state": "paused", + "updated_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/subscription-component.md b/doc/models/subscription-component.md index 8fc23418..638c9183 100644 --- a/doc/models/subscription-component.md +++ b/doc/models/subscription-component.md @@ -1,55 +1,55 @@ - -# Subscription Component - -## Structure - -`SubscriptionComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Name` | `*string` | Optional | - | -| `Kind` | [`*models.ComponentKind`](../../doc/models/component-kind.md) | Optional | A handle for the component type | -| `UnitName` | `*string` | Optional | - | -| `Enabled` | `*bool` | Optional | (for on/off components) indicates if the component is enabled for the subscription | -| `UnitBalance` | `*int` | Optional | - | -| `Currency` | `*string` | Optional | - | -| `AllocatedQuantity` | `*interface{}` | Optional | For Quantity-based components: The current allocation for the component on the given subscription. For On/Off components: Use 1 for on. Use 0 for off. | -| `PricingScheme` | [`Optional[models.PricingScheme]`](../../doc/models/pricing-scheme.md) | Optional | - | -| `ComponentId` | `*int` | Optional | - | -| `ComponentHandle` | `Optional[string]` | Optional | - | -| `SubscriptionId` | `*int` | Optional | - | -| `Recurring` | `*bool` | Optional | - | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `DowngradeCredit` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | -| `ArchivedAt` | `Optional[time.Time]` | Optional | - | -| `PricePointId` | `Optional[int]` | Optional | - | -| `PricePointHandle` | `Optional[string]` | Optional | - | -| `PricePointType` | `*interface{}` | Optional | - | -| `PricePointName` | `Optional[string]` | Optional | - | -| `ProductFamilyId` | `*int` | Optional | - | -| `ProductFamilyHandle` | `*string` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `UpdatedAt` | `*time.Time` | Optional | - | -| `UseSiteExchangeRate` | `Optional[bool]` | Optional | - | -| `Description` | `Optional[string]` | Optional | - | -| `AllowFractionalQuantities` | `*bool` | Optional | - | -| `Subscription` | [`*models.SubscriptionComponentSubscription`](../../doc/models/subscription-component-subscription.md) | Optional | An optional object, will be returned if provided `include=subscription` query param. | -| `DisplayOnHostedPage` | `*bool` | Optional | - | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of '30' coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | - -## Example (as JSON) - -```json -{ - "id": 20, - "name": "name8", - "kind": "quantity_based_component", - "unit_name": "unit_name0", - "enabled": false -} -``` - + +# Subscription Component + +## Structure + +`SubscriptionComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Name` | `*string` | Optional | - | +| `Kind` | [`*models.ComponentKind`](../../doc/models/component-kind.md) | Optional | A handle for the component type | +| `UnitName` | `*string` | Optional | - | +| `Enabled` | `*bool` | Optional | (for on/off components) indicates if the component is enabled for the subscription | +| `UnitBalance` | `*int` | Optional | - | +| `Currency` | `*string` | Optional | - | +| `AllocatedQuantity` | [`*models.SubscriptionComponentAllocatedQuantity`](../../doc/models/containers/subscription-component-allocated-quantity.md) | Optional | This is a container for one-of cases. | +| `PricingScheme` | [`models.Optional[models.SubscriptionComponentPricingScheme]`](../../doc/models/containers/subscription-component-pricing-scheme.md) | Optional | This is a container for one-of cases. | +| `ComponentId` | `*int` | Optional | - | +| `ComponentHandle` | `models.Optional[string]` | Optional | - | +| `SubscriptionId` | `*int` | Optional | - | +| `Recurring` | `*bool` | Optional | - | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `DowngradeCredit` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | +| `ArchivedAt` | `models.Optional[time.Time]` | Optional | - | +| `PricePointId` | `models.Optional[int]` | Optional | - | +| `PricePointHandle` | `models.Optional[string]` | Optional | - | +| `PricePointType` | [`*models.SubscriptionComponentPricePointType`](../../doc/models/containers/subscription-component-price-point-type.md) | Optional | This is a container for one-of cases. | +| `PricePointName` | `models.Optional[string]` | Optional | - | +| `ProductFamilyId` | `*int` | Optional | - | +| `ProductFamilyHandle` | `*string` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `UpdatedAt` | `*time.Time` | Optional | - | +| `UseSiteExchangeRate` | `models.Optional[bool]` | Optional | - | +| `Description` | `models.Optional[string]` | Optional | - | +| `AllowFractionalQuantities` | `*bool` | Optional | - | +| `Subscription` | [`*models.SubscriptionComponentSubscription`](../../doc/models/subscription-component-subscription.md) | Optional | An optional object, will be returned if provided `include=subscription` query param. | +| `DisplayOnHostedPage` | `*bool` | Optional | - | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of '30' coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | + +## Example (as JSON) + +```json +{ + "id": 20, + "name": "name8", + "kind": "quantity_based_component", + "unit_name": "unit_name0", + "enabled": false +} +``` + diff --git a/doc/models/subscription-custom-price.md b/doc/models/subscription-custom-price.md index 73a3758b..71ed1e3a 100644 --- a/doc/models/subscription-custom-price.md +++ b/doc/models/subscription-custom-price.md @@ -1,54 +1,42 @@ - -# Subscription Custom Price - -(Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription - -## Structure - -`SubscriptionCustomPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `*string` | Optional | (Optional) | -| `Handle` | `*string` | Optional | (Optional) | -| `PriceInCents` | `interface{}` | Required | Required if using `custom_price` attribute. | -| `Interval` | `interface{}` | Required | Required if using `custom_price` attribute. | -| `IntervalUnit` | [`models.IntervalUnit`](../../doc/models/interval-unit.md) | Required | Required if using `custom_price` attribute. | -| `TrialPriceInCents` | `*interface{}` | Optional | (Optional) | -| `TrialInterval` | `*interface{}` | Optional | (Optional) | -| `TrialIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | (Optional) | -| `InitialChargeInCents` | `*interface{}` | Optional | (Optional) | -| `InitialChargeAfterTrial` | `*bool` | Optional | (Optional) | -| `ExpirationInterval` | `*interface{}` | Optional | (Optional) | -| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | (Optional) | -| `TaxIncluded` | `*bool` | Optional | (Optional) | - -## Example (as JSON) - -```json -{ - "name": "name4", - "handle": "handle0", - "price_in_cents": { - "key1": "val1", - "key2": "val2" - }, - "interval": { - "key1": "val1", - "key2": "val2" - }, - "interval_unit": "day", - "trial_price_in_cents": { - "key1": "val1", - "key2": "val2" - }, - "trial_interval": { - "key1": "val1", - "key2": "val2" - }, - "trial_interval_unit": "day" -} -``` - + +# Subscription Custom Price + +(Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription + +## Structure + +`SubscriptionCustomPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `*string` | Optional | (Optional) | +| `Handle` | `*string` | Optional | (Optional) | +| `PriceInCents` | [`models.SubscriptionCustomPricePriceInCents`](../../doc/models/containers/subscription-custom-price-price-in-cents.md) | Required | This is a container for one-of cases. | +| `Interval` | [`models.SubscriptionCustomPriceInterval`](../../doc/models/containers/subscription-custom-price-interval.md) | Required | This is a container for one-of cases. | +| `IntervalUnit` | [`models.IntervalUnit`](../../doc/models/interval-unit.md) | Required | Required if using `custom_price` attribute. | +| `TrialPriceInCents` | [`*models.SubscriptionCustomPriceTrialPriceInCents`](../../doc/models/containers/subscription-custom-price-trial-price-in-cents.md) | Optional | This is a container for one-of cases. | +| `TrialInterval` | [`*models.SubscriptionCustomPriceTrialInterval`](../../doc/models/containers/subscription-custom-price-trial-interval.md) | Optional | This is a container for one-of cases. | +| `TrialIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | (Optional) | +| `InitialChargeInCents` | [`*models.SubscriptionCustomPriceInitialChargeInCents`](../../doc/models/containers/subscription-custom-price-initial-charge-in-cents.md) | Optional | This is a container for one-of cases. | +| `InitialChargeAfterTrial` | `*bool` | Optional | (Optional) | +| `ExpirationInterval` | [`*models.SubscriptionCustomPriceExpirationInterval`](../../doc/models/containers/subscription-custom-price-expiration-interval.md) | Optional | This is a container for one-of cases. | +| `ExpirationIntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | (Optional) | +| `TaxIncluded` | `*bool` | Optional | (Optional) | + +## Example (as JSON) + +```json +{ + "name": "name4", + "handle": "handle0", + "price_in_cents": "String3", + "interval": "String3", + "interval_unit": "day", + "trial_price_in_cents": "String3", + "trial_interval": "String5", + "trial_interval_unit": "day" +} +``` + diff --git a/doc/models/subscription-date-field.md b/doc/models/subscription-date-field.md index b8ef069c..2f371768 100644 --- a/doc/models/subscription-date-field.md +++ b/doc/models/subscription-date-field.md @@ -1,21 +1,21 @@ - -# Subscription Date Field - -## Enumeration - -`SubscriptionDateField` - -## Fields - -| Name | -| --- | -| `CURRENTPERIODENDSAT` | -| `CURRENTPERIODSTARTSAT` | -| `CREATEDAT` | -| `ACTIVATEDAT` | -| `CANCELEDAT` | -| `EXPIRESAT` | -| `TRIALSTARTEDAT` | -| `TRIALENDEDAT` | -| `UPDATEDAT` | - + +# Subscription Date Field + +## Enumeration + +`SubscriptionDateField` + +## Fields + +| Name | +| --- | +| `CURRENTPERIODENDSAT` | +| `CURRENTPERIODSTARTSAT` | +| `CREATEDAT` | +| `ACTIVATEDAT` | +| `CANCELEDAT` | +| `EXPIRESAT` | +| `TRIALSTARTEDAT` | +| `TRIALENDEDAT` | +| `UPDATEDAT` | + diff --git a/doc/models/subscription-group-balances.md b/doc/models/subscription-group-balances.md index daad559b..e8bd146c 100644 --- a/doc/models/subscription-group-balances.md +++ b/doc/models/subscription-group-balances.md @@ -1,35 +1,43 @@ - -# Subscription Group Balances - -## Structure - -`SubscriptionGroupBalances` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Prepayments` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | - | -| `ServiceCredits` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | - | -| `OpenInvoices` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | - | -| `PendingDiscounts` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "prepayments": { - "balance_in_cents": 192 - }, - "service_credits": { - "balance_in_cents": 84 - }, - "open_invoices": { - "balance_in_cents": 40 - }, - "pending_discounts": { - "balance_in_cents": 88 - } -} -``` - + +# Subscription Group Balances + +## Structure + +`SubscriptionGroupBalances` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Prepayments` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | - | +| `ServiceCredits` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | - | +| `OpenInvoices` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | - | +| `PendingDiscounts` | [`*models.AccountBalance`](../../doc/models/account-balance.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "prepayments": { + "balance_in_cents": 192, + "automatic_balance_in_cents": 178, + "remittance_balance_in_cents": 146 + }, + "service_credits": { + "balance_in_cents": 84, + "automatic_balance_in_cents": 70, + "remittance_balance_in_cents": 38 + }, + "open_invoices": { + "balance_in_cents": 40, + "automatic_balance_in_cents": 202, + "remittance_balance_in_cents": 170 + }, + "pending_discounts": { + "balance_in_cents": 88, + "automatic_balance_in_cents": 154, + "remittance_balance_in_cents": 134 + } +} +``` + diff --git a/doc/models/subscription-group-bank-account.md b/doc/models/subscription-group-bank-account.md index cd103852..bdc866a4 100644 --- a/doc/models/subscription-group-bank-account.md +++ b/doc/models/subscription-group-bank-account.md @@ -1,40 +1,40 @@ - -# Subscription Group Bank Account - -## Structure - -`SubscriptionGroupBankAccount` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `BankName` | `*string` | Optional | (Required when creating a subscription with ACH or GoCardless) The name of the bank where the customer’s account resides | -| `BankAccountNumber` | `*string` | Optional | (Required when creating a subscription with ACH. Required when creating a subscription with GoCardless and bank_iban is blank) The customerʼs bank account number | -| `BankRoutingNumber` | `*string` | Optional | (Required when creating a subscription with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API | -| `BankIban` | `*string` | Optional | (Optional when creating a subscription with GoCardless). International Bank Account Number. Alternatively, local bank details can be provided | -| `BankBranchCode` | `*string` | Optional | (Optional when creating a subscription with GoCardless) Branch code. Alternatively, an IBAN can be provided | -| `BankAccountType` | [`*models.BankAccountType`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking | -| `BankAccountHolderType` | [`*models.BankAccountHolderType`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | -| `PaymentType` | [`*models.PaymentType`](../../doc/models/payment-type.md) | Optional | - | -| `BillingAddress` | `*string` | Optional | - | -| `BillingCity` | `*string` | Optional | - | -| `BillingState` | `*string` | Optional | - | -| `BillingZip` | `*string` | Optional | - | -| `BillingCountry` | `*string` | Optional | - | -| `ChargifyToken` | `*string` | Optional | - | -| `CurrentVault` | [`*models.BankAccountVault`](../../doc/models/bank-account-vault.md) | Optional | The vault that stores the payment profile with the provided vault_token. | -| `GatewayHandle` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "bank_name": "bank_name2", - "bank_account_number": "bank_account_number4", - "bank_routing_number": "bank_routing_number8", - "bank_iban": "bank_iban6", - "bank_branch_code": "bank_branch_code6" -} -``` - + +# Subscription Group Bank Account + +## Structure + +`SubscriptionGroupBankAccount` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `BankName` | `*string` | Optional | (Required when creating a subscription with ACH or GoCardless) The name of the bank where the customer’s account resides | +| `BankAccountNumber` | `*string` | Optional | (Required when creating a subscription with ACH. Required when creating a subscription with GoCardless and bank_iban is blank) The customerʼs bank account number | +| `BankRoutingNumber` | `*string` | Optional | (Required when creating a subscription with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API | +| `BankIban` | `*string` | Optional | (Optional when creating a subscription with GoCardless). International Bank Account Number. Alternatively, local bank details can be provided | +| `BankBranchCode` | `*string` | Optional | (Optional when creating a subscription with GoCardless) Branch code. Alternatively, an IBAN can be provided | +| `BankAccountType` | [`*models.BankAccountType`](../../doc/models/bank-account-type.md) | Optional | Defaults to checking | +| `BankAccountHolderType` | [`*models.BankAccountHolderType`](../../doc/models/bank-account-holder-type.md) | Optional | Defaults to personal | +| `PaymentType` | [`*models.PaymentType`](../../doc/models/payment-type.md) | Optional | - | +| `BillingAddress` | `*string` | Optional | - | +| `BillingCity` | `*string` | Optional | - | +| `BillingState` | `*string` | Optional | - | +| `BillingZip` | `*string` | Optional | - | +| `BillingCountry` | `*string` | Optional | - | +| `ChargifyToken` | `*string` | Optional | - | +| `CurrentVault` | [`*models.BankAccountVault`](../../doc/models/bank-account-vault.md) | Optional | The vault that stores the payment profile with the provided vault_token. | +| `GatewayHandle` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "bank_name": "bank_name2", + "bank_account_number": "bank_account_number4", + "bank_routing_number": "bank_routing_number8", + "bank_iban": "bank_iban6", + "bank_branch_code": "bank_branch_code6" +} +``` + diff --git a/doc/models/subscription-group-component-custom-price.md b/doc/models/subscription-group-component-custom-price.md index e58ca5d6..b91c8313 100644 --- a/doc/models/subscription-group-component-custom-price.md +++ b/doc/models/subscription-group-component-custom-price.md @@ -1,64 +1,46 @@ - -# Subscription Group Component Custom Price - -Used in place of `price_point_id` to define a custom price point unique to the subscription. You still need to provide `component_id`. - -## Structure - -`SubscriptionGroupComponentCustomPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | - | -| `OveragePricing` | [`[]models.ComponentCustomPrice`](../../doc/models/component-custom-price.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "pricing_scheme": "per_unit", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ], - "overage_pricing": [ - { - "pricing_scheme": "stairstep", - "interval": 230, - "interval_unit": "day", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - } - ] -} -``` - + +# Subscription Group Component Custom Price + +Used in place of `price_point_id` to define a custom price point unique to the subscription. You still need to provide `component_id`. + +## Structure + +`SubscriptionGroupComponentCustomPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.Price`](../../doc/models/price.md) | Optional | - | +| `OveragePricing` | [`[]models.ComponentCustomPrice`](../../doc/models/component-custom-price.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "pricing_scheme": "per_unit", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "overage_pricing": [ + { + "pricing_scheme": "stairstep", + "interval": 230, + "interval_unit": "day", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ] + } + ] +} +``` + diff --git a/doc/models/subscription-group-create-error-response-exception.md b/doc/models/subscription-group-create-error-response-exception.md new file mode 100644 index 00000000..18c631d9 --- /dev/null +++ b/doc/models/subscription-group-create-error-response-exception.md @@ -0,0 +1,25 @@ + +# Subscription Group Create Error Response Exception + +## Structure + +`SubscriptionGroupCreateErrorResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`models.SubscriptionGroupCreateErrorResponseErrors`](../../doc/models/containers/subscription-group-create-error-response-errors.md) | Required | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "errors": { + "members": [ + "members6" + ] + } +} +``` + diff --git a/doc/models/subscription-group-credit-card.md b/doc/models/subscription-group-credit-card.md index f3c4b4eb..f98b5748 100644 --- a/doc/models/subscription-group-credit-card.md +++ b/doc/models/subscription-group-credit-card.md @@ -1,53 +1,44 @@ - -# Subscription Group Credit Card - -## Structure - -`SubscriptionGroupCreditCard` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `FullNumber` | `*interface{}` | Optional | - | -| `ExpirationMonth` | `*interface{}` | Optional | - | -| `ExpirationYear` | `*interface{}` | Optional | - | -| `ChargifyToken` | `*string` | Optional | - | -| `VaultToken` | `*string` | Optional | - | -| `CurrentVault` | [`*models.CurrentVault`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | -| `GatewayHandle` | `*string` | Optional | - | -| `FirstName` | `*string` | Optional | - | -| `LastName` | `*string` | Optional | - | -| `BillingAddress` | `*string` | Optional | - | -| `BillingAddress2` | `*string` | Optional | - | -| `BillingCity` | `*string` | Optional | - | -| `BillingState` | `*string` | Optional | - | -| `BillingZip` | `*string` | Optional | - | -| `BillingCountry` | `*string` | Optional | - | -| `LastFour` | `*string` | Optional | - | -| `CardType` | [`*models.CardType`](../../doc/models/card-type.md) | Optional | The type of card used. | -| `CustomerVaultToken` | `*string` | Optional | - | -| `Cvv` | `*string` | Optional | - | -| `PaymentType` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "full_number": { - "key1": "val1", - "key2": "val2" - }, - "chargify_token": "tok_592nf92ng0sjd4300p", - "expiration_month": { - "key1": "val1", - "key2": "val2" - }, - "expiration_year": { - "key1": "val1", - "key2": "val2" - }, - "vault_token": "vault_token6" -} -``` - + +# Subscription Group Credit Card + +## Structure + +`SubscriptionGroupCreditCard` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FullNumber` | [`*models.SubscriptionGroupCreditCardFullNumber`](../../doc/models/containers/subscription-group-credit-card-full-number.md) | Optional | This is a container for one-of cases. | +| `ExpirationMonth` | [`*models.SubscriptionGroupCreditCardExpirationMonth`](../../doc/models/containers/subscription-group-credit-card-expiration-month.md) | Optional | This is a container for one-of cases. | +| `ExpirationYear` | [`*models.SubscriptionGroupCreditCardExpirationYear`](../../doc/models/containers/subscription-group-credit-card-expiration-year.md) | Optional | This is a container for one-of cases. | +| `ChargifyToken` | `*string` | Optional | - | +| `VaultToken` | `*string` | Optional | - | +| `CurrentVault` | [`*models.CurrentVault`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | +| `GatewayHandle` | `*string` | Optional | - | +| `FirstName` | `*string` | Optional | - | +| `LastName` | `*string` | Optional | - | +| `BillingAddress` | `*string` | Optional | - | +| `BillingAddress2` | `*string` | Optional | - | +| `BillingCity` | `*string` | Optional | - | +| `BillingState` | `*string` | Optional | - | +| `BillingZip` | `*string` | Optional | - | +| `BillingCountry` | `*string` | Optional | - | +| `LastFour` | `*string` | Optional | - | +| `CardType` | [`*models.CardType`](../../doc/models/card-type.md) | Optional | The type of card used. | +| `CustomerVaultToken` | `*string` | Optional | - | +| `Cvv` | `*string` | Optional | - | +| `PaymentType` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "full_number": 4111111111111111, + "chargify_token": "tok_592nf92ng0sjd4300p", + "expiration_month": "String1", + "expiration_year": "String5", + "vault_token": "vault_token6" +} +``` + diff --git a/doc/models/subscription-group-customer.md b/doc/models/subscription-group-customer.md index 74cf7b40..dd6d5ded 100644 --- a/doc/models/subscription-group-customer.md +++ b/doc/models/subscription-group-customer.md @@ -1,29 +1,29 @@ - -# Subscription Group Customer - -## Structure - -`SubscriptionGroupCustomer` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `FirstName` | `*string` | Optional | - | -| `LastName` | `*string` | Optional | - | -| `Organization` | `*string` | Optional | - | -| `Email` | `*string` | Optional | - | -| `Reference` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "first_name": "first_name4", - "last_name": "last_name2", - "organization": "organization2", - "email": "email2", - "reference": "reference0" -} -``` - + +# Subscription Group Customer + +## Structure + +`SubscriptionGroupCustomer` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FirstName` | `*string` | Optional | - | +| `LastName` | `*string` | Optional | - | +| `Organization` | `*string` | Optional | - | +| `Email` | `*string` | Optional | - | +| `Reference` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "first_name": "first_name4", + "last_name": "last_name2", + "organization": "organization2", + "email": "email2", + "reference": "reference0" +} +``` + diff --git a/doc/models/subscription-group-include.md b/doc/models/subscription-group-include.md new file mode 100644 index 00000000..425d4a08 --- /dev/null +++ b/doc/models/subscription-group-include.md @@ -0,0 +1,13 @@ + +# Subscription Group Include + +## Enumeration + +`SubscriptionGroupInclude` + +## Fields + +| Name | +| --- | +| `CURRENTBILLINGAMOUNTINCENTS` | + diff --git a/doc/models/subscription-group-item.md b/doc/models/subscription-group-item.md index fbc6fc4f..7dde2768 100644 --- a/doc/models/subscription-group-item.md +++ b/doc/models/subscription-group-item.md @@ -1,34 +1,34 @@ - -# Subscription Group Item - -## Structure - -`SubscriptionGroupItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Reference` | `Optional[string]` | Optional | - | -| `ProductId` | `*int` | Optional | - | -| `ProductHandle` | `Optional[string]` | Optional | - | -| `ProductPricePointId` | `*int` | Optional | - | -| `ProductPricePointHandle` | `*string` | Optional | - | -| `Currency` | `*string` | Optional | - | -| `CouponCode` | `Optional[string]` | Optional | - | -| `TotalRevenueInCents` | `*int64` | Optional | - | -| `BalanceInCents` | `*int64` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 16, - "reference": "reference8", - "product_id": 214, - "product_handle": "product_handle4", - "product_price_point_id": 138 -} -``` - + +# Subscription Group Item + +## Structure + +`SubscriptionGroupItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Reference` | `models.Optional[string]` | Optional | - | +| `ProductId` | `*int` | Optional | - | +| `ProductHandle` | `models.Optional[string]` | Optional | - | +| `ProductPricePointId` | `*int` | Optional | - | +| `ProductPricePointHandle` | `*string` | Optional | - | +| `Currency` | `*string` | Optional | - | +| `CouponCode` | `models.Optional[string]` | Optional | - | +| `TotalRevenueInCents` | `*int64` | Optional | - | +| `BalanceInCents` | `*int64` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 16, + "reference": "reference8", + "product_id": 214, + "product_handle": "product_handle4", + "product_price_point_id": 138 +} +``` + diff --git a/doc/models/subscription-group-member-error.md b/doc/models/subscription-group-member-error.md index 95772b82..0d141b30 100644 --- a/doc/models/subscription-group-member-error.md +++ b/doc/models/subscription-group-member-error.md @@ -1,25 +1,25 @@ - -# Subscription Group Member Error - -## Structure - -`SubscriptionGroupMemberError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Type` | `*string` | Optional | - | -| `Message` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 56, - "type": "type8", - "message": "message2" -} -``` - + +# Subscription Group Member Error + +## Structure + +`SubscriptionGroupMemberError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Type` | `*string` | Optional | - | +| `Message` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 56, + "type": "type8", + "message": "message2" +} +``` + diff --git a/doc/models/subscription-group-members-array-error.md b/doc/models/subscription-group-members-array-error.md new file mode 100644 index 00000000..ee9934cb --- /dev/null +++ b/doc/models/subscription-group-members-array-error.md @@ -0,0 +1,23 @@ + +# Subscription Group Members Array Error + +## Structure + +`SubscriptionGroupMembersArrayError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Members` | `[]string` | Required | - | + +## Example (as JSON) + +```json +{ + "members": [ + "members6" + ] +} +``` + diff --git a/doc/models/subscription-group-payment-profile.md b/doc/models/subscription-group-payment-profile.md index ff4472c1..6319f92c 100644 --- a/doc/models/subscription-group-payment-profile.md +++ b/doc/models/subscription-group-payment-profile.md @@ -1,27 +1,27 @@ - -# Subscription Group Payment Profile - -## Structure - -`SubscriptionGroupPaymentProfile` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `FirstName` | `*string` | Optional | - | -| `LastName` | `*string` | Optional | - | -| `MaskedCardNumber` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 22, - "first_name": "first_name4", - "last_name": "last_name2", - "masked_card_number": "masked_card_number2" -} -``` - + +# Subscription Group Payment Profile + +## Structure + +`SubscriptionGroupPaymentProfile` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `FirstName` | `*string` | Optional | - | +| `LastName` | `*string` | Optional | - | +| `MaskedCardNumber` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 22, + "first_name": "first_name4", + "last_name": "last_name2", + "masked_card_number": "masked_card_number2" +} +``` + diff --git a/doc/models/subscription-group-prepayment-method.md b/doc/models/subscription-group-prepayment-method.md index 1b69b44d..f73ef8ad 100644 --- a/doc/models/subscription-group-prepayment-method.md +++ b/doc/models/subscription-group-prepayment-method.md @@ -1,18 +1,18 @@ - -# Subscription Group Prepayment Method - -## Enumeration - -`SubscriptionGroupPrepaymentMethod` - -## Fields - -| Name | -| --- | -| `CHECK` | -| `CASH` | -| `MONEYORDER` | -| `ACH` | -| `PAYPALACCOUNT` | -| `OTHER` | - + +# Subscription Group Prepayment Method + +## Enumeration + +`SubscriptionGroupPrepaymentMethod` + +## Fields + +| Name | +| --- | +| `CHECK` | +| `CASH` | +| `MONEYORDER` | +| `ACH` | +| `PAYPALACCOUNT` | +| `OTHER` | + diff --git a/doc/models/subscription-group-prepayment-request.md b/doc/models/subscription-group-prepayment-request.md index 0ef8e4b9..fdafe4ad 100644 --- a/doc/models/subscription-group-prepayment-request.md +++ b/doc/models/subscription-group-prepayment-request.md @@ -1,26 +1,26 @@ - -# Subscription Group Prepayment Request - -## Structure - -`SubscriptionGroupPrepaymentRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Prepayment` | [`models.SubscriptionGroupPrepayment`](../../doc/models/subscription-group-prepayment.md) | Required | - | - -## Example (as JSON) - -```json -{ - "prepayment": { - "amount": 136, - "details": "details8", - "memo": "memo2", - "method": "paypal_account" - } -} -``` - + +# Subscription Group Prepayment Request + +## Structure + +`SubscriptionGroupPrepaymentRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Prepayment` | [`models.SubscriptionGroupPrepayment`](../../doc/models/subscription-group-prepayment.md) | Required | - | + +## Example (as JSON) + +```json +{ + "prepayment": { + "amount": 136, + "details": "details8", + "memo": "memo2", + "method": "paypal_account" + } +} +``` + diff --git a/doc/models/subscription-group-prepayment-response.md b/doc/models/subscription-group-prepayment-response.md index 817df979..53c5aa4b 100644 --- a/doc/models/subscription-group-prepayment-response.md +++ b/doc/models/subscription-group-prepayment-response.md @@ -1,29 +1,29 @@ - -# Subscription Group Prepayment Response - -## Structure - -`SubscriptionGroupPrepaymentResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `AmountInCents` | `*int64` | Optional | The amount in cents of the entry. | -| `EndingBalanceInCents` | `*int64` | Optional | The ending balance in cents of the account. | -| `EntryType` | [`*models.ServiceCreditType`](../../doc/models/service-credit-type.md) | Optional | The type of entry | -| `Memo` | `*string` | Optional | A memo attached to the entry. | - -## Example (as JSON) - -```json -{ - "id": 110, - "amount_in_cents": 196, - "ending_balance_in_cents": 236, - "entry_type": "Credit", - "memo": "memo2" -} -``` - + +# Subscription Group Prepayment Response + +## Structure + +`SubscriptionGroupPrepaymentResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `AmountInCents` | `*int64` | Optional | The amount in cents of the entry. | +| `EndingBalanceInCents` | `*int64` | Optional | The ending balance in cents of the account. | +| `EntryType` | [`*models.ServiceCreditType`](../../doc/models/service-credit-type.md) | Optional | The type of entry | +| `Memo` | `*string` | Optional | A memo attached to the entry. | + +## Example (as JSON) + +```json +{ + "id": 110, + "amount_in_cents": 196, + "ending_balance_in_cents": 236, + "entry_type": "Credit", + "memo": "memo2" +} +``` + diff --git a/doc/models/subscription-group-prepayment.md b/doc/models/subscription-group-prepayment.md index 3db444e2..5b7e3563 100644 --- a/doc/models/subscription-group-prepayment.md +++ b/doc/models/subscription-group-prepayment.md @@ -1,27 +1,27 @@ - -# Subscription Group Prepayment - -## Structure - -`SubscriptionGroupPrepayment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Amount` | `int` | Required | - | -| `Details` | `string` | Required | - | -| `Memo` | `string` | Required | - | -| `Method` | [`models.SubscriptionGroupPrepaymentMethod`](../../doc/models/subscription-group-prepayment-method.md) | Required | - | - -## Example (as JSON) - -```json -{ - "amount": 96, - "details": "details2", - "memo": "memo6", - "method": "money_order" -} -``` - + +# Subscription Group Prepayment + +## Structure + +`SubscriptionGroupPrepayment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Amount` | `int` | Required | - | +| `Details` | `string` | Required | - | +| `Memo` | `string` | Required | - | +| `Method` | [`models.SubscriptionGroupPrepaymentMethod`](../../doc/models/subscription-group-prepayment-method.md) | Required | - | + +## Example (as JSON) + +```json +{ + "amount": 96, + "details": "details2", + "memo": "memo6", + "method": "money_order" +} +``` + diff --git a/doc/models/subscription-group-response.md b/doc/models/subscription-group-response.md index 79032db8..af74ab8a 100644 --- a/doc/models/subscription-group-response.md +++ b/doc/models/subscription-group-response.md @@ -1,35 +1,35 @@ - -# Subscription Group Response - -## Structure - -`SubscriptionGroupResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SubscriptionGroup` | [`models.SubscriptionGroup`](../../doc/models/subscription-group.md) | Required | - | - -## Example (as JSON) - -```json -{ - "subscription_group": { - "customer_id": 220, - "payment_profile": { - "id": 44, - "first_name": "first_name4", - "last_name": "last_name2", - "masked_card_number": "masked_card_number2" - }, - "payment_collection_method": "payment_collection_method8", - "subscription_ids": [ - 74, - 75 - ], - "created_at": "2016-03-13T12:52:32.123Z" - } -} -``` - + +# Subscription Group Response + +## Structure + +`SubscriptionGroupResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionGroup` | [`models.SubscriptionGroup`](../../doc/models/subscription-group.md) | Required | - | + +## Example (as JSON) + +```json +{ + "subscription_group": { + "payment_collection_method": "automatic", + "customer_id": 220, + "payment_profile": { + "id": 44, + "first_name": "first_name4", + "last_name": "last_name2", + "masked_card_number": "masked_card_number2" + }, + "subscription_ids": [ + 74, + 75 + ], + "created_at": "2016-03-13T12:52:32.123Z" + } +} +``` + diff --git a/doc/models/subscription-group-signup-component.md b/doc/models/subscription-group-signup-component.md index f513fa14..d28c09c5 100644 --- a/doc/models/subscription-group-signup-component.md +++ b/doc/models/subscription-group-signup-component.md @@ -1,138 +1,81 @@ - -# Subscription Group Signup Component - -## Structure - -`SubscriptionGroupSignupComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ComponentId` | `*interface{}` | Optional | Required if passing any component to `components` attribute. | -| `AllocatedQuantity` | `*interface{}` | Optional | - | -| `UnitBalance` | `*interface{}` | Optional | - | -| `PricePointId` | `*interface{}` | Optional | - | -| `CustomPrice` | [`*models.SubscriptionGroupComponentCustomPrice`](../../doc/models/subscription-group-component-custom-price.md) | Optional | Used in place of `price_point_id` to define a custom price point unique to the subscription. You still need to provide `component_id`. | - -## Example (as JSON) - -```json -{ - "component_id": { - "key1": "val1", - "key2": "val2" - }, - "allocated_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_balance": { - "key1": "val1", - "key2": "val2" - }, - "price_point_id": { - "key1": "val1", - "key2": "val2" - }, - "custom_price": { - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ], - "overage_pricing": [ - { - "pricing_scheme": "stairstep", - "interval": 230, - "interval_unit": "day", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - }, - { - "pricing_scheme": "stairstep", - "interval": 230, - "interval_unit": "day", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - }, - { - "pricing_scheme": "stairstep", - "interval": 230, - "interval_unit": "day", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - } - ] - } -} -``` - + +# Subscription Group Signup Component + +## Structure + +`SubscriptionGroupSignupComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ComponentId` | [`*models.SubscriptionGroupSignupComponentComponentId`](../../doc/models/containers/subscription-group-signup-component-component-id.md) | Optional | This is a container for one-of cases. | +| `AllocatedQuantity` | [`*models.SubscriptionGroupSignupComponentAllocatedQuantity`](../../doc/models/containers/subscription-group-signup-component-allocated-quantity.md) | Optional | This is a container for one-of cases. | +| `UnitBalance` | [`*models.SubscriptionGroupSignupComponentUnitBalance`](../../doc/models/containers/subscription-group-signup-component-unit-balance.md) | Optional | This is a container for one-of cases. | +| `PricePointId` | [`*models.SubscriptionGroupSignupComponentPricePointId`](../../doc/models/containers/subscription-group-signup-component-price-point-id.md) | Optional | This is a container for one-of cases. | +| `CustomPrice` | [`*models.SubscriptionGroupComponentCustomPrice`](../../doc/models/subscription-group-component-custom-price.md) | Optional | Used in place of `price_point_id` to define a custom price point unique to the subscription. You still need to provide `component_id`. | + +## Example (as JSON) + +```json +{ + "component_id": "String1", + "allocated_quantity": "String5", + "unit_balance": "String9", + "price_point_id": "String5", + "custom_price": { + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ], + "overage_pricing": [ + { + "pricing_scheme": "stairstep", + "interval": 230, + "interval_unit": "day", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ] + }, + { + "pricing_scheme": "stairstep", + "interval": 230, + "interval_unit": "day", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ] + }, + { + "pricing_scheme": "stairstep", + "interval": 230, + "interval_unit": "day", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ] + } + ] + } +} +``` + diff --git a/doc/models/subscription-group-signup-error-response-exception.md b/doc/models/subscription-group-signup-error-response-exception.md index 8b539db2..c1763670 100644 --- a/doc/models/subscription-group-signup-error-response-exception.md +++ b/doc/models/subscription-group-signup-error-response-exception.md @@ -1,58 +1,70 @@ - -# Subscription Group Signup Error Response Exception - -## Structure - -`SubscriptionGroupSignupErrorResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`models.SubscriptionGroupSignupError`](../../doc/models/subscription-group-signup-error.md) | Required | - | - -## Example (as JSON) - -```json -{ - "errors": { - "subscriptions": { - "0": { - "payment_profile.chargify_token": [ - "Chargify token not found" - ], - "product": [ - "must be among the Products for this Site" - ], - "product_price_point_id": [ - "Product price point must belong to product." - ], - "payment_profile": [ - "payment_profile2" - ] - } - }, - "payer_reference": "payer_reference4", - "payer": { - "last_name": [ - "last_name5", - "last_name6" - ], - "first_name": [ - "first_name8" - ], - "email": [ - "email0", - "email9" - ] - }, - "subscription_group": [ - "subscription_group7", - "subscription_group8", - "subscription_group9" - ], - "payment_profile_id": "payment_profile_id8" - } -} -``` - + +# Subscription Group Signup Error Response Exception + +## Structure + +`SubscriptionGroupSignupErrorResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`models.SubscriptionGroupSignupError`](../../doc/models/subscription-group-signup-error.md) | Required | - | + +## Example (as JSON) + +```json +{ + "errors": { + "subscriptions": { + "0": { + "payment_profile.chargify_token": [ + "Chargify token not found" + ], + "product": [ + "Product must be among the Products for this Site" + ], + "product_price_point_id": [ + "Product price point must belong to product." + ], + "base": [ + "No payment method was on file for the $30.00 balance'" + ], + "payment_profile.expiration_month": [ + "Credit card expiration month: cannot be blank." + ], + "payment_profile.expiration_year": [ + "Credit card expiration year: cannot be blank." + ], + "payment_profile.full_number": [ + "Credit card number: cannot be blank." + ], + "payment_profile": [ + "payment_profile2" + ] + } + }, + "payer_reference": "payer_reference4", + "payer": { + "last_name": [ + "last_name5", + "last_name6" + ], + "first_name": [ + "first_name8" + ], + "email": [ + "email0", + "email9" + ] + }, + "subscription_group": [ + "subscription_group7", + "subscription_group8", + "subscription_group9" + ], + "payment_profile_id": "payment_profile_id8" + } +} +``` + diff --git a/doc/models/subscription-group-signup-error.md b/doc/models/subscription-group-signup-error.md index bcde02ac..f26bb605 100644 --- a/doc/models/subscription-group-signup-error.md +++ b/doc/models/subscription-group-signup-error.md @@ -1,74 +1,82 @@ - -# Subscription Group Signup Error - -## Structure - -`SubscriptionGroupSignupError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Subscriptions` | [`map[string]models.SubscriptionGroupSubscriptionError`](../../doc/models/subscription-group-subscription-error.md) | Optional | Object that as key have subscription position in request subscriptions array and as value subscription errors object. | -| `PayerReference` | `*string` | Optional | - | -| `Payer` | [`*models.PayerError`](../../doc/models/payer-error.md) | Optional | - | -| `SubscriptionGroup` | `[]string` | Optional | - | -| `PaymentProfileId` | `*string` | Optional | - | -| `PayerId` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "subscriptions": { - "key0": { - "product": [ - "product9" - ], - "product_price_point_id": [ - "product_price_point_id7" - ], - "payment_profile": [ - "payment_profile2" - ], - "payment_profile.chargify_token": [ - "payment_profile.chargify_token6" - ] - }, - "key1": { - "product": [ - "product9" - ], - "product_price_point_id": [ - "product_price_point_id7" - ], - "payment_profile": [ - "payment_profile2" - ], - "payment_profile.chargify_token": [ - "payment_profile.chargify_token6" - ] - } - }, - "payer_reference": "payer_reference0", - "payer": { - "last_name": [ - "last_name5", - "last_name6" - ], - "first_name": [ - "first_name8" - ], - "email": [ - "email0", - "email9" - ] - }, - "subscription_group": [ - "subscription_group1", - "subscription_group2" - ], - "payment_profile_id": "payment_profile_id2" -} -``` - + +# Subscription Group Signup Error + +## Structure + +`SubscriptionGroupSignupError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Subscriptions` | [`map[string]models.SubscriptionGroupSubscriptionError`](../../doc/models/subscription-group-subscription-error.md) | Optional | Object that as key have subscription position in request subscriptions array and as value subscription errors object. | +| `PayerReference` | `*string` | Optional | - | +| `Payer` | [`*models.PayerError`](../../doc/models/payer-error.md) | Optional | - | +| `SubscriptionGroup` | `[]string` | Optional | - | +| `PaymentProfileId` | `*string` | Optional | - | +| `PayerId` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "subscriptions": { + "key0": { + "product": [ + "product9" + ], + "product_price_point_id": [ + "product_price_point_id7" + ], + "payment_profile": [ + "payment_profile2" + ], + "payment_profile.chargify_token": [ + "payment_profile.chargify_token6" + ], + "base": [ + "base5", + "base6" + ] + }, + "key1": { + "product": [ + "product9" + ], + "product_price_point_id": [ + "product_price_point_id7" + ], + "payment_profile": [ + "payment_profile2" + ], + "payment_profile.chargify_token": [ + "payment_profile.chargify_token6" + ], + "base": [ + "base5", + "base6" + ] + } + }, + "payer_reference": "payer_reference0", + "payer": { + "last_name": [ + "last_name5", + "last_name6" + ], + "first_name": [ + "first_name8" + ], + "email": [ + "email0", + "email9" + ] + }, + "subscription_group": [ + "subscription_group1", + "subscription_group2" + ], + "payment_profile_id": "payment_profile_id2" +} +``` + diff --git a/doc/models/subscription-group-signup-failure-data.md b/doc/models/subscription-group-signup-failure-data.md new file mode 100644 index 00000000..2d559bff --- /dev/null +++ b/doc/models/subscription-group-signup-failure-data.md @@ -0,0 +1,38 @@ + +# Subscription Group Signup Failure Data + +## Structure + +`SubscriptionGroupSignupFailureData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PayerId` | `*int` | Optional | - | +| `PayerReference` | `*string` | Optional | - | +| `PaymentProfileId` | `*int` | Optional | - | +| `PaymentCollectionMethod` | `*string` | Optional | - | +| `PayerAttributes` | [`*models.PayerAttributes`](../../doc/models/payer-attributes.md) | Optional | - | +| `CreditCardAttributes` | [`*models.SubscriptionGroupCreditCard`](../../doc/models/subscription-group-credit-card.md) | Optional | - | +| `BankAccountAttributes` | [`*models.SubscriptionGroupBankAccount`](../../doc/models/subscription-group-bank-account.md) | Optional | - | +| `Subscriptions` | [`[]models.SubscriptionGroupSignupItem`](../../doc/models/subscription-group-signup-item.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "payer_id": 16, + "payer_reference": "payer_reference8", + "payment_profile_id": 6, + "payment_collection_method": "payment_collection_method0", + "payer_attributes": { + "first_name": "first_name2", + "last_name": "last_name0", + "email": "email4", + "cc_emails": "cc_emails2", + "organization": "organization6" + } +} +``` + diff --git a/doc/models/subscription-group-signup-failure.md b/doc/models/subscription-group-signup-failure.md new file mode 100644 index 00000000..d5487b52 --- /dev/null +++ b/doc/models/subscription-group-signup-failure.md @@ -0,0 +1,35 @@ + +# Subscription Group Signup Failure + +## Structure + +`SubscriptionGroupSignupFailure` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionGroup` | [`models.SubscriptionGroupSignupFailureData`](../../doc/models/subscription-group-signup-failure-data.md) | Required | - | +| `Customer` | `*string` | Required | - | + +## Example (as JSON) + +```json +{ + "subscription_group": { + "payer_id": 150, + "payer_reference": "payer_reference6", + "payment_profile_id": 128, + "payment_collection_method": "payment_collection_method8", + "payer_attributes": { + "first_name": "first_name2", + "last_name": "last_name0", + "email": "email4", + "cc_emails": "cc_emails2", + "organization": "organization6" + } + }, + "customer": "customer8" +} +``` + diff --git a/doc/models/subscription-group-signup-item.md b/doc/models/subscription-group-signup-item.md index 13f32d0d..8c2b71a0 100644 --- a/doc/models/subscription-group-signup-item.md +++ b/doc/models/subscription-group-signup-item.md @@ -1,41 +1,41 @@ - -# Subscription Group Signup Item - -## Structure - -`SubscriptionGroupSignupItem` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ProductHandle` | `*string` | Optional | The API Handle of the product for which you are creating a subscription. Required, unless a `product_id` is given instead. | -| `ProductId` | `*int` | Optional | The Product ID of the product for which you are creating a subscription. You can pass either `product_id` or `product_handle`. | -| `ProductPricePointId` | `*int` | Optional | The ID of the particular price point on the product. | -| `ProductPricePointHandle` | `*string` | Optional | The user-friendly API handle of a product's particular price point. | -| `OfferId` | `*int` | Optional | Use in place of passing product and component information to set up the subscription with an existing offer. May be either the Chargify ID of the offer or its handle prefixed with `handle:` | -| `Reference` | `*string` | Optional | The reference value (provided by your app) for the subscription itelf. | -| `Primary` | `*bool` | Optional | One of the subscriptions must be marked as primary in the group. | -| `Currency` | `*string` | Optional | (Optional) If Multi-Currency is enabled and the currency is configured in Chargify, pass it at signup to create a subscription on a non-default currency. Note that you cannot update the currency of an existing subscription. | -| `CouponCodes` | `[]string` | Optional | An array for all the coupons attached to the subscription. | -| `Components` | [`[]models.SubscriptionGroupSignupComponent`](../../doc/models/subscription-group-signup-component.md) | Optional | - | -| `CustomPrice` | [`*models.SubscriptionCustomPrice`](../../doc/models/subscription-custom-price.md) | Optional | (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription | -| `CalendarBilling` | [`*models.CalendarBilling`](../../doc/models/calendar-billing.md) | Optional | (Optional). Cannot be used when also specifying next_billing_at | -| `Metafields` | `map[string]string` | Optional | (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. | - -## Example (as JSON) - -```json -{ - "metafields": { - "custom_field_name_1": "custom_field_value_1", - "custom_field_name_2": "custom_field_value_2" - }, - "product_handle": "product_handle2", - "product_id": 34, - "product_price_point_id": 214, - "product_price_point_handle": "product_price_point_handle4", - "offer_id": 150 -} -``` - + +# Subscription Group Signup Item + +## Structure + +`SubscriptionGroupSignupItem` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProductHandle` | `*string` | Optional | The API Handle of the product for which you are creating a subscription. Required, unless a `product_id` is given instead. | +| `ProductId` | `*int` | Optional | The Product ID of the product for which you are creating a subscription. You can pass either `product_id` or `product_handle`. | +| `ProductPricePointId` | `*int` | Optional | The ID of the particular price point on the product. | +| `ProductPricePointHandle` | `*string` | Optional | The user-friendly API handle of a product's particular price point. | +| `OfferId` | `*int` | Optional | Use in place of passing product and component information to set up the subscription with an existing offer. May be either the Chargify ID of the offer or its handle prefixed with `handle:` | +| `Reference` | `*string` | Optional | The reference value (provided by your app) for the subscription itelf. | +| `Primary` | `*bool` | Optional | One of the subscriptions must be marked as primary in the group. | +| `Currency` | `*string` | Optional | (Optional) If Multi-Currency is enabled and the currency is configured in Chargify, pass it at signup to create a subscription on a non-default currency. Note that you cannot update the currency of an existing subscription. | +| `CouponCodes` | `[]string` | Optional | An array for all the coupons attached to the subscription. | +| `Components` | [`[]models.SubscriptionGroupSignupComponent`](../../doc/models/subscription-group-signup-component.md) | Optional | - | +| `CustomPrice` | [`*models.SubscriptionCustomPrice`](../../doc/models/subscription-custom-price.md) | Optional | (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription | +| `CalendarBilling` | [`*models.CalendarBilling`](../../doc/models/calendar-billing.md) | Optional | (Optional). Cannot be used when also specifying next_billing_at | +| `Metafields` | `map[string]string` | Optional | (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. | + +## Example (as JSON) + +```json +{ + "metafields": { + "custom_field_name_1": "custom_field_value_1", + "custom_field_name_2": "custom_field_value_2" + }, + "product_handle": "product_handle2", + "product_id": 34, + "product_price_point_id": 214, + "product_price_point_handle": "product_price_point_handle4", + "offer_id": 150 +} +``` + diff --git a/doc/models/subscription-group-signup-request.md b/doc/models/subscription-group-signup-request.md index 4ae33be5..c0001241 100644 --- a/doc/models/subscription-group-signup-request.md +++ b/doc/models/subscription-group-signup-request.md @@ -1,46 +1,46 @@ - -# Subscription Group Signup Request - -## Structure - -`SubscriptionGroupSignupRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SubscriptionGroup` | [`models.SubscriptionGroupSignup`](../../doc/models/subscription-group-signup.md) | Required | - | - -## Example (as JSON) - -```json -{ - "subscription_group": { - "payment_collection_method": "automatic", - "subscriptions": [ - { - "metafields": { - "custom_field_name_1": "custom_field_value_1", - "custom_field_name_2": "custom_field_value_2" - }, - "product_handle": "product_handle8", - "product_id": 144, - "product_price_point_id": 68, - "product_price_point_handle": "product_price_point_handle4", - "offer_id": 40 - } - ], - "payment_profile_id": 128, - "payer_id": 150, - "payer_reference": "payer_reference6", - "payer_attributes": { - "first_name": "first_name2", - "last_name": "last_name0", - "email": "email4", - "cc_emails": "cc_emails2", - "organization": "organization6" - } - } -} -``` - + +# Subscription Group Signup Request + +## Structure + +`SubscriptionGroupSignupRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionGroup` | [`models.SubscriptionGroupSignup`](../../doc/models/subscription-group-signup.md) | Required | - | + +## Example (as JSON) + +```json +{ + "subscription_group": { + "payment_collection_method": "automatic", + "subscriptions": [ + { + "metafields": { + "custom_field_name_1": "custom_field_value_1", + "custom_field_name_2": "custom_field_value_2" + }, + "product_handle": "product_handle8", + "product_id": 144, + "product_price_point_id": 68, + "product_price_point_handle": "product_price_point_handle4", + "offer_id": 40 + } + ], + "payment_profile_id": 128, + "payer_id": 150, + "payer_reference": "payer_reference6", + "payer_attributes": { + "first_name": "first_name2", + "last_name": "last_name0", + "email": "email4", + "cc_emails": "cc_emails2", + "organization": "organization6" + } + } +} +``` + diff --git a/doc/models/subscription-group-signup-response.md b/doc/models/subscription-group-signup-response.md index e04c3554..222f3f2a 100644 --- a/doc/models/subscription-group-signup-response.md +++ b/doc/models/subscription-group-signup-response.md @@ -1,40 +1,40 @@ - -# Subscription Group Signup Response - -## Structure - -`SubscriptionGroupSignupResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Uid` | `*string` | Optional | - | -| `Scheme` | `*int` | Optional | - | -| `CustomerId` | `*int` | Optional | - | -| `PaymentProfileId` | `*int` | Optional | - | -| `SubscriptionIds` | `[]int` | Optional | - | -| `PrimarySubscriptionId` | `*int` | Optional | - | -| `NextAssessmentAt` | `*time.Time` | Optional | - | -| `State` | `*string` | Optional | - | -| `CancelAtEndOfPeriod` | `*bool` | Optional | - | -| `Subscriptions` | [`[]models.SubscriptionGroupItem`](../../doc/models/subscription-group-item.md) | Optional | - | -| `PaymentCollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | - -## Example (as JSON) - -```json -{ - "payment_collection_method": "automatic", - "uid": "uid8", - "scheme": 28, - "customer_id": 48, - "payment_profile_id": 44, - "subscription_ids": [ - 158, - 159, - 160 - ] -} -``` - + +# Subscription Group Signup Response + +## Structure + +`SubscriptionGroupSignupResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `*string` | Optional | - | +| `Scheme` | `*int` | Optional | - | +| `CustomerId` | `*int` | Optional | - | +| `PaymentProfileId` | `*int` | Optional | - | +| `SubscriptionIds` | `[]int` | Optional | - | +| `PrimarySubscriptionId` | `*int` | Optional | - | +| `NextAssessmentAt` | `*time.Time` | Optional | - | +| `State` | [`*models.SubscriptionState`](../../doc/models/subscription-state.md) | Optional | The state of a subscription.

* **Live States**
* `active` - A normal, active subscription. It is not in a trial and is paid and up to date.
* `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state.
* `paused` - An internal state that indicates that your account with Advanced Billing is in arrears.
* **Problem States**
* `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers.
* `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed.
* `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`.
* **End of Life States**
* `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription.
While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance.
* `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period.
* `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.)
* `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time.
* `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state.
* `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details.

See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. | +| `CancelAtEndOfPeriod` | `*bool` | Optional | - | +| `Subscriptions` | [`[]models.SubscriptionGroupItem`](../../doc/models/subscription-group-item.md) | Optional | - | +| `PaymentCollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | + +## Example (as JSON) + +```json +{ + "payment_collection_method": "automatic", + "uid": "uid8", + "scheme": 28, + "customer_id": 48, + "payment_profile_id": 44, + "subscription_ids": [ + 158, + 159, + 160 + ] +} +``` + diff --git a/doc/models/subscription-group-signup-success-data.md b/doc/models/subscription-group-signup-success-data.md new file mode 100644 index 00000000..9381446b --- /dev/null +++ b/doc/models/subscription-group-signup-success-data.md @@ -0,0 +1,40 @@ + +# Subscription Group Signup Success Data + +## Structure + +`SubscriptionGroupSignupSuccessData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Uid` | `string` | Required | - | +| `Scheme` | `int` | Required | - | +| `CustomerId` | `int` | Required | - | +| `PaymentProfileId` | `int` | Required | - | +| `SubscriptionIds` | `[]int` | Required | - | +| `PrimarySubscriptionId` | `int` | Required | - | +| `NextAssessmentAt` | `time.Time` | Required | - | +| `State` | `string` | Required | - | +| `CancelAtEndOfPeriod` | `bool` | Required | - | + +## Example (as JSON) + +```json +{ + "uid": "uid8", + "scheme": 154, + "customer_id": 174, + "payment_profile_id": 82, + "subscription_ids": [ + 28, + 29 + ], + "primary_subscription_id": 102, + "next_assessment_at": "2016-03-13T12:52:32.123Z", + "state": "state4", + "cancel_at_end_of_period": false +} +``` + diff --git a/doc/models/subscription-group-signup-success.md b/doc/models/subscription-group-signup-success.md new file mode 100644 index 00000000..aff98447 --- /dev/null +++ b/doc/models/subscription-group-signup-success.md @@ -0,0 +1,42 @@ + +# Subscription Group Signup Success + +## Structure + +`SubscriptionGroupSignupSuccess` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionGroup` | [`models.SubscriptionGroupSignupSuccessData`](../../doc/models/subscription-group-signup-success-data.md) | Required | - | +| `Customer` | [`models.Customer`](../../doc/models/customer.md) | Required | - | + +## Example (as JSON) + +```json +{ + "subscription_group": { + "uid": "uid8", + "scheme": 200, + "customer_id": 220, + "payment_profile_id": 128, + "subscription_ids": [ + 74, + 75 + ], + "primary_subscription_id": 148, + "next_assessment_at": "2016-03-13T12:52:32.123Z", + "state": "state6", + "cancel_at_end_of_period": false + }, + "customer": { + "first_name": "first_name0", + "last_name": "last_name8", + "email": "email6", + "cc_emails": "cc_emails0", + "organization": "organization6" + } +} +``` + diff --git a/doc/models/subscription-group-signup.md b/doc/models/subscription-group-signup.md index ff4ddee1..d28ab58d 100644 --- a/doc/models/subscription-group-signup.md +++ b/doc/models/subscription-group-signup.md @@ -1,51 +1,51 @@ - -# Subscription Group Signup - -## Structure - -`SubscriptionGroupSignup` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PaymentProfileId` | `*int` | Optional | - | -| `PayerId` | `*int` | Optional | - | -| `PayerReference` | `*string` | Optional | - | -| `PaymentCollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | -| `PayerAttributes` | [`*models.PayerAttributes`](../../doc/models/payer-attributes.md) | Optional | - | -| `CreditCardAttributes` | [`*models.SubscriptionGroupCreditCard`](../../doc/models/subscription-group-credit-card.md) | Optional | - | -| `BankAccountAttributes` | [`*models.SubscriptionGroupBankAccount`](../../doc/models/subscription-group-bank-account.md) | Optional | - | -| `Subscriptions` | [`[]models.SubscriptionGroupSignupItem`](../../doc/models/subscription-group-signup-item.md) | Required | - | - -## Example (as JSON) - -```json -{ - "payment_collection_method": "automatic", - "subscriptions": [ - { - "metafields": { - "custom_field_name_1": "custom_field_value_1", - "custom_field_name_2": "custom_field_value_2" - }, - "product_handle": "product_handle8", - "product_id": 144, - "product_price_point_id": 68, - "product_price_point_handle": "product_price_point_handle4", - "offer_id": 40 - } - ], - "payment_profile_id": 42, - "payer_id": 64, - "payer_reference": "payer_reference8", - "payer_attributes": { - "first_name": "first_name2", - "last_name": "last_name0", - "email": "email4", - "cc_emails": "cc_emails2", - "organization": "organization6" - } -} -``` - + +# Subscription Group Signup + +## Structure + +`SubscriptionGroupSignup` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PaymentProfileId` | `*int` | Optional | - | +| `PayerId` | `*int` | Optional | - | +| `PayerReference` | `*string` | Optional | - | +| `PaymentCollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | +| `PayerAttributes` | [`*models.PayerAttributes`](../../doc/models/payer-attributes.md) | Optional | - | +| `CreditCardAttributes` | [`*models.SubscriptionGroupCreditCard`](../../doc/models/subscription-group-credit-card.md) | Optional | - | +| `BankAccountAttributes` | [`*models.SubscriptionGroupBankAccount`](../../doc/models/subscription-group-bank-account.md) | Optional | - | +| `Subscriptions` | [`[]models.SubscriptionGroupSignupItem`](../../doc/models/subscription-group-signup-item.md) | Required | - | + +## Example (as JSON) + +```json +{ + "payment_collection_method": "automatic", + "subscriptions": [ + { + "metafields": { + "custom_field_name_1": "custom_field_value_1", + "custom_field_name_2": "custom_field_value_2" + }, + "product_handle": "product_handle8", + "product_id": 144, + "product_price_point_id": 68, + "product_price_point_handle": "product_price_point_handle4", + "offer_id": 40 + } + ], + "payment_profile_id": 42, + "payer_id": 64, + "payer_reference": "payer_reference8", + "payer_attributes": { + "first_name": "first_name2", + "last_name": "last_name0", + "email": "email4", + "cc_emails": "cc_emails2", + "organization": "organization6" + } +} +``` + diff --git a/doc/models/subscription-group-single-error.md b/doc/models/subscription-group-single-error.md new file mode 100644 index 00000000..5fe8eb05 --- /dev/null +++ b/doc/models/subscription-group-single-error.md @@ -0,0 +1,21 @@ + +# Subscription Group Single Error + +## Structure + +`SubscriptionGroupSingleError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionGroup` | `string` | Required | - | + +## Example (as JSON) + +```json +{ + "subscription_group": "subscription_group2" +} +``` + diff --git a/doc/models/subscription-group-subscription-error.md b/doc/models/subscription-group-subscription-error.md index 90c4acec..4c589ffc 100644 --- a/doc/models/subscription-group-subscription-error.md +++ b/doc/models/subscription-group-subscription-error.md @@ -1,41 +1,50 @@ - -# Subscription Group Subscription Error - -Object which contains subscription errors. - -## Structure - -`SubscriptionGroupSubscriptionError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Product` | `[]string` | Optional | - | -| `ProductPricePointId` | `[]string` | Optional | - | -| `PaymentProfile` | `[]string` | Optional | - | -| `PaymentProfileChargifyToken` | `[]string` | Optional | - | - -## Example (as JSON) - -```json -{ - "product": [ - "product7", - "product6" - ], - "product_price_point_id": [ - "product_price_point_id9", - "product_price_point_id0" - ], - "payment_profile": [ - "payment_profile4", - "payment_profile5" - ], - "payment_profile.chargify_token": [ - "payment_profile.chargify_token8", - "payment_profile.chargify_token9" - ] -} -``` - + +# Subscription Group Subscription Error + +Object which contains subscription errors. + +## Structure + +`SubscriptionGroupSubscriptionError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Product` | `[]string` | Optional | - | +| `ProductPricePointId` | `[]string` | Optional | - | +| `PaymentProfile` | `[]string` | Optional | - | +| `PaymentProfileChargifyToken` | `[]string` | Optional | - | +| `Base` | `[]string` | Optional | - | +| `PaymentProfileExpirationMonth` | `[]string` | Optional | - | +| `PaymentProfileExpirationYear` | `[]string` | Optional | - | +| `PaymentProfileFullNumber` | `[]string` | Optional | - | + +## Example (as JSON) + +```json +{ + "product": [ + "product7", + "product6" + ], + "product_price_point_id": [ + "product_price_point_id9", + "product_price_point_id0" + ], + "payment_profile": [ + "payment_profile4", + "payment_profile5" + ], + "payment_profile.chargify_token": [ + "payment_profile.chargify_token8", + "payment_profile.chargify_token9" + ], + "base": [ + "base7", + "base8", + "base9" + ] +} +``` + diff --git a/doc/models/subscription-group-update-error-response-exception.md b/doc/models/subscription-group-update-error-response-exception.md index e444f337..9b363907 100644 --- a/doc/models/subscription-group-update-error-response-exception.md +++ b/doc/models/subscription-group-update-error-response-exception.md @@ -1,34 +1,34 @@ - -# Subscription Group Update Error Response Exception - -## Structure - -`SubscriptionGroupUpdateErrorResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`*models.SubscriptionGroupUpdateError`](../../doc/models/subscription-group-update-error.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "errors": { - "members": [ - { - "id": 204, - "type": "type2", - "message": "message8" - }, - { - "id": 204, - "type": "type2", - "message": "message8" - } - ] - } -} -``` - + +# Subscription Group Update Error Response Exception + +## Structure + +`SubscriptionGroupUpdateErrorResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`*models.SubscriptionGroupUpdateError`](../../doc/models/subscription-group-update-error.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "errors": { + "members": [ + { + "id": 204, + "type": "type2", + "message": "message8" + }, + { + "id": 204, + "type": "type2", + "message": "message8" + } + ] + } +} +``` + diff --git a/doc/models/subscription-group-update-error.md b/doc/models/subscription-group-update-error.md index 6eee1c11..9948c0b8 100644 --- a/doc/models/subscription-group-update-error.md +++ b/doc/models/subscription-group-update-error.md @@ -1,37 +1,37 @@ - -# Subscription Group Update Error - -## Structure - -`SubscriptionGroupUpdateError` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Members` | [`[]models.SubscriptionGroupMemberError`](../../doc/models/subscription-group-member-error.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "members": [ - { - "id": 204, - "type": "type2", - "message": "message8" - }, - { - "id": 204, - "type": "type2", - "message": "message8" - }, - { - "id": 204, - "type": "type2", - "message": "message8" - } - ] -} -``` - + +# Subscription Group Update Error + +## Structure + +`SubscriptionGroupUpdateError` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Members` | [`[]models.SubscriptionGroupMemberError`](../../doc/models/subscription-group-member-error.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "members": [ + { + "id": 204, + "type": "type2", + "message": "message8" + }, + { + "id": 204, + "type": "type2", + "message": "message8" + }, + { + "id": 204, + "type": "type2", + "message": "message8" + } + ] +} +``` + diff --git a/doc/models/subscription-group.md b/doc/models/subscription-group.md index acd94d15..0a19af41 100644 --- a/doc/models/subscription-group.md +++ b/doc/models/subscription-group.md @@ -1,38 +1,38 @@ - -# Subscription Group - -## Structure - -`SubscriptionGroup` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CustomerId` | `*int` | Optional | - | -| `PaymentProfile` | [`*models.SubscriptionGroupPaymentProfile`](../../doc/models/subscription-group-payment-profile.md) | Optional | - | -| `PaymentCollectionMethod` | `*string` | Optional | - | -| `SubscriptionIds` | `[]int` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | - -## Example (as JSON) - -```json -{ - "customer_id": 36, - "payment_profile": { - "id": 44, - "first_name": "first_name4", - "last_name": "last_name2", - "masked_card_number": "masked_card_number2" - }, - "payment_collection_method": "payment_collection_method8", - "subscription_ids": [ - 146, - 147, - 148 - ], - "created_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Subscription Group + +## Structure + +`SubscriptionGroup` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CustomerId` | `*int` | Optional | - | +| `PaymentProfile` | [`*models.SubscriptionGroupPaymentProfile`](../../doc/models/subscription-group-payment-profile.md) | Optional | - | +| `PaymentCollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | +| `SubscriptionIds` | `[]int` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | + +## Example (as JSON) + +```json +{ + "payment_collection_method": "automatic", + "customer_id": 36, + "payment_profile": { + "id": 44, + "first_name": "first_name4", + "last_name": "last_name2", + "masked_card_number": "masked_card_number2" + }, + "subscription_ids": [ + 146, + 147, + 148 + ], + "created_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/subscription-groups-list-include.md b/doc/models/subscription-groups-list-include.md new file mode 100644 index 00000000..054c0588 --- /dev/null +++ b/doc/models/subscription-groups-list-include.md @@ -0,0 +1,13 @@ + +# Subscription Groups List Include + +## Enumeration + +`SubscriptionGroupsListInclude` + +## Fields + +| Name | +| --- | +| `ACCOUNTBALANCES` | + diff --git a/doc/models/subscription-include.md b/doc/models/subscription-include.md index a7e279e6..315773bc 100644 --- a/doc/models/subscription-include.md +++ b/doc/models/subscription-include.md @@ -1,14 +1,14 @@ - -# Subscription Include - -## Enumeration - -`SubscriptionInclude` - -## Fields - -| Name | -| --- | -| `COUPONS` | -| `SELFSERVICEPAGETOKEN` | - + +# Subscription Include + +## Enumeration + +`SubscriptionInclude` + +## Fields + +| Name | +| --- | +| `COUPONS` | +| `SELFSERVICEPAGETOKEN` | + diff --git a/doc/models/subscription-included-coupon.md b/doc/models/subscription-included-coupon.md index f9f707c0..0886042a 100644 --- a/doc/models/subscription-included-coupon.md +++ b/doc/models/subscription-included-coupon.md @@ -1,33 +1,33 @@ - -# Subscription Included Coupon - -## Structure - -`SubscriptionIncludedCoupon` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Code` | `*string` | Optional | - | -| `UseCount` | `*int` | Optional | - | -| `UsesAllowed` | `*int` | Optional | - | -| `ExpiresAt` | `Optional[string]` | Optional | - | -| `Recurring` | `*bool` | Optional | - | -| `AmountInCents` | `Optional[int64]` | Optional | **Constraints**: `>= 0` | -| `Percentage` | `Optional[string]` | Optional | - | - -## Example (as JSON) - -```json -{ - "code": "\"ABCD_10\"", - "use_count": 2, - "uses_allowed": 10, - "expires_at": "\"2023-07-13T05:18:58-04:00\"", - "amount_in_cents": 1000, - "percentage": "\"15.0\"", - "recurring": false -} -``` - + +# Subscription Included Coupon + +## Structure + +`SubscriptionIncludedCoupon` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Code` | `*string` | Optional | - | +| `UseCount` | `*int` | Optional | - | +| `UsesAllowed` | `*int` | Optional | - | +| `ExpiresAt` | `models.Optional[string]` | Optional | - | +| `Recurring` | `*bool` | Optional | - | +| `AmountInCents` | `models.Optional[int64]` | Optional | **Constraints**: `>= 0` | +| `Percentage` | `models.Optional[string]` | Optional | - | + +## Example (as JSON) + +```json +{ + "code": "\"ABCD_10\"", + "use_count": 2, + "uses_allowed": 10, + "expires_at": "\"2023-07-13T05:18:58-04:00\"", + "amount_in_cents": 1000, + "percentage": "\"15.0\"", + "recurring": false +} +``` + diff --git a/doc/models/subscription-list-date-field.md b/doc/models/subscription-list-date-field.md index 55871a56..f0fd1fd4 100644 --- a/doc/models/subscription-list-date-field.md +++ b/doc/models/subscription-list-date-field.md @@ -1,19 +1,19 @@ - -# Subscription List Date Field - -## Enumeration - -`SubscriptionListDateField` - -## Fields - -| Name | -| --- | -| `UPDATEDAT` | - -## Example - -``` -updated_at -``` - + +# Subscription List Date Field + +## Enumeration + +`SubscriptionListDateField` + +## Fields + +| Name | +| --- | +| `UPDATEDAT` | + +## Example + +``` +updated_at +``` + diff --git a/doc/models/subscription-list-include.md b/doc/models/subscription-list-include.md index 25757cdf..daf30abf 100644 --- a/doc/models/subscription-list-include.md +++ b/doc/models/subscription-list-include.md @@ -1,13 +1,13 @@ - -# Subscription List Include - -## Enumeration - -`SubscriptionListInclude` - -## Fields - -| Name | -| --- | -| `SELFSERVICEPAGETOKEN` | - + +# Subscription List Include + +## Enumeration + +`SubscriptionListInclude` + +## Fields + +| Name | +| --- | +| `SELFSERVICEPAGETOKEN` | + diff --git a/doc/models/subscription-migration-preview-options.md b/doc/models/subscription-migration-preview-options.md index dda6fc77..8d4b2d78 100644 --- a/doc/models/subscription-migration-preview-options.md +++ b/doc/models/subscription-migration-preview-options.md @@ -1,35 +1,35 @@ - -# Subscription Migration Preview Options - -## Structure - -`SubscriptionMigrationPreviewOptions` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ProductId` | `*int` | Optional | The ID of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. | -| `ProductPricePointId` | `*int` | Optional | The ID of the specified product's price point. This can be passed to migrate to a non-default price point. | -| `IncludeTrial` | `*bool` | Optional | Whether to include the trial period configured for the product price point when starting a new billing period. Note that if preserve_period is set, then include_trial will be ignored.
**Default**: `false` | -| `IncludeInitialCharge` | `*bool` | Optional | If `true` is sent initial charges will be assessed.
**Default**: `false` | -| `IncludeCoupons` | `*bool` | Optional | If `true` is sent, any coupons associated with the subscription will be applied to the migration. If `false` is sent, coupons will not be applied. Note: When migrating to a new product family, the coupon cannot migrate.
**Default**: `true` | -| `PreservePeriod` | `*bool` | Optional | If `false` is sent, the subscription's billing period will be reset to today and the full price of the new product will be charged. If `true` is sent, the billing period will not change and a prorated charge will be issued for the new product.
**Default**: `false` | -| `ProductHandle` | `*string` | Optional | The handle of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. | -| `ProductPricePointHandle` | `*string` | Optional | The ID or handle of the specified product's price point. This can be passed to migrate to a non-default price point. | -| `Proration` | [`*models.Proration`](../../doc/models/proration.md) | Optional | - | -| `ProrationDate` | `*time.Time` | Optional | The date that the proration is calculated from for the preview | - -## Example (as JSON) - -```json -{ - "include_trial": false, - "include_initial_charge": false, - "include_coupons": true, - "preserve_period": false, - "product_id": 242, - "product_price_point_id": 166 -} -``` - + +# Subscription Migration Preview Options + +## Structure + +`SubscriptionMigrationPreviewOptions` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProductId` | `*int` | Optional | The ID of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. | +| `ProductPricePointId` | `*int` | Optional | The ID of the specified product's price point. This can be passed to migrate to a non-default price point. | +| `IncludeTrial` | `*bool` | Optional | Whether to include the trial period configured for the product price point when starting a new billing period. Note that if preserve_period is set, then include_trial will be ignored.
**Default**: `false` | +| `IncludeInitialCharge` | `*bool` | Optional | If `true` is sent initial charges will be assessed.
**Default**: `false` | +| `IncludeCoupons` | `*bool` | Optional | If `true` is sent, any coupons associated with the subscription will be applied to the migration. If `false` is sent, coupons will not be applied. Note: When migrating to a new product family, the coupon cannot migrate.
**Default**: `true` | +| `PreservePeriod` | `*bool` | Optional | If `false` is sent, the subscription's billing period will be reset to today and the full price of the new product will be charged. If `true` is sent, the billing period will not change and a prorated charge will be issued for the new product.
**Default**: `false` | +| `ProductHandle` | `*string` | Optional | The handle of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. | +| `ProductPricePointHandle` | `*string` | Optional | The ID or handle of the specified product's price point. This can be passed to migrate to a non-default price point. | +| `Proration` | [`*models.Proration`](../../doc/models/proration.md) | Optional | - | +| `ProrationDate` | `*time.Time` | Optional | The date that the proration is calculated from for the preview | + +## Example (as JSON) + +```json +{ + "include_trial": false, + "include_initial_charge": false, + "include_coupons": true, + "preserve_period": false, + "product_id": 242, + "product_price_point_id": 166 +} +``` + diff --git a/doc/models/subscription-migration-preview-request.md b/doc/models/subscription-migration-preview-request.md index f69be8ac..d0cec4ed 100644 --- a/doc/models/subscription-migration-preview-request.md +++ b/doc/models/subscription-migration-preview-request.md @@ -1,28 +1,28 @@ - -# Subscription Migration Preview Request - -## Structure - -`SubscriptionMigrationPreviewRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Migration` | [`models.SubscriptionMigrationPreviewOptions`](../../doc/models/subscription-migration-preview-options.md) | Required | - | - -## Example (as JSON) - -```json -{ - "migration": { - "include_trial": false, - "include_initial_charge": false, - "include_coupons": true, - "preserve_period": false, - "product_id": 158, - "product_price_point_id": 82 - } -} -``` - + +# Subscription Migration Preview Request + +## Structure + +`SubscriptionMigrationPreviewRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Migration` | [`models.SubscriptionMigrationPreviewOptions`](../../doc/models/subscription-migration-preview-options.md) | Required | - | + +## Example (as JSON) + +```json +{ + "migration": { + "include_trial": false, + "include_initial_charge": false, + "include_coupons": true, + "preserve_period": false, + "product_id": 158, + "product_price_point_id": 82 + } +} +``` + diff --git a/doc/models/subscription-migration-preview-response.md b/doc/models/subscription-migration-preview-response.md index 520b5b34..ea626204 100644 --- a/doc/models/subscription-migration-preview-response.md +++ b/doc/models/subscription-migration-preview-response.md @@ -1,26 +1,26 @@ - -# Subscription Migration Preview Response - -## Structure - -`SubscriptionMigrationPreviewResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Migration` | [`models.SubscriptionMigrationPreview`](../../doc/models/subscription-migration-preview.md) | Required | - | - -## Example (as JSON) - -```json -{ - "migration": { - "prorated_adjustment_in_cents": 196, - "charge_in_cents": 78, - "payment_due_in_cents": 250, - "credit_applied_in_cents": 210 - } -} -``` - + +# Subscription Migration Preview Response + +## Structure + +`SubscriptionMigrationPreviewResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Migration` | [`models.SubscriptionMigrationPreview`](../../doc/models/subscription-migration-preview.md) | Required | - | + +## Example (as JSON) + +```json +{ + "migration": { + "prorated_adjustment_in_cents": 196, + "charge_in_cents": 78, + "payment_due_in_cents": 250, + "credit_applied_in_cents": 210 + } +} +``` + diff --git a/doc/models/subscription-migration-preview.md b/doc/models/subscription-migration-preview.md index 1569bd3e..291ff191 100644 --- a/doc/models/subscription-migration-preview.md +++ b/doc/models/subscription-migration-preview.md @@ -1,27 +1,27 @@ - -# Subscription Migration Preview - -## Structure - -`SubscriptionMigrationPreview` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ProratedAdjustmentInCents` | `*int64` | Optional | The amount of the prorated adjustment that would be issued for the current subscription. | -| `ChargeInCents` | `*int64` | Optional | The amount of the charge that would be created for the new product. | -| `PaymentDueInCents` | `*int64` | Optional | The amount of the payment due in the case of an upgrade. | -| `CreditAppliedInCents` | `*int64` | Optional | Represents a credit in cents that is applied to your subscription as part of a migration process for a specific product, which reduces the amount owed for the subscription. | - -## Example (as JSON) - -```json -{ - "prorated_adjustment_in_cents": 134, - "charge_in_cents": 16, - "payment_due_in_cents": 188, - "credit_applied_in_cents": 148 -} -``` - + +# Subscription Migration Preview + +## Structure + +`SubscriptionMigrationPreview` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProratedAdjustmentInCents` | `*int64` | Optional | The amount of the prorated adjustment that would be issued for the current subscription. | +| `ChargeInCents` | `*int64` | Optional | The amount of the charge that would be created for the new product. | +| `PaymentDueInCents` | `*int64` | Optional | The amount of the payment due in the case of an upgrade. | +| `CreditAppliedInCents` | `*int64` | Optional | Represents a credit in cents that is applied to your subscription as part of a migration process for a specific product, which reduces the amount owed for the subscription. | + +## Example (as JSON) + +```json +{ + "prorated_adjustment_in_cents": 134, + "charge_in_cents": 16, + "payment_due_in_cents": 188, + "credit_applied_in_cents": 148 +} +``` + diff --git a/doc/models/subscription-mrr-breakout.md b/doc/models/subscription-mrr-breakout.md index 7f827df7..5203d68a 100644 --- a/doc/models/subscription-mrr-breakout.md +++ b/doc/models/subscription-mrr-breakout.md @@ -1,23 +1,23 @@ - -# Subscription MRR Breakout - -## Structure - -`SubscriptionMRRBreakout` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PlanAmountInCents` | `int64` | Required | - | -| `UsageAmountInCents` | `int64` | Required | - | - -## Example (as JSON) - -```json -{ - "plan_amount_in_cents": 208, - "usage_amount_in_cents": 60 -} -``` - + +# Subscription MRR Breakout + +## Structure + +`SubscriptionMRRBreakout` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PlanAmountInCents` | `int64` | Required | - | +| `UsageAmountInCents` | `int64` | Required | - | + +## Example (as JSON) + +```json +{ + "plan_amount_in_cents": 208, + "usage_amount_in_cents": 60 +} +``` + diff --git a/doc/models/subscription-mrr-response.md b/doc/models/subscription-mrr-response.md index 679bfca7..73d76352 100644 --- a/doc/models/subscription-mrr-response.md +++ b/doc/models/subscription-mrr-response.md @@ -1,30 +1,30 @@ - -# Subscription MRR Response - -## Structure - -`SubscriptionMRRResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SubscriptionsMrr` | [`[]models.SubscriptionMRR`](../../doc/models/subscription-mrr.md) | Required | **Constraints**: *Minimum Items*: `1`, *Unique Items Required* | - -## Example (as JSON) - -```json -{ - "subscriptions_mrr": [ - { - "subscription_id": 0, - "mrr_amount_in_cents": 0, - "breakouts": { - "plan_amount_in_cents": 0, - "usage_amount_in_cents": 0 - } - } - ] -} -``` - + +# Subscription MRR Response + +## Structure + +`SubscriptionMRRResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionsMrr` | [`[]models.SubscriptionMRR`](../../doc/models/subscription-mrr.md) | Required | **Constraints**: *Minimum Items*: `1`, *Unique Items Required* | + +## Example (as JSON) + +```json +{ + "subscriptions_mrr": [ + { + "subscription_id": 0, + "mrr_amount_in_cents": 0, + "breakouts": { + "plan_amount_in_cents": 0, + "usage_amount_in_cents": 0 + } + } + ] +} +``` + diff --git a/doc/models/subscription-mrr.md b/doc/models/subscription-mrr.md index 34659211..4ae4f9cd 100644 --- a/doc/models/subscription-mrr.md +++ b/doc/models/subscription-mrr.md @@ -1,28 +1,28 @@ - -# Subscription MRR - -## Structure - -`SubscriptionMRR` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SubscriptionId` | `int` | Required | - | -| `MrrAmountInCents` | `int64` | Required | - | -| `Breakouts` | [`*models.SubscriptionMRRBreakout`](../../doc/models/subscription-mrr-breakout.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "subscription_id": 4, - "mrr_amount_in_cents": 22, - "breakouts": { - "plan_amount_in_cents": 254, - "usage_amount_in_cents": 106 - } -} -``` - + +# Subscription MRR + +## Structure + +`SubscriptionMRR` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionId` | `int` | Required | - | +| `MrrAmountInCents` | `int64` | Required | - | +| `Breakouts` | [`*models.SubscriptionMRRBreakout`](../../doc/models/subscription-mrr-breakout.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "subscription_id": 4, + "mrr_amount_in_cents": 22, + "breakouts": { + "plan_amount_in_cents": 254, + "usage_amount_in_cents": 106 + } +} +``` + diff --git a/doc/models/subscription-note-response.md b/doc/models/subscription-note-response.md index 9a83d0b1..ecdfdb32 100644 --- a/doc/models/subscription-note-response.md +++ b/doc/models/subscription-note-response.md @@ -1,27 +1,27 @@ - -# Subscription Note Response - -## Structure - -`SubscriptionNoteResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Note` | [`models.SubscriptionNote`](../../doc/models/subscription-note.md) | Required | - | - -## Example (as JSON) - -```json -{ - "note": { - "id": 28, - "body": "body0", - "subscription_id": 138, - "created_at": "2016-03-13T12:52:32.123Z", - "updated_at": "2016-03-13T12:52:32.123Z" - } -} -``` - + +# Subscription Note Response + +## Structure + +`SubscriptionNoteResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Note` | [`models.SubscriptionNote`](../../doc/models/subscription-note.md) | Required | - | + +## Example (as JSON) + +```json +{ + "note": { + "id": 28, + "body": "body0", + "subscription_id": 138, + "created_at": "2016-03-13T12:52:32.123Z", + "updated_at": "2016-03-13T12:52:32.123Z" + } +} +``` + diff --git a/doc/models/subscription-note.md b/doc/models/subscription-note.md index 036099b7..3415742f 100644 --- a/doc/models/subscription-note.md +++ b/doc/models/subscription-note.md @@ -1,30 +1,30 @@ - -# Subscription Note - -## Structure - -`SubscriptionNote` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `Body` | `*string` | Optional | - | -| `SubscriptionId` | `*int` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `UpdatedAt` | `*time.Time` | Optional | - | -| `Sticky` | `*bool` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 36, - "body": "body4", - "subscription_id": 146, - "created_at": "2016-03-13T12:52:32.123Z", - "updated_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Subscription Note + +## Structure + +`SubscriptionNote` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `Body` | `*string` | Optional | - | +| `SubscriptionId` | `*int` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `UpdatedAt` | `*time.Time` | Optional | - | +| `Sticky` | `*bool` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 36, + "body": "body4", + "subscription_id": 146, + "created_at": "2016-03-13T12:52:32.123Z", + "updated_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/subscription-preview-response.md b/doc/models/subscription-preview-response.md index 95ba9e22..3006e36f 100644 --- a/doc/models/subscription-preview-response.md +++ b/doc/models/subscription-preview-response.md @@ -1,66 +1,66 @@ - -# Subscription Preview Response - -## Structure - -`SubscriptionPreviewResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SubscriptionPreview` | [`models.SubscriptionPreview`](../../doc/models/subscription-preview.md) | Required | - | - -## Example (as JSON) - -```json -{ - "subscription_preview": { - "current_billing_manifest": { - "line_items": [ - { - "transaction_type": "credit", - "kind": "component", - "amount_in_cents": 24, - "memo": "memo2", - "discount_amount_in_cents": 172 - } - ], - "total_in_cents": 38, - "total_discount_in_cents": 24, - "total_tax_in_cents": 18, - "subtotal_in_cents": 150 - }, - "next_billing_manifest": { - "line_items": [ - { - "transaction_type": "credit", - "kind": "component", - "amount_in_cents": 24, - "memo": "memo2", - "discount_amount_in_cents": 172 - }, - { - "transaction_type": "credit", - "kind": "component", - "amount_in_cents": 24, - "memo": "memo2", - "discount_amount_in_cents": 172 - }, - { - "transaction_type": "credit", - "kind": "component", - "amount_in_cents": 24, - "memo": "memo2", - "discount_amount_in_cents": 172 - } - ], - "total_in_cents": 62, - "total_discount_in_cents": 208, - "total_tax_in_cents": 42, - "subtotal_in_cents": 174 - } - } -} -``` - + +# Subscription Preview Response + +## Structure + +`SubscriptionPreviewResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionPreview` | [`models.SubscriptionPreview`](../../doc/models/subscription-preview.md) | Required | - | + +## Example (as JSON) + +```json +{ + "subscription_preview": { + "current_billing_manifest": { + "line_items": [ + { + "transaction_type": "credit", + "kind": "component", + "amount_in_cents": 24, + "memo": "memo2", + "discount_amount_in_cents": 172 + } + ], + "total_in_cents": 38, + "total_discount_in_cents": 24, + "total_tax_in_cents": 18, + "subtotal_in_cents": 150 + }, + "next_billing_manifest": { + "line_items": [ + { + "transaction_type": "credit", + "kind": "component", + "amount_in_cents": 24, + "memo": "memo2", + "discount_amount_in_cents": 172 + }, + { + "transaction_type": "credit", + "kind": "component", + "amount_in_cents": 24, + "memo": "memo2", + "discount_amount_in_cents": 172 + }, + { + "transaction_type": "credit", + "kind": "component", + "amount_in_cents": 24, + "memo": "memo2", + "discount_amount_in_cents": 172 + } + ], + "total_in_cents": 62, + "total_discount_in_cents": 208, + "total_tax_in_cents": 42, + "subtotal_in_cents": 174 + } + } +} +``` + diff --git a/doc/models/subscription-preview.md b/doc/models/subscription-preview.md index c3853731..b3db99be 100644 --- a/doc/models/subscription-preview.md +++ b/doc/models/subscription-preview.md @@ -1,65 +1,65 @@ - -# Subscription Preview - -## Structure - -`SubscriptionPreview` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CurrentBillingManifest` | [`*models.BillingManifest`](../../doc/models/billing-manifest.md) | Optional | - | -| `NextBillingManifest` | [`*models.BillingManifest`](../../doc/models/billing-manifest.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "current_billing_manifest": { - "line_items": [ - { - "transaction_type": "credit", - "kind": "component", - "amount_in_cents": 24, - "memo": "memo2", - "discount_amount_in_cents": 172 - } - ], - "total_in_cents": 38, - "total_discount_in_cents": 24, - "total_tax_in_cents": 18, - "subtotal_in_cents": 150 - }, - "next_billing_manifest": { - "line_items": [ - { - "transaction_type": "credit", - "kind": "component", - "amount_in_cents": 24, - "memo": "memo2", - "discount_amount_in_cents": 172 - }, - { - "transaction_type": "credit", - "kind": "component", - "amount_in_cents": 24, - "memo": "memo2", - "discount_amount_in_cents": 172 - }, - { - "transaction_type": "credit", - "kind": "component", - "amount_in_cents": 24, - "memo": "memo2", - "discount_amount_in_cents": 172 - } - ], - "total_in_cents": 62, - "total_discount_in_cents": 208, - "total_tax_in_cents": 42, - "subtotal_in_cents": 174 - } -} -``` - + +# Subscription Preview + +## Structure + +`SubscriptionPreview` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrentBillingManifest` | [`*models.BillingManifest`](../../doc/models/billing-manifest.md) | Optional | - | +| `NextBillingManifest` | [`*models.BillingManifest`](../../doc/models/billing-manifest.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "current_billing_manifest": { + "line_items": [ + { + "transaction_type": "credit", + "kind": "component", + "amount_in_cents": 24, + "memo": "memo2", + "discount_amount_in_cents": 172 + } + ], + "total_in_cents": 38, + "total_discount_in_cents": 24, + "total_tax_in_cents": 18, + "subtotal_in_cents": 150 + }, + "next_billing_manifest": { + "line_items": [ + { + "transaction_type": "credit", + "kind": "component", + "amount_in_cents": 24, + "memo": "memo2", + "discount_amount_in_cents": 172 + }, + { + "transaction_type": "credit", + "kind": "component", + "amount_in_cents": 24, + "memo": "memo2", + "discount_amount_in_cents": 172 + }, + { + "transaction_type": "credit", + "kind": "component", + "amount_in_cents": 24, + "memo": "memo2", + "discount_amount_in_cents": 172 + } + ], + "total_in_cents": 62, + "total_discount_in_cents": 208, + "total_tax_in_cents": 42, + "subtotal_in_cents": 174 + } +} +``` + diff --git a/doc/models/subscription-product-change.md b/doc/models/subscription-product-change.md new file mode 100644 index 00000000..fdf5431a --- /dev/null +++ b/doc/models/subscription-product-change.md @@ -0,0 +1,23 @@ + +# Subscription Product Change + +## Structure + +`SubscriptionProductChange` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PreviousProductId` | `int` | Required | - | +| `NewProductId` | `int` | Required | - | + +## Example (as JSON) + +```json +{ + "previous_product_id": 126, + "new_product_id": 12 +} +``` + diff --git a/doc/models/subscription-product-migration-request.md b/doc/models/subscription-product-migration-request.md index 2c28b9e5..3faa943d 100644 --- a/doc/models/subscription-product-migration-request.md +++ b/doc/models/subscription-product-migration-request.md @@ -1,28 +1,28 @@ - -# Subscription Product Migration Request - -## Structure - -`SubscriptionProductMigrationRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Migration` | [`models.SubscriptionProductMigration`](../../doc/models/subscription-product-migration.md) | Required | - | - -## Example (as JSON) - -```json -{ - "migration": { - "include_trial": false, - "include_initial_charge": false, - "include_coupons": true, - "preserve_period": false, - "product_id": 158, - "product_price_point_id": 82 - } -} -``` - + +# Subscription Product Migration Request + +## Structure + +`SubscriptionProductMigrationRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Migration` | [`models.SubscriptionProductMigration`](../../doc/models/subscription-product-migration.md) | Required | - | + +## Example (as JSON) + +```json +{ + "migration": { + "include_trial": false, + "include_initial_charge": false, + "include_coupons": true, + "preserve_period": false, + "product_id": 158, + "product_price_point_id": 82 + } +} +``` + diff --git a/doc/models/subscription-product-migration.md b/doc/models/subscription-product-migration.md index 589583cc..d10e6e89 100644 --- a/doc/models/subscription-product-migration.md +++ b/doc/models/subscription-product-migration.md @@ -1,34 +1,34 @@ - -# Subscription Product Migration - -## Structure - -`SubscriptionProductMigration` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ProductId` | `*int` | Optional | The ID of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. | -| `ProductPricePointId` | `*int` | Optional | The ID of the specified product's price point. This can be passed to migrate to a non-default price point. | -| `IncludeTrial` | `*bool` | Optional | Whether to include the trial period configured for the product price point when starting a new billing period. Note that if preserve_period is set, then include_trial will be ignored.
**Default**: `false` | -| `IncludeInitialCharge` | `*bool` | Optional | If `true` is sent initial charges will be assessed.
**Default**: `false` | -| `IncludeCoupons` | `*bool` | Optional | If `true` is sent, any coupons associated with the subscription will be applied to the migration. If `false` is sent, coupons will not be applied. Note: When migrating to a new product family, the coupon cannot migrate.
**Default**: `true` | -| `PreservePeriod` | `*bool` | Optional | If `false` is sent, the subscription's billing period will be reset to today and the full price of the new product will be charged. If `true` is sent, the billing period will not change and a prorated charge will be issued for the new product.
**Default**: `false` | -| `ProductHandle` | `*string` | Optional | The handle of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. | -| `ProductPricePointHandle` | `*string` | Optional | The ID or handle of the specified product's price point. This can be passed to migrate to a non-default price point. | -| `Proration` | [`*models.Proration`](../../doc/models/proration.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "include_trial": false, - "include_initial_charge": false, - "include_coupons": true, - "preserve_period": false, - "product_id": 8, - "product_price_point_id": 172 -} -``` - + +# Subscription Product Migration + +## Structure + +`SubscriptionProductMigration` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ProductId` | `*int` | Optional | The ID of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. | +| `ProductPricePointId` | `*int` | Optional | The ID of the specified product's price point. This can be passed to migrate to a non-default price point. | +| `IncludeTrial` | `*bool` | Optional | Whether to include the trial period configured for the product price point when starting a new billing period. Note that if preserve_period is set, then include_trial will be ignored.
**Default**: `false` | +| `IncludeInitialCharge` | `*bool` | Optional | If `true` is sent initial charges will be assessed.
**Default**: `false` | +| `IncludeCoupons` | `*bool` | Optional | If `true` is sent, any coupons associated with the subscription will be applied to the migration. If `false` is sent, coupons will not be applied. Note: When migrating to a new product family, the coupon cannot migrate.
**Default**: `true` | +| `PreservePeriod` | `*bool` | Optional | If `false` is sent, the subscription's billing period will be reset to today and the full price of the new product will be charged. If `true` is sent, the billing period will not change and a prorated charge will be issued for the new product.
**Default**: `false` | +| `ProductHandle` | `*string` | Optional | The handle of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. | +| `ProductPricePointHandle` | `*string` | Optional | The ID or handle of the specified product's price point. This can be passed to migrate to a non-default price point. | +| `Proration` | [`*models.Proration`](../../doc/models/proration.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "include_trial": false, + "include_initial_charge": false, + "include_coupons": true, + "preserve_period": false, + "product_id": 8, + "product_price_point_id": 172 +} +``` + diff --git a/doc/models/subscription-purge-type.md b/doc/models/subscription-purge-type.md index 306b9be3..4a13c0d2 100644 --- a/doc/models/subscription-purge-type.md +++ b/doc/models/subscription-purge-type.md @@ -1,14 +1,14 @@ - -# Subscription Purge Type - -## Enumeration - -`SubscriptionPurgeType` - -## Fields - -| Name | -| --- | -| `CUSTOMER` | -| `PAYMENTPROFILE` | - + +# Subscription Purge Type + +## Enumeration + +`SubscriptionPurgeType` + +## Fields + +| Name | +| --- | +| `CUSTOMER` | +| `PAYMENTPROFILE` | + diff --git a/doc/models/subscription-remove-coupon-errors-exception.md b/doc/models/subscription-remove-coupon-errors-exception.md index 86d5906c..797e1246 100644 --- a/doc/models/subscription-remove-coupon-errors-exception.md +++ b/doc/models/subscription-remove-coupon-errors-exception.md @@ -1,23 +1,23 @@ - -# Subscription Remove Coupon Errors Exception - -## Structure - -`SubscriptionRemoveCouponErrorsException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Subscription` | `[]string` | Required | - | - -## Example (as JSON) - -```json -{ - "subscription": [ - "subscription0" - ] -} -``` - + +# Subscription Remove Coupon Errors Exception + +## Structure + +`SubscriptionRemoveCouponErrorsException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Subscription` | `[]string` | Required | - | + +## Example (as JSON) + +```json +{ + "subscription": [ + "subscription0" + ] +} +``` + diff --git a/doc/models/subscription-response.md b/doc/models/subscription-response.md index 44ec696b..17cb2159 100644 --- a/doc/models/subscription-response.md +++ b/doc/models/subscription-response.md @@ -1,27 +1,27 @@ - -# Subscription Response - -## Structure - -`SubscriptionResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Subscription` | [`*models.Subscription`](../../doc/models/subscription.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "subscription": { - "id": 8, - "state": "paused", - "balance_in_cents": 124, - "total_revenue_in_cents": 48, - "product_price_in_cents": 238 - } -} -``` - + +# Subscription Response + +## Structure + +`SubscriptionResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Subscription` | [`*models.Subscription`](../../doc/models/subscription.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "subscription": { + "id": 8, + "state": "paused", + "balance_in_cents": 124, + "total_revenue_in_cents": 48, + "product_price_in_cents": 238 + } +} +``` + diff --git a/doc/models/subscription-sort.md b/doc/models/subscription-sort.md index bcfb745d..140193b7 100644 --- a/doc/models/subscription-sort.md +++ b/doc/models/subscription-sort.md @@ -1,18 +1,18 @@ - -# Subscription Sort - -## Enumeration - -`SubscriptionSort` - -## Fields - -| Name | -| --- | -| `SIGNUPDATE` | -| `PERIODSTART` | -| `PERIODEND` | -| `NEXTASSESSMENT` | -| `UPDATEDAT` | -| `CREATEDAT` | - + +# Subscription Sort + +## Enumeration + +`SubscriptionSort` + +## Fields + +| Name | +| --- | +| `SIGNUPDATE` | +| `PERIODSTART` | +| `PERIODEND` | +| `NEXTASSESSMENT` | +| `UPDATEDAT` | +| `CREATEDAT` | + diff --git a/doc/models/subscription-state-change.md b/doc/models/subscription-state-change.md new file mode 100644 index 00000000..7b190a12 --- /dev/null +++ b/doc/models/subscription-state-change.md @@ -0,0 +1,23 @@ + +# Subscription State Change + +## Structure + +`SubscriptionStateChange` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PreviousSubscriptionState` | `string` | Required | **Constraints**: *Minimum Length*: `1` | +| `NewSubscriptionState` | `string` | Required | **Constraints**: *Minimum Length*: `1` | + +## Example (as JSON) + +```json +{ + "previous_subscription_state": "previous_subscription_state2", + "new_subscription_state": "new_subscription_state6" +} +``` + diff --git a/doc/models/subscription-state-filter.md b/doc/models/subscription-state-filter.md index fd5f2a90..37f4263f 100644 --- a/doc/models/subscription-state-filter.md +++ b/doc/models/subscription-state-filter.md @@ -1,26 +1,26 @@ - -# Subscription State Filter - -Allowed values for filtering by the current state of the subscription. - -## Enumeration - -`SubscriptionStateFilter` - -## Fields - -| Name | -| --- | -| `ACTIVE` | -| `CANCELED` | -| `EXPIRED` | -| `EXPIREDCARDS` | -| `ONHOLD` | -| `PASTDUE` | -| `PENDINGCANCELLATION` | -| `PENDINGRENEWAL` | -| `SUSPENDED` | -| `TRIALENDED` | -| `TRIALING` | -| `UNPAID` | - + +# Subscription State Filter + +Allowed values for filtering by the current state of the subscription. + +## Enumeration + +`SubscriptionStateFilter` + +## Fields + +| Name | +| --- | +| `ACTIVE` | +| `CANCELED` | +| `EXPIRED` | +| `EXPIREDCARDS` | +| `ONHOLD` | +| `PASTDUE` | +| `PENDINGCANCELLATION` | +| `PENDINGRENEWAL` | +| `SUSPENDED` | +| `TRIALENDED` | +| `TRIALING` | +| `UNPAID` | + diff --git a/doc/models/subscription-state.md b/doc/models/subscription-state.md index f88c7694..2f26f5d9 100644 --- a/doc/models/subscription-state.md +++ b/doc/models/subscription-state.md @@ -1,6 +1,6 @@ - -# Subscription State - + +# Subscription State + The state of a subscription. * **Live States** @@ -22,29 +22,29 @@ The state of a subscription. * `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state. * `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details. -See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. - -## Enumeration - -`SubscriptionState` - -## Fields - -| Name | -| --- | -| `PENDING` | -| `FAILEDTOCREATE` | -| `TRIALING` | -| `ASSESSING` | -| `ACTIVE` | -| `SOFTFAILURE` | -| `PASTDUE` | -| `SUSPENDED` | -| `CANCELED` | -| `EXPIRED` | -| `PAUSED` | -| `UNPAID` | -| `TRIALENDED` | -| `ONHOLD` | -| `AWAITINGSIGNUP` | - +See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. + +## Enumeration + +`SubscriptionState` + +## Fields + +| Name | +| --- | +| `PENDING` | +| `FAILEDTOCREATE` | +| `TRIALING` | +| `ASSESSING` | +| `ACTIVE` | +| `SOFTFAILURE` | +| `PASTDUE` | +| `SUSPENDED` | +| `CANCELED` | +| `EXPIRED` | +| `PAUSED` | +| `UNPAID` | +| `TRIALENDED` | +| `ONHOLD` | +| `AWAITINGSIGNUP` | + diff --git a/doc/models/subscription.md b/doc/models/subscription.md index a89480a2..ec762012 100644 --- a/doc/models/subscription.md +++ b/doc/models/subscription.md @@ -1,110 +1,110 @@ - -# Subscription - -## Structure - -`Subscription` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | The subscription unique id within Chargify. | -| `State` | [`*models.SubscriptionState`](../../doc/models/subscription-state.md) | Optional | The state of a subscription.

* **Live States**
* `active` - A normal, active subscription. It is not in a trial and is paid and up to date.
* `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state.
* `paused` - An internal state that indicates that your account with Advanced Billing is in arrears.
* **Problem States**
* `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers.
* `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed.
* `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`.
* **End of Life States**
* `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription.
While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance.
* `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period.
* `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.)
* `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time.
* `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state.
* `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details.

See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. | -| `BalanceInCents` | `*int64` | Optional | Gives the current outstanding subscription balance in the number of cents. | -| `TotalRevenueInCents` | `*int64` | Optional | Gives the total revenue from the subscription in the number of cents. | -| `ProductPriceInCents` | `*int64` | Optional | (Added Nov 5 2013) The recurring amount of the product (and version),currently subscribed. NOTE: this may differ from the current price of,the product, if you’ve changed the price of the product but haven’t,moved this subscription to a newer version. | -| `ProductVersionNumber` | `*int` | Optional | The version of the product for the subscription. Note that this is a deprecated field kept for backwards-compatibility. | -| `CurrentPeriodEndsAt` | `*time.Time` | Optional | Timestamp relating to the end of the current (recurring) period (i.e.,when the next regularly scheduled attempted charge will occur) | -| `NextAssessmentAt` | `*time.Time` | Optional | Timestamp that indicates when capture of payment will be tried or,retried. This value will usually track the current_period_ends_at, but,will diverge if a renewal payment fails and must be retried. In that,case, the current_period_ends_at will advance to the end of the next,period (time doesn’t stop because a payment was missed) but the,next_assessment_at will be scheduled for the auto-retry time (i.e. 24,hours in the future, in some cases) | -| `TrialStartedAt` | `Optional[time.Time]` | Optional | Timestamp for when the trial period (if any) began | -| `TrialEndedAt` | `Optional[time.Time]` | Optional | Timestamp for when the trial period (if any) ended | -| `ActivatedAt` | `*time.Time` | Optional | Timestamp for when the subscription began (i.e. when it came out of trial, or when it began in the case of no trial) | -| `ExpiresAt` | `Optional[time.Time]` | Optional | Timestamp giving the expiration date of this subscription (if any) | -| `CreatedAt` | `*time.Time` | Optional | The creation date for this subscription | -| `UpdatedAt` | `*time.Time` | Optional | The date of last update for this subscription | -| `CancellationMessage` | `Optional[string]` | Optional | Seller-provided reason for, or note about, the cancellation. | -| `CancellationMethod` | [`Optional[models.CancellationMethod]`](../../doc/models/cancellation-method.md) | Optional | The process used to cancel the subscription, if the subscription has been canceled. It is nil if the subscription's state is not canceled. | -| `CancelAtEndOfPeriod` | `Optional[bool]` | Optional | Whether or not the subscription will (or has) canceled at the end of the period. | -| `CanceledAt` | `Optional[time.Time]` | Optional | The timestamp of the most recent cancellation | -| `CurrentPeriodStartedAt` | `*time.Time` | Optional | Timestamp relating to the start of the current (recurring) period | -| `PreviousState` | [`*models.SubscriptionState`](../../doc/models/subscription-state.md) | Optional | Only valid for webhook payloads The previous state for webhooks that have indicated a change in state. For normal API calls, this will always be the same as the state (current state) | -| `SignupPaymentId` | `*int` | Optional | The ID of the transaction that generated the revenue | -| `SignupRevenue` | `*string` | Optional | The revenue, formatted as a string of decimal separated dollars and,cents, from the subscription signup ($50.00 would be formatted as,50.00) | -| `DelayedCancelAt` | `Optional[time.Time]` | Optional | Timestamp for when the subscription is currently set to cancel. | -| `CouponCode` | `Optional[string]` | Optional | (deprecated) The coupon code of the single coupon currently applied to the subscription. See coupon_codes instead as subscriptions can now have more than one coupon. | -| `SnapDay` | `Optional[string]` | Optional | The day of the month that the subscription will charge according to calendar billing rules, if used. | -| `PaymentCollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | -| `Customer` | [`*models.Customer`](../../doc/models/customer.md) | Optional | - | -| `Product` | [`*models.Product`](../../doc/models/product.md) | Optional | - | -| `CreditCard` | [`*models.CreditCardPaymentProfile`](../../doc/models/credit-card-payment-profile.md) | Optional | - | -| `Group` | [`Optional[models.NestedSubscriptionGroup]`](../../doc/models/nested-subscription-group.md) | Optional | - | -| `BankAccount` | [`*models.BankAccountPaymentProfile`](../../doc/models/bank-account-payment-profile.md) | Optional | - | -| `PaymentType` | `Optional[string]` | Optional | The payment profile type for the active profile on file. | -| `ReferralCode` | `Optional[string]` | Optional | The subscription's unique code that can be given to referrals. | -| `NextProductId` | `Optional[int]` | Optional | If a delayed product change is scheduled, the ID of the product that the subscription will be changed to at the next renewal. | -| `NextProductHandle` | `Optional[string]` | Optional | If a delayed product change is scheduled, the handle of the product that the subscription will be changed to at the next renewal. | -| `CouponUseCount` | `Optional[int]` | Optional | (deprecated) How many times the subscription's single coupon has been used. This field has no replacement for multiple coupons. | -| `CouponUsesAllowed` | `Optional[int]` | Optional | (deprecated) How many times the subscription's single coupon may be used. This field has no replacement for multiple coupons. | -| `ReasonCode` | `Optional[string]` | Optional | If the subscription is canceled, this is their churn code. | -| `AutomaticallyResumeAt` | `Optional[time.Time]` | Optional | The date the subscription is scheduled to automatically resume from the on_hold state. | -| `CouponCodes` | `[]string` | Optional | An array for all the coupons attached to the subscription. | -| `OfferId` | `Optional[int]` | Optional | The ID of the offer associated with the subscription. | -| `PayerId` | `Optional[int]` | Optional | On Relationship Invoicing, the ID of the individual paying for the subscription. Defaults to the Customer ID unless the 'Customer Hierarchies & WhoPays' feature is enabled. | -| `CurrentBillingAmountInCents` | `*int64` | Optional | The balance in cents plus the estimated renewal amount in cents. | -| `ProductPricePointId` | `*int` | Optional | The product price point currently subscribed to. | -| `ProductPricePointType` | [`*models.PricePointType`](../../doc/models/price-point-type.md) | Optional | Price point type. We expose the following types:

1. **default**: a price point that is marked as a default price for a certain product.
2. **custom**: a custom price point.
3. **catalog**: a price point that is **not** marked as a default price for a certain product and is **not** a custom one. | -| `NextProductPricePointId` | `Optional[int]` | Optional | If a delayed product change is scheduled, the ID of the product price point that the subscription will be changed to at the next renewal. | -| `NetTerms` | `Optional[int]` | Optional | On Relationship Invoicing, the number of days before a renewal invoice is due. | -| `StoredCredentialTransactionId` | `Optional[int]` | Optional | For European sites subject to PSD2 and using 3D Secure, this can be used to reference a previous transaction for the customer. This will ensure the card will be charged successfully at renewal. | -| `Reference` | `Optional[string]` | Optional | The reference value (provided by your app) for the subscription itelf. | -| `OnHoldAt` | `Optional[time.Time]` | Optional | The timestamp of the most recent on hold action. | -| `PrepaidDunning` | `*bool` | Optional | Boolean representing whether the subscription is prepaid and currently in dunning. Only returned for Relationship Invoicing sites with the feature enabled | -| `Coupons` | [`[]models.SubscriptionIncludedCoupon`](../../doc/models/subscription-included-coupon.md) | Optional | Additional coupon data. To use this data you also have to include the following param in the request`include[]=coupons`.
Only in Read Subscription Endpoint. | -| `DunningCommunicationDelayEnabled` | `*bool` | Optional | Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute. | -| `DunningCommunicationDelayTimeZone` | `Optional[string]` | Optional | Time zone for the Dunning Communication Delay feature. | -| `ReceivesInvoiceEmails` | `Optional[bool]` | Optional | - | -| `Locale` | `Optional[string]` | Optional | - | -| `Currency` | `*string` | Optional | - | -| `ScheduledCancellationAt` | `Optional[time.Time]` | Optional | - | -| `CreditBalanceInCents` | `*int64` | Optional | - | -| `PrepaymentBalanceInCents` | `*int64` | Optional | - | -| `PrepaidConfiguration` | [`*models.PrepaidConfiguration`](../../doc/models/prepaid-configuration.md) | Optional | - | -| `SelfServicePageToken` | `*string` | Optional | Returned only for list/read Subscription operation when `include[]=self_service_page_token` parameter is provided. | - -## Example (as JSON) - -```json -{ - "payment_collection_method": "automatic", - "credit_card": { - "id": 10088716, - "first_name": "Test", - "last_name": "Subscription", - "masked_card_number": "XXXX-XXXX-XXXX-1", - "card_type": "bogus", - "expiration_month": 1, - "expiration_year": 2022, - "customer_id": 14543792, - "current_vault": "bogus", - "vault_token": "1", - "billing_address": "123 Montana Way", - "billing_city": "Billings", - "billing_state": "MT", - "billing_zip": "59101", - "billing_country": "US", - "customer_vault_token": null, - "billing_address_2": "", - "payment_type": "credit_card", - "site_gateway_setting_id": 1, - "gateway_handle": null - }, - "dunning_communication_delay_time_zone": "\"Eastern Time (US & Canada)\"", - "id": 96, - "state": "soft_failure", - "balance_in_cents": 212, - "total_revenue_in_cents": 136, - "product_price_in_cents": 70 -} -``` - + +# Subscription + +## Structure + +`Subscription` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | The subscription unique id within Chargify. | +| `State` | [`*models.SubscriptionState`](../../doc/models/subscription-state.md) | Optional | The state of a subscription.

* **Live States**
* `active` - A normal, active subscription. It is not in a trial and is paid and up to date.
* `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed.
* `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state.
* `paused` - An internal state that indicates that your account with Advanced Billing is in arrears.
* **Problem States**
* `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers.
* `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed.
* `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`.
* **End of Life States**
* `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription.
While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance.
* `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period.
* `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.)
* `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time.
* `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state.
* `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details.

See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. | +| `BalanceInCents` | `*int64` | Optional | Gives the current outstanding subscription balance in the number of cents. | +| `TotalRevenueInCents` | `*int64` | Optional | Gives the total revenue from the subscription in the number of cents. | +| `ProductPriceInCents` | `*int64` | Optional | (Added Nov 5 2013) The recurring amount of the product (and version),currently subscribed. NOTE: this may differ from the current price of,the product, if you’ve changed the price of the product but haven’t,moved this subscription to a newer version. | +| `ProductVersionNumber` | `*int` | Optional | The version of the product for the subscription. Note that this is a deprecated field kept for backwards-compatibility. | +| `CurrentPeriodEndsAt` | `*time.Time` | Optional | Timestamp relating to the end of the current (recurring) period (i.e.,when the next regularly scheduled attempted charge will occur) | +| `NextAssessmentAt` | `*time.Time` | Optional | Timestamp that indicates when capture of payment will be tried or,retried. This value will usually track the current_period_ends_at, but,will diverge if a renewal payment fails and must be retried. In that,case, the current_period_ends_at will advance to the end of the next,period (time doesn’t stop because a payment was missed) but the,next_assessment_at will be scheduled for the auto-retry time (i.e. 24,hours in the future, in some cases) | +| `TrialStartedAt` | `models.Optional[time.Time]` | Optional | Timestamp for when the trial period (if any) began | +| `TrialEndedAt` | `models.Optional[time.Time]` | Optional | Timestamp for when the trial period (if any) ended | +| `ActivatedAt` | `*time.Time` | Optional | Timestamp for when the subscription began (i.e. when it came out of trial, or when it began in the case of no trial) | +| `ExpiresAt` | `models.Optional[time.Time]` | Optional | Timestamp giving the expiration date of this subscription (if any) | +| `CreatedAt` | `*time.Time` | Optional | The creation date for this subscription | +| `UpdatedAt` | `*time.Time` | Optional | The date of last update for this subscription | +| `CancellationMessage` | `models.Optional[string]` | Optional | Seller-provided reason for, or note about, the cancellation. | +| `CancellationMethod` | [`models.Optional[models.CancellationMethod]`](../../doc/models/cancellation-method.md) | Optional | The process used to cancel the subscription, if the subscription has been canceled. It is nil if the subscription's state is not canceled. | +| `CancelAtEndOfPeriod` | `models.Optional[bool]` | Optional | Whether or not the subscription will (or has) canceled at the end of the period. | +| `CanceledAt` | `models.Optional[time.Time]` | Optional | The timestamp of the most recent cancellation | +| `CurrentPeriodStartedAt` | `*time.Time` | Optional | Timestamp relating to the start of the current (recurring) period | +| `PreviousState` | [`*models.SubscriptionState`](../../doc/models/subscription-state.md) | Optional | Only valid for webhook payloads The previous state for webhooks that have indicated a change in state. For normal API calls, this will always be the same as the state (current state) | +| `SignupPaymentId` | `*int` | Optional | The ID of the transaction that generated the revenue | +| `SignupRevenue` | `*string` | Optional | The revenue, formatted as a string of decimal separated dollars and,cents, from the subscription signup ($50.00 would be formatted as,50.00) | +| `DelayedCancelAt` | `models.Optional[time.Time]` | Optional | Timestamp for when the subscription is currently set to cancel. | +| `CouponCode` | `models.Optional[string]` | Optional | (deprecated) The coupon code of the single coupon currently applied to the subscription. See coupon_codes instead as subscriptions can now have more than one coupon. | +| `SnapDay` | `models.Optional[string]` | Optional | The day of the month that the subscription will charge according to calendar billing rules, if used. | +| `PaymentCollectionMethod` | [`*models.CollectionMethod`](../../doc/models/collection-method.md) | Optional | The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`.
**Default**: `"automatic"` | +| `Customer` | [`*models.Customer`](../../doc/models/customer.md) | Optional | - | +| `Product` | [`*models.Product`](../../doc/models/product.md) | Optional | - | +| `CreditCard` | [`*models.CreditCardPaymentProfile`](../../doc/models/credit-card-payment-profile.md) | Optional | - | +| `Group` | [`models.Optional[models.SubscriptionGroup2]`](../../doc/models/containers/subscription-group-2.md) | Optional | This is a container for one-of cases. | +| `BankAccount` | [`*models.BankAccountPaymentProfile`](../../doc/models/bank-account-payment-profile.md) | Optional | - | +| `PaymentType` | `models.Optional[string]` | Optional | The payment profile type for the active profile on file. | +| `ReferralCode` | `models.Optional[string]` | Optional | The subscription's unique code that can be given to referrals. | +| `NextProductId` | `models.Optional[int]` | Optional | If a delayed product change is scheduled, the ID of the product that the subscription will be changed to at the next renewal. | +| `NextProductHandle` | `models.Optional[string]` | Optional | If a delayed product change is scheduled, the handle of the product that the subscription will be changed to at the next renewal. | +| `CouponUseCount` | `models.Optional[int]` | Optional | (deprecated) How many times the subscription's single coupon has been used. This field has no replacement for multiple coupons. | +| `CouponUsesAllowed` | `models.Optional[int]` | Optional | (deprecated) How many times the subscription's single coupon may be used. This field has no replacement for multiple coupons. | +| `ReasonCode` | `models.Optional[string]` | Optional | If the subscription is canceled, this is their churn code. | +| `AutomaticallyResumeAt` | `models.Optional[time.Time]` | Optional | The date the subscription is scheduled to automatically resume from the on_hold state. | +| `CouponCodes` | `[]string` | Optional | An array for all the coupons attached to the subscription. | +| `OfferId` | `models.Optional[int]` | Optional | The ID of the offer associated with the subscription. | +| `PayerId` | `models.Optional[int]` | Optional | On Relationship Invoicing, the ID of the individual paying for the subscription. Defaults to the Customer ID unless the 'Customer Hierarchies & WhoPays' feature is enabled. | +| `CurrentBillingAmountInCents` | `*int64` | Optional | The balance in cents plus the estimated renewal amount in cents. | +| `ProductPricePointId` | `*int` | Optional | The product price point currently subscribed to. | +| `ProductPricePointType` | [`*models.PricePointType`](../../doc/models/price-point-type.md) | Optional | Price point type. We expose the following types:

1. **default**: a price point that is marked as a default price for a certain product.
2. **custom**: a custom price point.
3. **catalog**: a price point that is **not** marked as a default price for a certain product and is **not** a custom one. | +| `NextProductPricePointId` | `models.Optional[int]` | Optional | If a delayed product change is scheduled, the ID of the product price point that the subscription will be changed to at the next renewal. | +| `NetTerms` | `models.Optional[int]` | Optional | On Relationship Invoicing, the number of days before a renewal invoice is due. | +| `StoredCredentialTransactionId` | `models.Optional[int]` | Optional | For European sites subject to PSD2 and using 3D Secure, this can be used to reference a previous transaction for the customer. This will ensure the card will be charged successfully at renewal. | +| `Reference` | `models.Optional[string]` | Optional | The reference value (provided by your app) for the subscription itelf. | +| `OnHoldAt` | `models.Optional[time.Time]` | Optional | The timestamp of the most recent on hold action. | +| `PrepaidDunning` | `*bool` | Optional | Boolean representing whether the subscription is prepaid and currently in dunning. Only returned for Relationship Invoicing sites with the feature enabled | +| `Coupons` | [`[]models.SubscriptionIncludedCoupon`](../../doc/models/subscription-included-coupon.md) | Optional | Additional coupon data. To use this data you also have to include the following param in the request`include[]=coupons`.
Only in Read Subscription Endpoint. | +| `DunningCommunicationDelayEnabled` | `*bool` | Optional | Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute. | +| `DunningCommunicationDelayTimeZone` | `models.Optional[string]` | Optional | Time zone for the Dunning Communication Delay feature. | +| `ReceivesInvoiceEmails` | `models.Optional[bool]` | Optional | - | +| `Locale` | `models.Optional[string]` | Optional | - | +| `Currency` | `*string` | Optional | - | +| `ScheduledCancellationAt` | `models.Optional[time.Time]` | Optional | - | +| `CreditBalanceInCents` | `*int64` | Optional | - | +| `PrepaymentBalanceInCents` | `*int64` | Optional | - | +| `PrepaidConfiguration` | [`*models.PrepaidConfiguration`](../../doc/models/prepaid-configuration.md) | Optional | - | +| `SelfServicePageToken` | `*string` | Optional | Returned only for list/read Subscription operation when `include[]=self_service_page_token` parameter is provided. | + +## Example (as JSON) + +```json +{ + "payment_collection_method": "automatic", + "credit_card": { + "id": 10088716, + "first_name": "Test", + "last_name": "Subscription", + "masked_card_number": "XXXX-XXXX-XXXX-1", + "card_type": "bogus", + "expiration_month": 1, + "expiration_year": 2022, + "customer_id": 14543792, + "current_vault": "bogus", + "vault_token": "1", + "billing_address": "123 Montana Way", + "billing_city": "Billings", + "billing_state": "MT", + "billing_zip": "59101", + "billing_country": "US", + "customer_vault_token": null, + "billing_address_2": "", + "payment_type": "credit_card", + "site_gateway_setting_id": 1, + "gateway_handle": null + }, + "dunning_communication_delay_time_zone": "\"Eastern Time (US & Canada)\"", + "id": 96, + "state": "soft_failure", + "balance_in_cents": 212, + "total_revenue_in_cents": 136, + "product_price_in_cents": 70 +} +``` + diff --git a/doc/models/subscriptions-mrr-error-response-exception.md b/doc/models/subscriptions-mrr-error-response-exception.md index 51f4d1a4..c02ecdb9 100644 --- a/doc/models/subscriptions-mrr-error-response-exception.md +++ b/doc/models/subscriptions-mrr-error-response-exception.md @@ -1,25 +1,25 @@ - -# Subscriptions Mrr Error Response Exception - -## Structure - -`SubscriptionsMrrErrorResponseException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`models.AttributeError`](../../doc/models/attribute-error.md) | Required | - | - -## Example (as JSON) - -```json -{ - "errors": { - "attribute": [ - "supplied value is invalid, expected ISO 8601 format" - ] - } -} -``` - + +# Subscriptions Mrr Error Response Exception + +## Structure + +`SubscriptionsMrrErrorResponseException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`models.AttributeError`](../../doc/models/attribute-error.md) | Required | - | + +## Example (as JSON) + +```json +{ + "errors": { + "attribute": [ + "supplied value is invalid, expected ISO 8601 format" + ] + } +} +``` + diff --git a/doc/models/tax-configuration-kind.md b/doc/models/tax-configuration-kind.md index b53ff33e..3876d0cb 100644 --- a/doc/models/tax-configuration-kind.md +++ b/doc/models/tax-configuration-kind.md @@ -1,16 +1,16 @@ - -# Tax Configuration Kind - -## Enumeration - -`TaxConfigurationKind` - -## Fields - -| Name | -| --- | -| `CUSTOM` | -| `ENUMMANAGEDAVALARA` | -| `ENUMLINKEDAVALARA` | -| `ENUMDIGITALRIVER` | - + +# Tax Configuration Kind + +## Enumeration + +`TaxConfigurationKind` + +## Fields + +| Name | +| --- | +| `CUSTOM` | +| `ENUMMANAGEDAVALARA` | +| `ENUMLINKEDAVALARA` | +| `ENUMDIGITALRIVER` | + diff --git a/doc/models/tax-configuration.md b/doc/models/tax-configuration.md index 8498cf5e..364cdfd8 100644 --- a/doc/models/tax-configuration.md +++ b/doc/models/tax-configuration.md @@ -1,25 +1,25 @@ - -# Tax Configuration - -## Structure - -`TaxConfiguration` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Kind` | [`*models.TaxConfigurationKind`](../../doc/models/tax-configuration-kind.md) | Optional | **Default**: `"custom"` | -| `DestinationAddress` | [`*models.TaxDestinationAddress`](../../doc/models/tax-destination-address.md) | Optional | - | -| `FullyConfigured` | `*bool` | Optional | Returns `true` when Chargify has been properly configured to charge tax using the specified tax system. More details about taxes: https://maxio-chargify.zendesk.com/hc/en-us/articles/5405488905869-Taxes-Introduction
**Default**: `false` | - -## Example (as JSON) - -```json -{ - "kind": "custom", - "fully_configured": false, - "destination_address": "shipping_only" -} -``` - + +# Tax Configuration + +## Structure + +`TaxConfiguration` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Kind` | [`*models.TaxConfigurationKind`](../../doc/models/tax-configuration-kind.md) | Optional | **Default**: `"custom"` | +| `DestinationAddress` | [`*models.TaxDestinationAddress`](../../doc/models/tax-destination-address.md) | Optional | - | +| `FullyConfigured` | `*bool` | Optional | Returns `true` when Chargify has been properly configured to charge tax using the specified tax system. More details about taxes: https://maxio-chargify.zendesk.com/hc/en-us/articles/5405488905869-Taxes-Introduction
**Default**: `false` | + +## Example (as JSON) + +```json +{ + "kind": "custom", + "fully_configured": false, + "destination_address": "shipping_only" +} +``` + diff --git a/doc/models/tax-destination-address.md b/doc/models/tax-destination-address.md index 81a9db3c..15eb501a 100644 --- a/doc/models/tax-destination-address.md +++ b/doc/models/tax-destination-address.md @@ -1,16 +1,16 @@ - -# Tax Destination Address - -## Enumeration - -`TaxDestinationAddress` - -## Fields - -| Name | -| --- | -| `SHIPPINGTHENBILLING` | -| `BILLINGTHENSHIPPING` | -| `SHIPPINGONLY` | -| `BILLINGONLY` | - + +# Tax Destination Address + +## Enumeration + +`TaxDestinationAddress` + +## Fields + +| Name | +| --- | +| `SHIPPINGTHENBILLING` | +| `BILLINGTHENSHIPPING` | +| `SHIPPINGONLY` | +| `BILLINGONLY` | + diff --git a/doc/models/too-many-management-link-requests-error-exception.md b/doc/models/too-many-management-link-requests-error-exception.md index 61bb0183..4f781ca3 100644 --- a/doc/models/too-many-management-link-requests-error-exception.md +++ b/doc/models/too-many-management-link-requests-error-exception.md @@ -1,24 +1,24 @@ - -# Too Many Management Link Requests Error Exception - -## Structure - -`TooManyManagementLinkRequestsErrorException` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Errors` | [`models.TooManyManagementLinkRequests`](../../doc/models/too-many-management-link-requests.md) | Required | - | - -## Example (as JSON) - -```json -{ - "errors": { - "error": "error4", - "new_link_available_at": "2016-03-13T12:52:32.123Z" - } -} -``` - + +# Too Many Management Link Requests Error Exception + +## Structure + +`TooManyManagementLinkRequestsErrorException` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Errors` | [`models.TooManyManagementLinkRequests`](../../doc/models/too-many-management-link-requests.md) | Required | - | + +## Example (as JSON) + +```json +{ + "errors": { + "error": "error4", + "new_link_available_at": "2016-03-13T12:52:32.123Z" + } +} +``` + diff --git a/doc/models/too-many-management-link-requests.md b/doc/models/too-many-management-link-requests.md index 92d57495..d45e2c2e 100644 --- a/doc/models/too-many-management-link-requests.md +++ b/doc/models/too-many-management-link-requests.md @@ -1,23 +1,23 @@ - -# Too Many Management Link Requests - -## Structure - -`TooManyManagementLinkRequests` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Error` | `string` | Required | - | -| `NewLinkAvailableAt` | `time.Time` | Required | - | - -## Example (as JSON) - -```json -{ - "error": "error2", - "new_link_available_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Too Many Management Link Requests + +## Structure + +`TooManyManagementLinkRequests` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Error` | `string` | Required | - | +| `NewLinkAvailableAt` | `time.Time` | Required | - | + +## Example (as JSON) + +```json +{ + "error": "error2", + "new_link_available_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/update-allocation-expiration-date.md b/doc/models/update-allocation-expiration-date.md index 7e0b73c9..c08d166a 100644 --- a/doc/models/update-allocation-expiration-date.md +++ b/doc/models/update-allocation-expiration-date.md @@ -1,23 +1,23 @@ - -# Update Allocation Expiration Date - -## Structure - -`UpdateAllocationExpirationDate` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Allocation` | [`*models.AllocationExpirationDate`](../../doc/models/allocation-expiration-date.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "allocation": { - "expires_at": "2016-03-13T12:52:32.123Z" - } -} -``` - + +# Update Allocation Expiration Date + +## Structure + +`UpdateAllocationExpirationDate` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Allocation` | [`*models.AllocationExpirationDate`](../../doc/models/allocation-expiration-date.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "allocation": { + "expires_at": "2016-03-13T12:52:32.123Z" + } +} +``` + diff --git a/doc/models/update-component-price-point-request.md b/doc/models/update-component-price-point-request.md index 2be8bc1e..02e2c433 100644 --- a/doc/models/update-component-price-point-request.md +++ b/doc/models/update-component-price-point-request.md @@ -1,27 +1,27 @@ - -# Update Component Price Point Request - -## Structure - -`UpdateComponentPricePointRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoint` | [`*models.UpdateComponentPricePoint`](../../doc/models/update-component-price-point.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "price_point": { - "name": "name0", - "handle": "handle6", - "pricing_scheme": "per_unit", - "use_site_exchange_rate": false, - "tax_included": false - } -} -``` - + +# Update Component Price Point Request + +## Structure + +`UpdateComponentPricePointRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoint` | [`*models.UpdateComponentPricePoint`](../../doc/models/update-component-price-point.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "price_point": { + "name": "name0", + "handle": "handle6", + "pricing_scheme": "per_unit", + "use_site_exchange_rate": false, + "tax_included": false + } +} +``` + diff --git a/doc/models/update-component-price-point.md b/doc/models/update-component-price-point.md index a5bfdc11..8436143d 100644 --- a/doc/models/update-component-price-point.md +++ b/doc/models/update-component-price-point.md @@ -1,32 +1,32 @@ - -# Update Component Price Point - -## Structure - -`UpdateComponentPricePoint` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Name` | `*string` | Optional | - | -| `Handle` | `*string` | Optional | - | -| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `UseSiteExchangeRate` | `*bool` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. | -| `TaxIncluded` | `*bool` | Optional | Whether or not the price point includes tax | -| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | -| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | -| `Prices` | [`[]models.UpdatePrice`](../../doc/models/update-price.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "name": "name2", - "handle": "handle8", - "pricing_scheme": "per_unit", - "use_site_exchange_rate": false, - "tax_included": false -} -``` - + +# Update Component Price Point + +## Structure + +`UpdateComponentPricePoint` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Name` | `*string` | Optional | - | +| `Handle` | `*string` | Optional | - | +| `PricingScheme` | [`*models.PricingScheme`](../../doc/models/pricing-scheme.md) | Optional | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `UseSiteExchangeRate` | `*bool` | Optional | Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. | +| `TaxIncluded` | `*bool` | Optional | Whether or not the price point includes tax | +| `Interval` | `*int` | Optional | The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. | +| `IntervalUnit` | [`*models.IntervalUnit`](../../doc/models/interval-unit.md) | Optional | A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. | +| `Prices` | [`[]models.UpdatePrice`](../../doc/models/update-price.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "name": "name2", + "handle": "handle8", + "pricing_scheme": "per_unit", + "use_site_exchange_rate": false, + "tax_included": false +} +``` + diff --git a/doc/models/update-component-request.md b/doc/models/update-component-request.md index 35bdbea1..85ca8d17 100644 --- a/doc/models/update-component-request.md +++ b/doc/models/update-component-request.md @@ -1,28 +1,28 @@ - -# Update Component Request - -## Structure - -`UpdateComponentRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Component` | [`models.UpdateComponent`](../../doc/models/update-component.md) | Required | - | - -## Example (as JSON) - -```json -{ - "component": { - "item_category": "Business Software", - "handle": "handle4", - "name": "name8", - "description": "description2", - "accounting_code": "accounting_code4", - "taxable": false - } -} -``` - + +# Update Component Request + +## Structure + +`UpdateComponentRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Component` | [`models.UpdateComponent`](../../doc/models/update-component.md) | Required | - | + +## Example (as JSON) + +```json +{ + "component": { + "item_category": "Business Software", + "handle": "handle4", + "name": "name8", + "description": "description2", + "accounting_code": "accounting_code4", + "taxable": false + } +} +``` + diff --git a/doc/models/update-component.md b/doc/models/update-component.md index e9ef488b..f6a6efbe 100644 --- a/doc/models/update-component.md +++ b/doc/models/update-component.md @@ -1,34 +1,34 @@ - -# Update Component - -## Structure - -`UpdateComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Handle` | `*string` | Optional | - | -| `Name` | `*string` | Optional | The name of the Component, suitable for display on statements. i.e. Text Messages. | -| `Description` | `Optional[string]` | Optional | The description of the component. | -| `AccountingCode` | `Optional[string]` | Optional | - | -| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | -| `TaxCode` | `Optional[string]` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | -| `ItemCategory` | [`Optional[models.ItemCategory]`](../../doc/models/item-category.md) | Optional | One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other | -| `DisplayOnHostedPage` | `*bool` | Optional | - | -| `UpgradeCharge` | [`Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | - -## Example (as JSON) - -```json -{ - "item_category": "Business Software", - "handle": "handle6", - "name": "name0", - "description": "description0", - "accounting_code": "accounting_code6", - "taxable": false -} -``` - + +# Update Component + +## Structure + +`UpdateComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Handle` | `*string` | Optional | - | +| `Name` | `*string` | Optional | The name of the Component, suitable for display on statements. i.e. Text Messages. | +| `Description` | `models.Optional[string]` | Optional | The description of the component. | +| `AccountingCode` | `models.Optional[string]` | Optional | - | +| `Taxable` | `*bool` | Optional | Boolean flag describing whether a component is taxable or not. | +| `TaxCode` | `models.Optional[string]` | Optional | A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. | +| `ItemCategory` | [`models.Optional[models.ItemCategory]`](../../doc/models/item-category.md) | Optional | One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other | +| `DisplayOnHostedPage` | `*bool` | Optional | - | +| `UpgradeCharge` | [`models.Optional[models.CreditType]`](../../doc/models/credit-type.md) | Optional | The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided.
Available values: `full`, `prorated`, `none`. | + +## Example (as JSON) + +```json +{ + "item_category": "Business Software", + "handle": "handle6", + "name": "name0", + "description": "description0", + "accounting_code": "accounting_code6", + "taxable": false +} +``` + diff --git a/doc/models/update-coupon-currency.md b/doc/models/update-coupon-currency.md index 0180b461..80894edc 100644 --- a/doc/models/update-coupon-currency.md +++ b/doc/models/update-coupon-currency.md @@ -1,23 +1,23 @@ - -# Update Coupon Currency - -## Structure - -`UpdateCouponCurrency` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Currency` | `string` | Required | ISO code for the site defined currency. | -| `Price` | `int` | Required | Price for the given currency. | - -## Example (as JSON) - -```json -{ - "currency": "currency4", - "price": 146 -} -``` - + +# Update Coupon Currency + +## Structure + +`UpdateCouponCurrency` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Currency` | `string` | Required | ISO code for the site defined currency. | +| `Price` | `int` | Required | Price for the given currency. | + +## Example (as JSON) + +```json +{ + "currency": "currency4", + "price": 146 +} +``` + diff --git a/doc/models/update-currency-price.md b/doc/models/update-currency-price.md index 26c9b602..4c2d3cd7 100644 --- a/doc/models/update-currency-price.md +++ b/doc/models/update-currency-price.md @@ -1,23 +1,23 @@ - -# Update Currency Price - -## Structure - -`UpdateCurrencyPrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `int` | Required | ID of the currency price record being updated | -| `Price` | `int` | Required | New price for the given currency | - -## Example (as JSON) - -```json -{ - "id": 146, - "price": 18 -} -``` - + +# Update Currency Price + +## Structure + +`UpdateCurrencyPrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `int` | Required | ID of the currency price record being updated | +| `Price` | `int` | Required | New price for the given currency | + +## Example (as JSON) + +```json +{ + "id": 146, + "price": 18 +} +``` + diff --git a/doc/models/update-currency-prices-request.md b/doc/models/update-currency-prices-request.md index ced2a386..818744d5 100644 --- a/doc/models/update-currency-prices-request.md +++ b/doc/models/update-currency-prices-request.md @@ -1,26 +1,26 @@ - -# Update Currency Prices Request - -## Structure - -`UpdateCurrencyPricesRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CurrencyPrices` | [`[]models.UpdateCurrencyPrice`](../../doc/models/update-currency-price.md) | Required | - | - -## Example (as JSON) - -```json -{ - "currency_prices": [ - { - "id": 50, - "price": 78 - } - ] -} -``` - + +# Update Currency Prices Request + +## Structure + +`UpdateCurrencyPricesRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrencyPrices` | [`[]models.UpdateCurrencyPrice`](../../doc/models/update-currency-price.md) | Required | - | + +## Example (as JSON) + +```json +{ + "currency_prices": [ + { + "id": 50, + "price": 78 + } + ] +} +``` + diff --git a/doc/models/update-customer-request.md b/doc/models/update-customer-request.md index b1dffa87..54a1bd07 100644 --- a/doc/models/update-customer-request.md +++ b/doc/models/update-customer-request.md @@ -1,27 +1,27 @@ - -# Update Customer Request - -## Structure - -`UpdateCustomerRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Customer` | [`models.UpdateCustomer`](../../doc/models/update-customer.md) | Required | - | - -## Example (as JSON) - -```json -{ - "customer": { - "first_name": "first_name0", - "last_name": "last_name8", - "email": "email6", - "cc_emails": "cc_emails0", - "organization": "organization6" - } -} -``` - + +# Update Customer Request + +## Structure + +`UpdateCustomerRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Customer` | [`models.UpdateCustomer`](../../doc/models/update-customer.md) | Required | - | + +## Example (as JSON) + +```json +{ + "customer": { + "first_name": "first_name0", + "last_name": "last_name8", + "email": "email6", + "cc_emails": "cc_emails0", + "organization": "organization6" + } +} +``` + diff --git a/doc/models/update-customer.md b/doc/models/update-customer.md index 9bee0211..51fbd945 100644 --- a/doc/models/update-customer.md +++ b/doc/models/update-customer.md @@ -1,42 +1,42 @@ - -# Update Customer - -## Structure - -`UpdateCustomer` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `FirstName` | `*string` | Optional | - | -| `LastName` | `*string` | Optional | - | -| `Email` | `*string` | Optional | - | -| `CcEmails` | `*string` | Optional | - | -| `Organization` | `*string` | Optional | - | -| `Reference` | `*string` | Optional | - | -| `Address` | `*string` | Optional | - | -| `Address2` | `*string` | Optional | - | -| `City` | `*string` | Optional | - | -| `State` | `*string` | Optional | - | -| `Zip` | `*string` | Optional | - | -| `Country` | `*string` | Optional | - | -| `Phone` | `*string` | Optional | - | -| `Locale` | `*string` | Optional | Set a specific language on a customer record. | -| `VatNumber` | `*string` | Optional | - | -| `TaxExempt` | `*bool` | Optional | - | -| `TaxExemptReason` | `*string` | Optional | - | -| `ParentId` | `Optional[int]` | Optional | - | - -## Example (as JSON) - -```json -{ - "first_name": "first_name2", - "last_name": "last_name0", - "email": "email4", - "cc_emails": "cc_emails8", - "organization": "organization6" -} -``` - + +# Update Customer + +## Structure + +`UpdateCustomer` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FirstName` | `*string` | Optional | - | +| `LastName` | `*string` | Optional | - | +| `Email` | `*string` | Optional | - | +| `CcEmails` | `*string` | Optional | - | +| `Organization` | `*string` | Optional | - | +| `Reference` | `*string` | Optional | - | +| `Address` | `*string` | Optional | - | +| `Address2` | `*string` | Optional | - | +| `City` | `*string` | Optional | - | +| `State` | `*string` | Optional | - | +| `Zip` | `*string` | Optional | - | +| `Country` | `*string` | Optional | - | +| `Phone` | `*string` | Optional | - | +| `Locale` | `*string` | Optional | Set a specific language on a customer record. | +| `VatNumber` | `*string` | Optional | - | +| `TaxExempt` | `*bool` | Optional | - | +| `TaxExemptReason` | `*string` | Optional | - | +| `ParentId` | `models.Optional[int]` | Optional | - | + +## Example (as JSON) + +```json +{ + "first_name": "first_name2", + "last_name": "last_name0", + "email": "email4", + "cc_emails": "cc_emails8", + "organization": "organization6" +} +``` + diff --git a/doc/models/update-metadata-request.md b/doc/models/update-metadata-request.md index 5b83d480..de8cf310 100644 --- a/doc/models/update-metadata-request.md +++ b/doc/models/update-metadata-request.md @@ -1,25 +1,25 @@ - -# Update Metadata Request - -## Structure - -`UpdateMetadataRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Metadata` | [`*models.UpdateMetadata`](../../doc/models/update-metadata.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "metadata": { - "current_name": "current_name0", - "name": "name6", - "value": "value8" - } -} -``` - + +# Update Metadata Request + +## Structure + +`UpdateMetadataRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Metadata` | [`*models.UpdateMetadata`](../../doc/models/update-metadata.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "metadata": { + "current_name": "current_name0", + "name": "name6", + "value": "value8" + } +} +``` + diff --git a/doc/models/update-metadata.md b/doc/models/update-metadata.md index 8f11d512..e558f442 100644 --- a/doc/models/update-metadata.md +++ b/doc/models/update-metadata.md @@ -1,25 +1,25 @@ - -# Update Metadata - -## Structure - -`UpdateMetadata` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CurrentName` | `*string` | Optional | - | -| `Name` | `*string` | Optional | - | -| `Value` | `*string` | Optional | - | - -## Example (as JSON) - -```json -{ - "current_name": "current_name4", - "name": "name0", - "value": "value2" -} -``` - + +# Update Metadata + +## Structure + +`UpdateMetadata` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrentName` | `*string` | Optional | - | +| `Name` | `*string` | Optional | - | +| `Value` | `*string` | Optional | - | + +## Example (as JSON) + +```json +{ + "current_name": "current_name4", + "name": "name0", + "value": "value2" +} +``` + diff --git a/doc/models/update-metafield.md b/doc/models/update-metafield.md new file mode 100644 index 00000000..8be4d515 --- /dev/null +++ b/doc/models/update-metafield.md @@ -0,0 +1,37 @@ + +# Update Metafield + +## Structure + +`UpdateMetafield` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CurrentName` | `*string` | Optional | - | +| `Name` | `*string` | Optional | - | +| `Scope` | [`*models.MetafieldScope`](../../doc/models/metafield-scope.md) | Optional | Warning: When updating a metafield's scope attribute, all scope attributes must be passed. Partially complete scope attributes will override the existing settings. | +| `InputType` | [`*models.MetafieldInput`](../../doc/models/metafield-input.md) | Optional | Indicates how data should be added to the metafield. For example, a text type is just a string, so a given metafield of this type can have any value attached. On the other hand, dropdown and radio have a set of allowed values that can be input, and appear differently on a Public Signup Page. Defaults to 'text' | +| `Enum` | `[]string` | Optional | Only applicable when input_type is radio or dropdown | + +## Example (as JSON) + +```json +{ + "current_name": "current_name0", + "name": "name6", + "scope": { + "csv": "0", + "invoices": "0", + "statements": "0", + "portal": "0", + "public_show": "0" + }, + "input_type": "balance_tracker", + "enum": [ + "enum2" + ] +} +``` + diff --git a/doc/models/update-metafields-request.md b/doc/models/update-metafields-request.md index d7c9cc84..ca3a0dfe 100644 --- a/doc/models/update-metafields-request.md +++ b/doc/models/update-metafields-request.md @@ -1,24 +1,35 @@ - -# Update Metafields Request - -## Structure - -`UpdateMetafieldsRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Metafields` | `*interface{}` | Optional | - | - -## Example (as JSON) - -```json -{ - "metafields": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Update Metafields Request + +## Structure + +`UpdateMetafieldsRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Metafields` | [`*models.UpdateMetafieldsRequestMetafields`](../../doc/models/containers/update-metafields-request-metafields.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "metafields": { + "current_name": "current_name0", + "name": "name6", + "scope": { + "csv": "0", + "invoices": "0", + "statements": "0", + "portal": "0", + "public_show": "0" + }, + "input_type": "balance_tracker", + "enum": [ + "enum2" + ] + } +} +``` + diff --git a/doc/models/update-payment-profile-request.md b/doc/models/update-payment-profile-request.md index 615013e4..d21a593a 100644 --- a/doc/models/update-payment-profile-request.md +++ b/doc/models/update-payment-profile-request.md @@ -1,27 +1,27 @@ - -# Update Payment Profile Request - -## Structure - -`UpdatePaymentProfileRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PaymentProfile` | [`models.UpdatePaymentProfile`](../../doc/models/update-payment-profile.md) | Required | - | - -## Example (as JSON) - -```json -{ - "payment_profile": { - "full_number": "5424000000000015", - "first_name": "first_name4", - "last_name": "last_name2", - "card_type": "bogus", - "expiration_month": "expiration_month0" - } -} -``` - + +# Update Payment Profile Request + +## Structure + +`UpdatePaymentProfileRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PaymentProfile` | [`models.UpdatePaymentProfile`](../../doc/models/update-payment-profile.md) | Required | - | + +## Example (as JSON) + +```json +{ + "payment_profile": { + "full_number": "5424000000000015", + "first_name": "first_name4", + "last_name": "last_name2", + "card_type": "bogus", + "expiration_month": "expiration_month0" + } +} +``` + diff --git a/doc/models/update-payment-profile.md b/doc/models/update-payment-profile.md index 9be5bc01..f039cc72 100644 --- a/doc/models/update-payment-profile.md +++ b/doc/models/update-payment-profile.md @@ -1,37 +1,37 @@ - -# Update Payment Profile - -## Structure - -`UpdatePaymentProfile` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `FirstName` | `*string` | Optional | The first name of the card holder. | -| `LastName` | `*string` | Optional | The last name of the card holder. | -| `FullNumber` | `*string` | Optional | The full credit card number | -| `CardType` | [`*models.CardType`](../../doc/models/card-type.md) | Optional | The type of card used. | -| `ExpirationMonth` | `*string` | Optional | (Optional when performing an Import via vault_token, required otherwise) The 1- or 2-digit credit card expiration month, as an integer or string, i.e. 5 | -| `ExpirationYear` | `*string` | Optional | (Optional when performing a Import via vault_token, required otherwise) The 4-digit credit card expiration year, as an integer or string, i.e. 2012 | -| `CurrentVault` | [`*models.CurrentVault`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | -| `BillingAddress` | `*string` | Optional | The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. | -| `BillingCity` | `*string` | Optional | The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. | -| `BillingState` | `*string` | Optional | The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. | -| `BillingZip` | `*string` | Optional | The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. | -| `BillingCountry` | `*string` | Optional | The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. | -| `BillingAddress2` | `Optional[string]` | Optional | Second line of the customer’s billing address i.e. Apt. 100 | - -## Example (as JSON) - -```json -{ - "full_number": "5424000000000015", - "first_name": "first_name2", - "last_name": "last_name0", - "card_type": "carnet", - "expiration_month": "expiration_month2" -} -``` - + +# Update Payment Profile + +## Structure + +`UpdatePaymentProfile` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `FirstName` | `*string` | Optional | The first name of the card holder. | +| `LastName` | `*string` | Optional | The last name of the card holder. | +| `FullNumber` | `*string` | Optional | The full credit card number | +| `CardType` | [`*models.CardType`](../../doc/models/card-type.md) | Optional | The type of card used. | +| `ExpirationMonth` | `*string` | Optional | (Optional when performing an Import via vault_token, required otherwise) The 1- or 2-digit credit card expiration month, as an integer or string, i.e. 5 | +| `ExpirationYear` | `*string` | Optional | (Optional when performing a Import via vault_token, required otherwise) The 4-digit credit card expiration year, as an integer or string, i.e. 2012 | +| `CurrentVault` | [`*models.CurrentVault`](../../doc/models/current-vault.md) | Optional | The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. | +| `BillingAddress` | `*string` | Optional | The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. | +| `BillingCity` | `*string` | Optional | The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. | +| `BillingState` | `*string` | Optional | The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. | +| `BillingZip` | `*string` | Optional | The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. | +| `BillingCountry` | `*string` | Optional | The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. | +| `BillingAddress2` | `models.Optional[string]` | Optional | Second line of the customer’s billing address i.e. Apt. 100 | + +## Example (as JSON) + +```json +{ + "full_number": "5424000000000015", + "first_name": "first_name2", + "last_name": "last_name0", + "card_type": "carnet", + "expiration_month": "expiration_month2" +} +``` + diff --git a/doc/models/update-price.md b/doc/models/update-price.md index acceeb39..8cdd7b7b 100644 --- a/doc/models/update-price.md +++ b/doc/models/update-price.md @@ -1,38 +1,29 @@ - -# Update Price - -## Structure - -`UpdatePrice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int` | Optional | - | -| `EndingQuantity` | `*interface{}` | Optional | - | -| `UnitPrice` | `*interface{}` | Optional | The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 | -| `Destroy` | `*bool` | Optional | - | -| `StartingQuantity` | `*interface{}` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 18, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - }, - "_destroy": false, - "starting_quantity": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Update Price + +## Structure + +`UpdatePrice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int` | Optional | - | +| `EndingQuantity` | [`*models.UpdatePriceEndingQuantity`](../../doc/models/containers/update-price-ending-quantity.md) | Optional | This is a container for one-of cases. | +| `UnitPrice` | [`*models.UpdatePriceUnitPrice`](../../doc/models/containers/update-price-unit-price.md) | Optional | This is a container for one-of cases. | +| `Destroy` | `*bool` | Optional | - | +| `StartingQuantity` | [`*models.UpdatePriceStartingQuantity`](../../doc/models/containers/update-price-starting-quantity.md) | Optional | This is a container for one-of cases. | + +## Example (as JSON) + +```json +{ + "id": 18, + "ending_quantity": 216, + "unit_price": 166.62, + "_destroy": false, + "starting_quantity": 242 +} +``` + diff --git a/doc/models/update-product-price-point-request.md b/doc/models/update-product-price-point-request.md index 3e027b8c..ea20d387 100644 --- a/doc/models/update-product-price-point-request.md +++ b/doc/models/update-product-price-point-request.md @@ -1,24 +1,24 @@ - -# Update Product Price Point Request - -## Structure - -`UpdateProductPricePointRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricePoint` | [`models.UpdateProductPricePoint`](../../doc/models/update-product-price-point.md) | Required | - | - -## Example (as JSON) - -```json -{ - "price_point": { - "handle": "handle6", - "price_in_cents": 196 - } -} -``` - + +# Update Product Price Point Request + +## Structure + +`UpdateProductPricePointRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricePoint` | [`models.UpdateProductPricePoint`](../../doc/models/update-product-price-point.md) | Required | - | + +## Example (as JSON) + +```json +{ + "price_point": { + "handle": "handle6", + "price_in_cents": 196 + } +} +``` + diff --git a/doc/models/update-product-price-point.md b/doc/models/update-product-price-point.md index c9f38e79..f1619124 100644 --- a/doc/models/update-product-price-point.md +++ b/doc/models/update-product-price-point.md @@ -1,23 +1,23 @@ - -# Update Product Price Point - -## Structure - -`UpdateProductPricePoint` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Handle` | `*string` | Optional | - | -| `PriceInCents` | `*int64` | Optional | - | - -## Example (as JSON) - -```json -{ - "handle": "handle6", - "price_in_cents": 220 -} -``` - + +# Update Product Price Point + +## Structure + +`UpdateProductPricePoint` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Handle` | `*string` | Optional | - | +| `PriceInCents` | `*int64` | Optional | - | + +## Example (as JSON) + +```json +{ + "handle": "handle6", + "price_in_cents": 220 +} +``` + diff --git a/doc/models/update-reason-code-request.md b/doc/models/update-reason-code-request.md index a40cd489..753955d5 100644 --- a/doc/models/update-reason-code-request.md +++ b/doc/models/update-reason-code-request.md @@ -1,25 +1,25 @@ - -# Update Reason Code Request - -## Structure - -`UpdateReasonCodeRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ReasonCode` | [`models.UpdateReasonCode`](../../doc/models/update-reason-code.md) | Required | - | - -## Example (as JSON) - -```json -{ - "reason_code": { - "code": "code4", - "description": "description6", - "position": 14 - } -} -``` - + +# Update Reason Code Request + +## Structure + +`UpdateReasonCodeRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ReasonCode` | [`models.UpdateReasonCode`](../../doc/models/update-reason-code.md) | Required | - | + +## Example (as JSON) + +```json +{ + "reason_code": { + "code": "code4", + "description": "description6", + "position": 14 + } +} +``` + diff --git a/doc/models/update-reason-code.md b/doc/models/update-reason-code.md index 71db9120..3b55f604 100644 --- a/doc/models/update-reason-code.md +++ b/doc/models/update-reason-code.md @@ -1,25 +1,25 @@ - -# Update Reason Code - -## Structure - -`UpdateReasonCode` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Code` | `*string` | Optional | The unique identifier for the ReasonCode | -| `Description` | `*string` | Optional | The friendly summary of what the code signifies | -| `Position` | `*int` | Optional | The order that code appears in lists | - -## Example (as JSON) - -```json -{ - "code": "code0", - "description": "description8", - "position": 118 -} -``` - + +# Update Reason Code + +## Structure + +`UpdateReasonCode` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Code` | `*string` | Optional | The unique identifier for the ReasonCode | +| `Description` | `*string` | Optional | The friendly summary of what the code signifies | +| `Position` | `*int` | Optional | The order that code appears in lists | + +## Example (as JSON) + +```json +{ + "code": "code0", + "description": "description8", + "position": 118 +} +``` + diff --git a/doc/models/update-segment-request.md b/doc/models/update-segment-request.md index 31d9b785..c3145718 100644 --- a/doc/models/update-segment-request.md +++ b/doc/models/update-segment-request.md @@ -1,49 +1,40 @@ - -# Update Segment Request - -## Structure - -`UpdateSegmentRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Segment` | [`models.UpdateSegment`](../../doc/models/update-segment.md) | Required | - | - -## Example (as JSON) - -```json -{ - "segment": { - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - } -} -``` - + +# Update Segment Request + +## Structure + +`UpdateSegmentRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Segment` | [`models.UpdateSegment`](../../doc/models/update-segment.md) | Required | - | + +## Example (as JSON) + +```json +{ + "segment": { + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + }, + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + } + ] + } +} +``` + diff --git a/doc/models/update-segment.md b/doc/models/update-segment.md index e753926b..80010df6 100644 --- a/doc/models/update-segment.md +++ b/doc/models/update-segment.md @@ -1,32 +1,29 @@ - -# Update Segment - -## Structure - -`UpdateSegment` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | -| `Prices` | [`[]models.CreateOrUpdateSegmentPrice`](../../doc/models/create-or-update-segment-price.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "pricing_scheme": "stairstep", - "prices": [ - { - "starting_quantity": 64, - "ending_quantity": 38, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] -} -``` - + +# Update Segment + +## Structure + +`UpdateSegment` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PricingScheme` | [`models.PricingScheme`](../../doc/models/pricing-scheme.md) | Required | The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. | +| `Prices` | [`[]models.CreateOrUpdateSegmentPrice`](../../doc/models/create-or-update-segment-price.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "pricing_scheme": "stairstep", + "prices": [ + { + "starting_quantity": 64, + "ending_quantity": 38, + "unit_price": "String3" + } + ] +} +``` + diff --git a/doc/models/update-subscription-component.md b/doc/models/update-subscription-component.md index 282ca029..419f32c0 100644 --- a/doc/models/update-subscription-component.md +++ b/doc/models/update-subscription-component.md @@ -1,57 +1,39 @@ - -# Update Subscription Component - -## Structure - -`UpdateSubscriptionComponent` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `ComponentId` | `*int` | Optional | - | -| `CustomPrice` | [`*models.ComponentCustomPrice`](../../doc/models/component-custom-price.md) | Optional | Create or update custom pricing unique to the subscription. Used in place of `price_point_id`. | - -## Example (as JSON) - -```json -{ - "component_id": 244, - "custom_price": { - "pricing_scheme": "stairstep", - "interval": 66, - "interval_unit": "day", - "prices": [ - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - }, - { - "starting_quantity": { - "key1": "val1", - "key2": "val2" - }, - "ending_quantity": { - "key1": "val1", - "key2": "val2" - }, - "unit_price": { - "key1": "val1", - "key2": "val2" - } - } - ] - } -} -``` - + +# Update Subscription Component + +## Structure + +`UpdateSubscriptionComponent` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `ComponentId` | `*int` | Optional | - | +| `CustomPrice` | [`*models.ComponentCustomPrice`](../../doc/models/component-custom-price.md) | Optional | Create or update custom pricing unique to the subscription. Used in place of `price_point_id`. | + +## Example (as JSON) + +```json +{ + "component_id": 244, + "custom_price": { + "pricing_scheme": "stairstep", + "interval": 66, + "interval_unit": "day", + "prices": [ + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + }, + { + "starting_quantity": 242, + "ending_quantity": 40, + "unit_price": 23.26 + } + ] + } +} +``` + diff --git a/doc/models/update-subscription-group-request.md b/doc/models/update-subscription-group-request.md index b9ee7541..972efb80 100644 --- a/doc/models/update-subscription-group-request.md +++ b/doc/models/update-subscription-group-request.md @@ -1,26 +1,26 @@ - -# Update Subscription Group Request - -## Structure - -`UpdateSubscriptionGroupRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `SubscriptionGroup` | [`models.UpdateSubscriptionGroup`](../../doc/models/update-subscription-group.md) | Required | - | - -## Example (as JSON) - -```json -{ - "subscription_group": { - "member_ids": [ - 164, - 165 - ] - } -} -``` - + +# Update Subscription Group Request + +## Structure + +`UpdateSubscriptionGroupRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `SubscriptionGroup` | [`models.UpdateSubscriptionGroup`](../../doc/models/update-subscription-group.md) | Required | - | + +## Example (as JSON) + +```json +{ + "subscription_group": { + "member_ids": [ + 164, + 165 + ] + } +} +``` + diff --git a/doc/models/update-subscription-group.md b/doc/models/update-subscription-group.md index 84c1fadd..21b9e040 100644 --- a/doc/models/update-subscription-group.md +++ b/doc/models/update-subscription-group.md @@ -1,25 +1,25 @@ - -# Update Subscription Group - -## Structure - -`UpdateSubscriptionGroup` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `MemberIds` | `[]int` | Optional | - | - -## Example (as JSON) - -```json -{ - "member_ids": [ - 52, - 53, - 54 - ] -} -``` - + +# Update Subscription Group + +## Structure + +`UpdateSubscriptionGroup` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `MemberIds` | `[]int` | Optional | - | + +## Example (as JSON) + +```json +{ + "member_ids": [ + 52, + 53, + 54 + ] +} +``` + diff --git a/doc/models/update-subscription-note-request.md b/doc/models/update-subscription-note-request.md index 0d12434b..0772d887 100644 --- a/doc/models/update-subscription-note-request.md +++ b/doc/models/update-subscription-note-request.md @@ -1,26 +1,26 @@ - -# Update Subscription Note Request - -Updatable fields for Subscription Note - -## Structure - -`UpdateSubscriptionNoteRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Note` | [`models.UpdateSubscriptionNote`](../../doc/models/update-subscription-note.md) | Required | Updatable fields for Subscription Note | - -## Example (as JSON) - -```json -{ - "note": { - "body": "body0", - "sticky": false - } -} -``` - + +# Update Subscription Note Request + +Updatable fields for Subscription Note + +## Structure + +`UpdateSubscriptionNoteRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Note` | [`models.UpdateSubscriptionNote`](../../doc/models/update-subscription-note.md) | Required | Updatable fields for Subscription Note | + +## Example (as JSON) + +```json +{ + "note": { + "body": "body0", + "sticky": false + } +} +``` + diff --git a/doc/models/update-subscription-note.md b/doc/models/update-subscription-note.md index 000da34b..212af79b 100644 --- a/doc/models/update-subscription-note.md +++ b/doc/models/update-subscription-note.md @@ -1,25 +1,25 @@ - -# Update Subscription Note - -Updatable fields for Subscription Note - -## Structure - -`UpdateSubscriptionNote` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Body` | `string` | Required | - | -| `Sticky` | `bool` | Required | - | - -## Example (as JSON) - -```json -{ - "body": "body8", - "sticky": false -} -``` - + +# Update Subscription Note + +Updatable fields for Subscription Note + +## Structure + +`UpdateSubscriptionNote` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Body` | `string` | Required | - | +| `Sticky` | `bool` | Required | - | + +## Example (as JSON) + +```json +{ + "body": "body8", + "sticky": false +} +``` + diff --git a/doc/models/update-subscription-request.md b/doc/models/update-subscription-request.md index d3b355b9..3634765a 100644 --- a/doc/models/update-subscription-request.md +++ b/doc/models/update-subscription-request.md @@ -1,32 +1,32 @@ - -# Update Subscription Request - -## Structure - -`UpdateSubscriptionRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Subscription` | [`models.UpdateSubscription`](../../doc/models/update-subscription.md) | Required | - | - -## Example (as JSON) - -```json -{ - "subscription": { - "dunning_communication_delay_time_zone": "\"Eastern Time (US & Canada)\"", - "credit_card_attributes": { - "full_number": "full_number2", - "expiration_month": "expiration_month6", - "expiration_year": "expiration_year2" - }, - "product_handle": "product_handle6", - "product_id": 206, - "product_change_delayed": false, - "next_product_id": "next_product_id6" - } -} -``` - + +# Update Subscription Request + +## Structure + +`UpdateSubscriptionRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Subscription` | [`models.UpdateSubscription`](../../doc/models/update-subscription.md) | Required | - | + +## Example (as JSON) + +```json +{ + "subscription": { + "dunning_communication_delay_time_zone": "\"Eastern Time (US & Canada)\"", + "credit_card_attributes": { + "full_number": "full_number2", + "expiration_month": "expiration_month6", + "expiration_year": "expiration_year2" + }, + "product_handle": "product_handle6", + "product_id": 206, + "product_change_delayed": false, + "next_product_id": "next_product_id6" + } +} +``` + diff --git a/doc/models/update-subscription.md b/doc/models/update-subscription.md index 98a18b3f..5475731b 100644 --- a/doc/models/update-subscription.md +++ b/doc/models/update-subscription.md @@ -1,46 +1,46 @@ - -# Update Subscription - -## Structure - -`UpdateSubscription` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `CreditCardAttributes` | [`*models.CreditCardAttributes`](../../doc/models/credit-card-attributes.md) | Optional | - | -| `ProductHandle` | `*string` | Optional | Set to the handle of a different product to change the subscription's product | -| `ProductId` | `*int` | Optional | Set to the id of a different product to change the subscription's product | -| `ProductChangeDelayed` | `*bool` | Optional | - | -| `NextProductId` | `*string` | Optional | Set to an empty string to cancel a delayed product change. | -| `NextProductPricePointId` | `*string` | Optional | - | -| `SnapDay` | `*interface{}` | Optional | Use for subscriptions with product eligible for calendar billing only. Value can be 1-28 or 'end'. | -| `NextBillingAt` | `*time.Time` | Optional | - | -| `PaymentCollectionMethod` | `*string` | Optional | - | -| `ReceivesInvoiceEmails` | `*bool` | Optional | - | -| `NetTerms` | `*interface{}` | Optional | - | -| `StoredCredentialTransactionId` | `*int` | Optional | - | -| `Reference` | `*string` | Optional | - | -| `CustomPrice` | [`*models.SubscriptionCustomPrice`](../../doc/models/subscription-custom-price.md) | Optional | (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription | -| `Components` | [`[]models.UpdateSubscriptionComponent`](../../doc/models/update-subscription-component.md) | Optional | (Optional) An array of component ids and custom prices to be added to the subscription. | -| `DunningCommunicationDelayEnabled` | `Optional[bool]` | Optional | Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute. | -| `DunningCommunicationDelayTimeZone` | `Optional[string]` | Optional | Time zone for the Dunning Communication Delay feature. | - -## Example (as JSON) - -```json -{ - "dunning_communication_delay_time_zone": "\"Eastern Time (US & Canada)\"", - "credit_card_attributes": { - "full_number": "full_number2", - "expiration_month": "expiration_month6", - "expiration_year": "expiration_year2" - }, - "product_handle": "product_handle2", - "product_id": 114, - "product_change_delayed": false, - "next_product_id": "next_product_id8" -} -``` - + +# Update Subscription + +## Structure + +`UpdateSubscription` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CreditCardAttributes` | [`*models.CreditCardAttributes`](../../doc/models/credit-card-attributes.md) | Optional | - | +| `ProductHandle` | `*string` | Optional | Set to the handle of a different product to change the subscription's product | +| `ProductId` | `*int` | Optional | Set to the id of a different product to change the subscription's product | +| `ProductChangeDelayed` | `*bool` | Optional | - | +| `NextProductId` | `*string` | Optional | Set to an empty string to cancel a delayed product change. | +| `NextProductPricePointId` | `*string` | Optional | - | +| `SnapDay` | [`*models.UpdateSubscriptionSnapDay`](../../doc/models/containers/update-subscription-snap-day.md) | Optional | This is a container for one-of cases. | +| `NextBillingAt` | `*time.Time` | Optional | - | +| `PaymentCollectionMethod` | `*string` | Optional | - | +| `ReceivesInvoiceEmails` | `*bool` | Optional | - | +| `NetTerms` | [`*models.UpdateSubscriptionNetTerms`](../../doc/models/containers/update-subscription-net-terms.md) | Optional | This is a container for one-of cases. | +| `StoredCredentialTransactionId` | `*int` | Optional | - | +| `Reference` | `*string` | Optional | - | +| `CustomPrice` | [`*models.SubscriptionCustomPrice`](../../doc/models/subscription-custom-price.md) | Optional | (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription | +| `Components` | [`[]models.UpdateSubscriptionComponent`](../../doc/models/update-subscription-component.md) | Optional | (Optional) An array of component ids and custom prices to be added to the subscription. | +| `DunningCommunicationDelayEnabled` | `models.Optional[bool]` | Optional | Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute. | +| `DunningCommunicationDelayTimeZone` | `models.Optional[string]` | Optional | Time zone for the Dunning Communication Delay feature. | + +## Example (as JSON) + +```json +{ + "dunning_communication_delay_time_zone": "\"Eastern Time (US & Canada)\"", + "credit_card_attributes": { + "full_number": "full_number2", + "expiration_month": "expiration_month6", + "expiration_year": "expiration_year2" + }, + "product_handle": "product_handle2", + "product_id": 114, + "product_change_delayed": false, + "next_product_id": "next_product_id8" +} +``` + diff --git a/doc/models/upsert-prepaid-configuration-request.md b/doc/models/upsert-prepaid-configuration-request.md index 79687d57..1d3750d7 100644 --- a/doc/models/upsert-prepaid-configuration-request.md +++ b/doc/models/upsert-prepaid-configuration-request.md @@ -1,26 +1,26 @@ - -# Upsert Prepaid Configuration Request - -## Structure - -`UpsertPrepaidConfigurationRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `PrepaidConfiguration` | [`models.UpsertPrepaidConfiguration`](../../doc/models/upsert-prepaid-configuration.md) | Required | - | - -## Example (as JSON) - -```json -{ - "prepaid_configuration": { - "initial_funding_amount_in_cents": 74, - "replenish_to_amount_in_cents": 76, - "auto_replenish": false, - "replenish_threshold_amount_in_cents": 20 - } -} -``` - + +# Upsert Prepaid Configuration Request + +## Structure + +`UpsertPrepaidConfigurationRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `PrepaidConfiguration` | [`models.UpsertPrepaidConfiguration`](../../doc/models/upsert-prepaid-configuration.md) | Required | - | + +## Example (as JSON) + +```json +{ + "prepaid_configuration": { + "initial_funding_amount_in_cents": 74, + "replenish_to_amount_in_cents": 76, + "auto_replenish": false, + "replenish_threshold_amount_in_cents": 20 + } +} +``` + diff --git a/doc/models/upsert-prepaid-configuration.md b/doc/models/upsert-prepaid-configuration.md index 15f2341c..393b3108 100644 --- a/doc/models/upsert-prepaid-configuration.md +++ b/doc/models/upsert-prepaid-configuration.md @@ -1,27 +1,27 @@ - -# Upsert Prepaid Configuration - -## Structure - -`UpsertPrepaidConfiguration` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `InitialFundingAmountInCents` | `*int64` | Optional | - | -| `ReplenishToAmountInCents` | `*int64` | Optional | - | -| `AutoReplenish` | `*bool` | Optional | - | -| `ReplenishThresholdAmountInCents` | `*int64` | Optional | - | - -## Example (as JSON) - -```json -{ - "initial_funding_amount_in_cents": 40, - "replenish_to_amount_in_cents": 42, - "auto_replenish": false, - "replenish_threshold_amount_in_cents": 242 -} -``` - + +# Upsert Prepaid Configuration + +## Structure + +`UpsertPrepaidConfiguration` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `InitialFundingAmountInCents` | `*int64` | Optional | - | +| `ReplenishToAmountInCents` | `*int64` | Optional | - | +| `AutoReplenish` | `*bool` | Optional | - | +| `ReplenishThresholdAmountInCents` | `*int64` | Optional | - | + +## Example (as JSON) + +```json +{ + "initial_funding_amount_in_cents": 40, + "replenish_to_amount_in_cents": 42, + "auto_replenish": false, + "replenish_threshold_amount_in_cents": 242 +} +``` + diff --git a/doc/models/usage-response.md b/doc/models/usage-response.md index a40a4920..863fc99d 100644 --- a/doc/models/usage-response.md +++ b/doc/models/usage-response.md @@ -1,30 +1,27 @@ - -# Usage Response - -## Structure - -`UsageResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Usage` | [`models.Usage`](../../doc/models/usage.md) | Required | - | - -## Example (as JSON) - -```json -{ - "usage": { - "id": 150, - "memo": "memo2", - "created_at": "2016-03-13T12:52:32.123Z", - "price_point_id": 28, - "quantity": { - "key1": "val1", - "key2": "val2" - } - } -} -``` - + +# Usage Response + +## Structure + +`UsageResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Usage` | [`models.Usage`](../../doc/models/usage.md) | Required | - | + +## Example (as JSON) + +```json +{ + "usage": { + "id": 150, + "memo": "memo2", + "created_at": "2016-03-13T12:52:32.123Z", + "price_point_id": 28, + "quantity": 28 + } +} +``` + diff --git a/doc/models/usage.md b/doc/models/usage.md index 169bfdfa..97bfe260 100644 --- a/doc/models/usage.md +++ b/doc/models/usage.md @@ -1,36 +1,33 @@ - -# Usage - -## Structure - -`Usage` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Id` | `*int64` | Optional | **Constraints**: `>= 0` | -| `Memo` | `*string` | Optional | - | -| `CreatedAt` | `*time.Time` | Optional | - | -| `PricePointId` | `*int` | Optional | - | -| `Quantity` | `*interface{}` | Optional | - | -| `OverageQuantity` | `*int` | Optional | - | -| `ComponentId` | `*int` | Optional | - | -| `ComponentHandle` | `*string` | Optional | - | -| `SubscriptionId` | `*int` | Optional | - | - -## Example (as JSON) - -```json -{ - "id": 252, - "memo": "memo8", - "created_at": "2016-03-13T12:52:32.123Z", - "price_point_id": 126, - "quantity": { - "key1": "val1", - "key2": "val2" - } -} -``` - + +# Usage + +## Structure + +`Usage` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Id` | `*int64` | Optional | **Constraints**: `>= 0` | +| `Memo` | `*string` | Optional | - | +| `CreatedAt` | `*time.Time` | Optional | - | +| `PricePointId` | `*int` | Optional | - | +| `Quantity` | [`*models.UsageQuantity`](../../doc/models/containers/usage-quantity.md) | Optional | This is a container for one-of cases. | +| `OverageQuantity` | `*int` | Optional | - | +| `ComponentId` | `*int` | Optional | - | +| `ComponentHandle` | `*string` | Optional | - | +| `SubscriptionId` | `*int` | Optional | - | + +## Example (as JSON) + +```json +{ + "id": 252, + "memo": "memo8", + "created_at": "2016-03-13T12:52:32.123Z", + "price_point_id": 126, + "quantity": 130 +} +``` + diff --git a/doc/models/void-invoice-event-data.md b/doc/models/void-invoice-event-data.md new file mode 100644 index 00000000..de301f16 --- /dev/null +++ b/doc/models/void-invoice-event-data.md @@ -0,0 +1,39 @@ + +# Void Invoice Event Data + +Example schema for an `void_invoice` event + +## Structure + +`VoidInvoiceEventData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CreditNoteAttributes` | [`*models.VoidInvoiceEventDataCreditNoteAttributes`](../../doc/models/containers/void-invoice-event-data-credit-note-attributes.md) | Required | This is a container for one-of cases. | +| `Memo` | `*string` | Required | The memo provided during invoice voiding. | +| `AppliedAmount` | `*string` | Required | The amount of the void. | +| `TransactionTime` | `*time.Time` | Required | The time the refund was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" | +| `IsAdvanceInvoice` | `bool` | Required | If true, the invoice is an advance invoice. | +| `Reason` | `string` | Required | The reason for the void. | + +## Example (as JSON) + +```json +{ + "credit_note_attributes": { + "uid": "uid2", + "site_id": 218, + "customer_id": 74, + "subscription_id": 146, + "number": "number0" + }, + "memo": "memo6", + "applied_amount": "applied_amount6", + "transaction_time": "2016-03-13T12:52:32.123Z", + "is_advance_invoice": false, + "reason": "reason8" +} +``` + diff --git a/doc/models/void-invoice-request.md b/doc/models/void-invoice-request.md index 2b5bf910..e6422381 100644 --- a/doc/models/void-invoice-request.md +++ b/doc/models/void-invoice-request.md @@ -1,23 +1,23 @@ - -# Void Invoice Request - -## Structure - -`VoidInvoiceRequest` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Void` | [`models.VoidInvoice`](../../doc/models/void-invoice.md) | Required | - | - -## Example (as JSON) - -```json -{ - "void": { - "reason": "reason6" - } -} -``` - + +# Void Invoice Request + +## Structure + +`VoidInvoiceRequest` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Void` | [`models.VoidInvoice`](../../doc/models/void-invoice.md) | Required | - | + +## Example (as JSON) + +```json +{ + "void": { + "reason": "reason6" + } +} +``` + diff --git a/doc/models/void-invoice.md b/doc/models/void-invoice.md index d35cfc30..6b37f008 100644 --- a/doc/models/void-invoice.md +++ b/doc/models/void-invoice.md @@ -1,21 +1,21 @@ - -# Void Invoice - -## Structure - -`VoidInvoice` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Reason` | `string` | Required | **Constraints**: *Minimum Length*: `1` | - -## Example (as JSON) - -```json -{ - "reason": "reason2" -} -``` - + +# Void Invoice + +## Structure + +`VoidInvoice` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Reason` | `string` | Required | **Constraints**: *Minimum Length*: `1` | + +## Example (as JSON) + +```json +{ + "reason": "reason2" +} +``` + diff --git a/doc/models/void-remainder-event-data.md b/doc/models/void-remainder-event-data.md new file mode 100644 index 00000000..5e72824f --- /dev/null +++ b/doc/models/void-remainder-event-data.md @@ -0,0 +1,35 @@ + +# Void Remainder Event Data + +Example schema for an `void_remainder` event + +## Structure + +`VoidRemainderEventData` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `CreditNoteAttributes` | [`models.CreditNote`](../../doc/models/credit-note.md) | Required | - | +| `Memo` | `string` | Required | The memo provided during invoice remainder voiding. | +| `AppliedAmount` | `string` | Required | The amount of the void. | +| `TransactionTime` | `time.Time` | Required | The time the refund was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" | + +## Example (as JSON) + +```json +{ + "credit_note_attributes": { + "uid": "uid2", + "site_id": 72, + "customer_id": 184, + "subscription_id": 0, + "number": "number0" + }, + "memo": "memo6", + "applied_amount": "applied_amount4", + "transaction_time": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/models/webhook-order.md b/doc/models/webhook-order.md index a2b94bd0..09ab749e 100644 --- a/doc/models/webhook-order.md +++ b/doc/models/webhook-order.md @@ -1,14 +1,14 @@ - -# Webhook Order - -## Enumeration - -`WebhookOrder` - -## Fields - -| Name | -| --- | -| `NEWESTFIRST` | -| `OLDESTFIRST` | - + +# Webhook Order + +## Enumeration + +`WebhookOrder` + +## Fields + +| Name | +| --- | +| `NEWESTFIRST` | +| `OLDESTFIRST` | + diff --git a/doc/models/webhook-response.md b/doc/models/webhook-response.md index 1df7479a..6e8c7fd0 100644 --- a/doc/models/webhook-response.md +++ b/doc/models/webhook-response.md @@ -1,27 +1,27 @@ - -# Webhook Response - -## Structure - -`WebhookResponse` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Webhook` | [`*models.Webhook`](../../doc/models/webhook.md) | Optional | - | - -## Example (as JSON) - -```json -{ - "webhook": { - "event": "event2", - "id": 18, - "created_at": "2016-03-13T12:52:32.123Z", - "last_error": "last_error4", - "last_error_at": "2016-03-13T12:52:32.123Z" - } -} -``` - + +# Webhook Response + +## Structure + +`WebhookResponse` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Webhook` | [`*models.Webhook`](../../doc/models/webhook.md) | Optional | - | + +## Example (as JSON) + +```json +{ + "webhook": { + "event": "event2", + "id": 18, + "created_at": "2016-03-13T12:52:32.123Z", + "last_error": "last_error4", + "last_error_at": "2016-03-13T12:52:32.123Z" + } +} +``` + diff --git a/doc/models/webhook-status.md b/doc/models/webhook-status.md index 53b2214d..9202a9bf 100644 --- a/doc/models/webhook-status.md +++ b/doc/models/webhook-status.md @@ -1,16 +1,16 @@ - -# Webhook Status - -## Enumeration - -`WebhookStatus` - -## Fields - -| Name | -| --- | -| `SUCCESSFUL` | -| `FAILED` | -| `PENDING` | -| `PAUSED` | - + +# Webhook Status + +## Enumeration + +`WebhookStatus` + +## Fields + +| Name | +| --- | +| `SUCCESSFUL` | +| `FAILED` | +| `PENDING` | +| `PAUSED` | + diff --git a/doc/models/webhook-subscription.md b/doc/models/webhook-subscription.md index 00bf3825..19a54313 100644 --- a/doc/models/webhook-subscription.md +++ b/doc/models/webhook-subscription.md @@ -1,47 +1,47 @@ - -# Webhook Subscription - -## Enumeration - -`WebhookSubscription` - -## Fields - -| Name | -| --- | -| `BILLINGDATECHANGE` | -| `COMPONENTALLOCATIONCHANGE` | -| `CUSTOMERCREATE` | -| `CUSTOMERUPDATE` | -| `DUNNINGSTEPREACHED` | -| `EXPIRINGCARD` | -| `EXPIRATIONDATECHANGE` | -| `INVOICEISSUED` | -| `METEREDUSAGE` | -| `PAYMENTFAILURE` | -| `PAYMENTSUCCESS` | -| `DIRECTDEBITPAYMENTPENDING` | -| `DIRECTDEBITPAYMENTPAIDOUT` | -| `DIRECTDEBITPAYMENTREJECTED` | -| `PREPAIDSUBSCRIPTIONBALANCECHANGED` | -| `PREPAIDUSAGE` | -| `REFUNDFAILURE` | -| `REFUNDSUCCESS` | -| `RENEWALFAILURE` | -| `RENEWALSUCCESS` | -| `SIGNUPFAILURE` | -| `SIGNUPSUCCESS` | -| `STATEMENTCLOSED` | -| `STATEMENTSETTLED` | -| `SUBSCRIPTIONCARDUPDATE` | -| `SUBSCRIPTIONGROUPCARDUPDATE` | -| `SUBSCRIPTIONPRODUCTCHANGE` | -| `SUBSCRIPTIONSTATECHANGE` | -| `TRIALENDNOTICE` | -| `UPCOMINGRENEWALNOTICE` | -| `UPGRADEDOWNGRADEFAILURE` | -| `UPGRADEDOWNGRADESUCCESS` | -| `PENDINGCANCELLATIONCHANGE` | -| `SUBSCRIPTIONPREPAYMENTACCOUNTBALANCECHANGED` | -| `SUBSCRIPTIONSERVICECREDITACCOUNTBALANCECHANGED` | - + +# Webhook Subscription + +## Enumeration + +`WebhookSubscription` + +## Fields + +| Name | +| --- | +| `BILLINGDATECHANGE` | +| `COMPONENTALLOCATIONCHANGE` | +| `CUSTOMERCREATE` | +| `CUSTOMERUPDATE` | +| `DUNNINGSTEPREACHED` | +| `EXPIRINGCARD` | +| `EXPIRATIONDATECHANGE` | +| `INVOICEISSUED` | +| `METEREDUSAGE` | +| `PAYMENTFAILURE` | +| `PAYMENTSUCCESS` | +| `DIRECTDEBITPAYMENTPENDING` | +| `DIRECTDEBITPAYMENTPAIDOUT` | +| `DIRECTDEBITPAYMENTREJECTED` | +| `PREPAIDSUBSCRIPTIONBALANCECHANGED` | +| `PREPAIDUSAGE` | +| `REFUNDFAILURE` | +| `REFUNDSUCCESS` | +| `RENEWALFAILURE` | +| `RENEWALSUCCESS` | +| `SIGNUPFAILURE` | +| `SIGNUPSUCCESS` | +| `STATEMENTCLOSED` | +| `STATEMENTSETTLED` | +| `SUBSCRIPTIONCARDUPDATE` | +| `SUBSCRIPTIONGROUPCARDUPDATE` | +| `SUBSCRIPTIONPRODUCTCHANGE` | +| `SUBSCRIPTIONSTATECHANGE` | +| `TRIALENDNOTICE` | +| `UPCOMINGRENEWALNOTICE` | +| `UPGRADEDOWNGRADEFAILURE` | +| `UPGRADEDOWNGRADESUCCESS` | +| `PENDINGCANCELLATIONCHANGE` | +| `SUBSCRIPTIONPREPAYMENTACCOUNTBALANCECHANGED` | +| `SUBSCRIPTIONSERVICECREDITACCOUNTBALANCECHANGED` | + diff --git a/doc/models/webhook.md b/doc/models/webhook.md index 66a77b72..80a9561f 100644 --- a/doc/models/webhook.md +++ b/doc/models/webhook.md @@ -1,36 +1,36 @@ - -# Webhook - -## Structure - -`Webhook` - -## Fields - -| Name | Type | Tags | Description | -| --- | --- | --- | --- | -| `Event` | `*string` | Optional | A string describing which event type produced the given webhook | -| `Id` | `*int64` | Optional | The unique identifier for the webhooks (unique across all of Chargify). This is not changed on a retry/replay of the same webhook, so it may be used to avoid duplicate action for the same event. | -| `CreatedAt` | `*time.Time` | Optional | Timestamp indicating when the webhook was created | -| `LastError` | `*string` | Optional | Text describing the status code and/or error from the last failed attempt to send the Webhook. When a webhook is retried and accepted, this field will be cleared. | -| `LastErrorAt` | `*time.Time` | Optional | Timestamp indicating when the last non-acceptance occurred. If a webhook is later resent and accepted, this field will be cleared. | -| `AcceptedAt` | `Optional[time.Time]` | Optional | Timestamp indicating when the webhook was accepted by the merchant endpoint. When a webhook is explicitly replayed by the merchant, this value will be cleared until it is accepted again. | -| `LastSentAt` | `*time.Time` | Optional | Timestamp indicating when the most recent attempt was made to send the webhook | -| `LastSentUrl` | `*string` | Optional | The url that the endpoint was last sent to. | -| `Successful` | `*bool` | Optional | A boolean flag describing whether the webhook was accepted by the webhook endpoint for the most recent attempt. (Acceptance is defined by receiving a “200 OK” HTTP response within a reasonable timeframe, i.e. 15 seconds) | -| `Body` | `*string` | Optional | The data sent within the webhook post | -| `Signature` | `*string` | Optional | The calculated webhook signature | -| `SignatureHmacSha256` | `*string` | Optional | The calculated HMAC-SHA-256 webhook signature | - -## Example (as JSON) - -```json -{ - "event": "event6", - "id": 154, - "created_at": "2016-03-13T12:52:32.123Z", - "last_error": "last_error8", - "last_error_at": "2016-03-13T12:52:32.123Z" -} -``` - + +# Webhook + +## Structure + +`Webhook` + +## Fields + +| Name | Type | Tags | Description | +| --- | --- | --- | --- | +| `Event` | `*string` | Optional | A string describing which event type produced the given webhook | +| `Id` | `*int64` | Optional | The unique identifier for the webhooks (unique across all of Chargify). This is not changed on a retry/replay of the same webhook, so it may be used to avoid duplicate action for the same event. | +| `CreatedAt` | `*time.Time` | Optional | Timestamp indicating when the webhook was created | +| `LastError` | `*string` | Optional | Text describing the status code and/or error from the last failed attempt to send the Webhook. When a webhook is retried and accepted, this field will be cleared. | +| `LastErrorAt` | `*time.Time` | Optional | Timestamp indicating when the last non-acceptance occurred. If a webhook is later resent and accepted, this field will be cleared. | +| `AcceptedAt` | `models.Optional[time.Time]` | Optional | Timestamp indicating when the webhook was accepted by the merchant endpoint. When a webhook is explicitly replayed by the merchant, this value will be cleared until it is accepted again. | +| `LastSentAt` | `*time.Time` | Optional | Timestamp indicating when the most recent attempt was made to send the webhook | +| `LastSentUrl` | `*string` | Optional | The url that the endpoint was last sent to. | +| `Successful` | `*bool` | Optional | A boolean flag describing whether the webhook was accepted by the webhook endpoint for the most recent attempt. (Acceptance is defined by receiving a “200 OK” HTTP response within a reasonable timeframe, i.e. 15 seconds) | +| `Body` | `*string` | Optional | The data sent within the webhook post | +| `Signature` | `*string` | Optional | The calculated webhook signature | +| `SignatureHmacSha256` | `*string` | Optional | The calculated HMAC-SHA-256 webhook signature | + +## Example (as JSON) + +```json +{ + "event": "event6", + "id": 154, + "created_at": "2016-03-13T12:52:32.123Z", + "last_error": "last_error8", + "last_error_at": "2016-03-13T12:52:32.123Z" +} +``` + diff --git a/doc/retry-configuration.md b/doc/retry-configuration.md index ea77b12d..607fc171 100644 --- a/doc/retry-configuration.md +++ b/doc/retry-configuration.md @@ -1,22 +1,22 @@ - -# RetryConfiguration - -The following parameters are configurable for the RetryConfiguration: - -## Properties - -| Name | Type | Description | -| --- | --- | --- | -| `maxRetryAttempts` | `int64` | Maximum number of retries.
*Default*: `0` | -| `retryOnTimeout` | `bool` | Whether to retry on request timeout.
*Default*: `true` | -| `retryInterval` | `time.Duration` | Interval before next retry. Used in calculation of wait time for next request in case of failure.
*Default*: `1` | -| `maximumRetryWaitTime` | `time.Duration` | Overall wait time for the requests getting retried.
*Default*: `0` | -| `backoffFactor` | `int64` | Used in calculation of wait time for next request in case of failure.
*Default*: `2` | -| `httpStatusCodesToRetry` | `[]int64` | Http status codes to retry against.
*Default*: `[]int64{408, 413, 429, 500, 502, 503, 504, 521, 522, 524, 408, 413, 429, 500, 502, 503, 504, 521, 522, 524}` | -| `httpMethodsToRetry` | `[]string` | Http methods to retry against.
*Default*: `[]string{"GET", "PUT", "GET", "PUT"}` | - -The retryConfiguration can be initialized as follows: - + +# RetryConfiguration + +The following parameters are configurable for the RetryConfiguration: + +## Properties + +| Name | Type | Description | +| --- | --- | --- | +| `maxRetryAttempts` | `int64` | Maximum number of retries.
*Default*: `0` | +| `retryOnTimeout` | `bool` | Whether to retry on request timeout.
*Default*: `true` | +| `retryInterval` | `time.Duration` | Interval before next retry. Used in calculation of wait time for next request in case of failure.
*Default*: `1` | +| `maximumRetryWaitTime` | `time.Duration` | Overall wait time for the requests getting retried.
*Default*: `0` | +| `backoffFactor` | `int64` | Used in calculation of wait time for next request in case of failure.
*Default*: `2` | +| `httpStatusCodesToRetry` | `[]int64` | Http status codes to retry against.
*Default*: `[]int64{408, 413, 429, 500, 502, 503, 504, 521, 522, 524, 408, 413, 429, 500, 502, 503, 504, 521, 522, 524}` | +| `httpMethodsToRetry` | `[]string` | Http methods to retry against.
*Default*: `[]string{"GET", "PUT", "GET", "PUT"}` | + +The retryConfiguration can be initialized as follows: + ```go retryConfiguration := CreateRetryConfiguration( advancedbilling.WithMaxRetryAttempts(0), @@ -27,5 +27,5 @@ retryConfiguration := CreateRetryConfiguration( advancedbilling.WithHttpStatusCodesToRetry([]int64{408, 413, 429, 500, 502, 503, 504, 521, 522, 524, 408, 413, 429, 500, 502, 503, 504, 521, 522, 524}), advancedbilling.WithHttpMethodsToRetry([]string{"GET", "PUT", "GET", "PUT"}), ) -``` - +``` + diff --git a/errors/errors.go b/errors/errors.go index a9805e69..a31bd512 100644 --- a/errors/errors.go +++ b/errors/errors.go @@ -1,414 +1,432 @@ -/* -Package advancedbilling - -This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). */ package errors import ( - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/maxio-com/ab-golang-sdk/models" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/maxio-com/ab-golang-sdk/models" ) // ComponentAllocationError is a custom error. type ComponentAllocationError struct { - https.ApiError - Errors []models.ComponentAllocationErrorItem `json:"errors,omitempty"` + https.ApiError + Errors []models.ComponentAllocationErrorItem `json:"errors,omitempty"` } -// NewComponentAllocationError is a constructor for ComponentAllocationError. +// NewComponentAllocationError is a constructor for ComponentAllocationError. // It creates and returns a pointer to a new ComponentAllocationError instance with the given statusCode and body. func NewComponentAllocationError(apiError https.ApiError) error { - return &ComponentAllocationError{ApiError: apiError} + return &ComponentAllocationError{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for ComponentAllocationError. func (c *ComponentAllocationError) Error() string { - return fmt.Sprintf("ComponentAllocationError occured: %v", c.Message) + return fmt.Sprintf("ComponentAllocationError occured: %v", c.Message) } // ComponentPricePointError is a custom error. type ComponentPricePointError struct { - https.ApiError - Errors []models.ComponentPricePointErrorItem `json:"errors,omitempty"` + https.ApiError + Errors []models.ComponentPricePointErrorItem `json:"errors,omitempty"` } -// NewComponentPricePointError is a constructor for ComponentPricePointError. +// NewComponentPricePointError is a constructor for ComponentPricePointError. // It creates and returns a pointer to a new ComponentPricePointError instance with the given statusCode and body. func NewComponentPricePointError(apiError https.ApiError) error { - return &ComponentPricePointError{ApiError: apiError} + return &ComponentPricePointError{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for ComponentPricePointError. func (c *ComponentPricePointError) Error() string { - return fmt.Sprintf("ComponentPricePointError occured: %v", c.Message) + return fmt.Sprintf("ComponentPricePointError occured: %v", c.Message) } // CustomerErrorResponse is a custom error. type CustomerErrorResponse struct { - https.ApiError - Errors *interface{} `json:"errors,omitempty"` + https.ApiError + Errors *models.CustomerErrorResponseErrors `json:"errors,omitempty"` } -// NewCustomerErrorResponse is a constructor for CustomerErrorResponse. +// NewCustomerErrorResponse is a constructor for CustomerErrorResponse. // It creates and returns a pointer to a new CustomerErrorResponse instance with the given statusCode and body. func NewCustomerErrorResponse(apiError https.ApiError) error { - return &CustomerErrorResponse{ApiError: apiError} + return &CustomerErrorResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for CustomerErrorResponse. func (c *CustomerErrorResponse) Error() string { - return fmt.Sprintf("CustomerErrorResponse occured: %v", c.Message) + return fmt.Sprintf("CustomerErrorResponse occured: %v", c.Message) } // ErrorArrayMapResponse is a custom error. type ErrorArrayMapResponse struct { - https.ApiError - Errors map[string]interface{} `json:"errors,omitempty"` + https.ApiError + Errors map[string]interface{} `json:"errors,omitempty"` } -// NewErrorArrayMapResponse is a constructor for ErrorArrayMapResponse. +// NewErrorArrayMapResponse is a constructor for ErrorArrayMapResponse. // It creates and returns a pointer to a new ErrorArrayMapResponse instance with the given statusCode and body. func NewErrorArrayMapResponse(apiError https.ApiError) error { - return &ErrorArrayMapResponse{ApiError: apiError} + return &ErrorArrayMapResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for ErrorArrayMapResponse. func (e *ErrorArrayMapResponse) Error() string { - return fmt.Sprintf("ErrorArrayMapResponse occured: %v", e.Message) + return fmt.Sprintf("ErrorArrayMapResponse occured: %v", e.Message) } -// ErrorListResponse is a custom error. +// ErrorListResponse is a custom error. // Error which contains list of messages. type ErrorListResponse struct { - https.ApiError - Errors []string `json:"errors"` + https.ApiError + Errors []string `json:"errors"` } -// NewErrorListResponse is a constructor for ErrorListResponse. +// NewErrorListResponse is a constructor for ErrorListResponse. // It creates and returns a pointer to a new ErrorListResponse instance with the given statusCode and body. func NewErrorListResponse(apiError https.ApiError) error { - return &ErrorListResponse{ApiError: apiError} + return &ErrorListResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for ErrorListResponse. func (e *ErrorListResponse) Error() string { - return fmt.Sprintf("ErrorListResponse occured: %v", e.Message) + return fmt.Sprintf("ErrorListResponse occured: %v", e.Message) } // ErrorStringMapResponse is a custom error. type ErrorStringMapResponse struct { - https.ApiError - Errors map[string]string `json:"errors,omitempty"` + https.ApiError + Errors map[string]string `json:"errors,omitempty"` } -// NewErrorStringMapResponse is a constructor for ErrorStringMapResponse. +// NewErrorStringMapResponse is a constructor for ErrorStringMapResponse. // It creates and returns a pointer to a new ErrorStringMapResponse instance with the given statusCode and body. func NewErrorStringMapResponse(apiError https.ApiError) error { - return &ErrorStringMapResponse{ApiError: apiError} + return &ErrorStringMapResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for ErrorStringMapResponse. func (e *ErrorStringMapResponse) Error() string { - return fmt.Sprintf("ErrorStringMapResponse occured: %v", e.Message) + return fmt.Sprintf("ErrorStringMapResponse occured: %v", e.Message) } // EventBasedBillingListSegmentsErrors is a custom error. type EventBasedBillingListSegmentsErrors struct { - https.ApiError - Errors *models.Errors `json:"errors,omitempty"` + https.ApiError + Errors *models.Errors `json:"errors,omitempty"` } -// NewEventBasedBillingListSegmentsErrors is a constructor for EventBasedBillingListSegmentsErrors. +// NewEventBasedBillingListSegmentsErrors is a constructor for EventBasedBillingListSegmentsErrors. // It creates and returns a pointer to a new EventBasedBillingListSegmentsErrors instance with the given statusCode and body. func NewEventBasedBillingListSegmentsErrors(apiError https.ApiError) error { - return &EventBasedBillingListSegmentsErrors{ApiError: apiError} + return &EventBasedBillingListSegmentsErrors{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for EventBasedBillingListSegmentsErrors. func (e *EventBasedBillingListSegmentsErrors) Error() string { - return fmt.Sprintf("EventBasedBillingListSegmentsErrors occured: %v", e.Message) + return fmt.Sprintf("EventBasedBillingListSegmentsErrors occured: %v", e.Message) } // EventBasedBillingSegment is a custom error. type EventBasedBillingSegment struct { - https.ApiError - Errors models.EventBasedBillingSegmentError `json:"errors"` + https.ApiError + Errors models.EventBasedBillingSegmentError `json:"errors"` } -// NewEventBasedBillingSegment is a constructor for EventBasedBillingSegment. +// NewEventBasedBillingSegment is a constructor for EventBasedBillingSegment. // It creates and returns a pointer to a new EventBasedBillingSegment instance with the given statusCode and body. func NewEventBasedBillingSegment(apiError https.ApiError) error { - return &EventBasedBillingSegment{ApiError: apiError} + return &EventBasedBillingSegment{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for EventBasedBillingSegment. func (e *EventBasedBillingSegment) Error() string { - return fmt.Sprintf("EventBasedBillingSegment occured: %v", e.Message) + return fmt.Sprintf("EventBasedBillingSegment occured: %v", e.Message) } // EventBasedBillingSegmentErrors is a custom error. type EventBasedBillingSegmentErrors struct { - https.ApiError - Errors map[string]interface{} `json:"errors,omitempty"` + https.ApiError + Errors map[string]interface{} `json:"errors,omitempty"` } -// NewEventBasedBillingSegmentErrors is a constructor for EventBasedBillingSegmentErrors. +// NewEventBasedBillingSegmentErrors is a constructor for EventBasedBillingSegmentErrors. // It creates and returns a pointer to a new EventBasedBillingSegmentErrors instance with the given statusCode and body. func NewEventBasedBillingSegmentErrors(apiError https.ApiError) error { - return &EventBasedBillingSegmentErrors{ApiError: apiError} + return &EventBasedBillingSegmentErrors{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for EventBasedBillingSegmentErrors. func (e *EventBasedBillingSegmentErrors) Error() string { - return fmt.Sprintf("EventBasedBillingSegmentErrors occured: %v", e.Message) + return fmt.Sprintf("EventBasedBillingSegmentErrors occured: %v", e.Message) } // ProductPricePointErrorResponse is a custom error. type ProductPricePointErrorResponse struct { - https.ApiError - Errors models.ProductPricePointErrors `json:"errors"` + https.ApiError + Errors models.ProductPricePointErrors `json:"errors"` } -// NewProductPricePointErrorResponse is a constructor for ProductPricePointErrorResponse. +// NewProductPricePointErrorResponse is a constructor for ProductPricePointErrorResponse. // It creates and returns a pointer to a new ProductPricePointErrorResponse instance with the given statusCode and body. func NewProductPricePointErrorResponse(apiError https.ApiError) error { - return &ProductPricePointErrorResponse{ApiError: apiError} + return &ProductPricePointErrorResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for ProductPricePointErrorResponse. func (p *ProductPricePointErrorResponse) Error() string { - return fmt.Sprintf("ProductPricePointErrorResponse occured: %v", p.Message) + return fmt.Sprintf("ProductPricePointErrorResponse occured: %v", p.Message) } // ProformaBadRequestErrorResponse is a custom error. type ProformaBadRequestErrorResponse struct { - https.ApiError - Errors *models.ProformaError `json:"errors,omitempty"` + https.ApiError + Errors *models.ProformaError `json:"errors,omitempty"` } -// NewProformaBadRequestErrorResponse is a constructor for ProformaBadRequestErrorResponse. +// NewProformaBadRequestErrorResponse is a constructor for ProformaBadRequestErrorResponse. // It creates and returns a pointer to a new ProformaBadRequestErrorResponse instance with the given statusCode and body. func NewProformaBadRequestErrorResponse(apiError https.ApiError) error { - return &ProformaBadRequestErrorResponse{ApiError: apiError} + return &ProformaBadRequestErrorResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for ProformaBadRequestErrorResponse. func (p *ProformaBadRequestErrorResponse) Error() string { - return fmt.Sprintf("ProformaBadRequestErrorResponse occured: %v", p.Message) + return fmt.Sprintf("ProformaBadRequestErrorResponse occured: %v", p.Message) } -// RefundPrepaymentAggregatedErrorsResponse is a custom error. +// RefundPrepaymentAggregatedErrorsResponse is a custom error. // Errors returned on creating a refund prepayment, grouped by field, as arrays of strings. type RefundPrepaymentAggregatedErrorsResponse struct { - https.ApiError - Errors *models.RefundPrepaymentAggregatedError `json:"errors,omitempty"` + https.ApiError + Errors *models.RefundPrepaymentAggregatedError `json:"errors,omitempty"` } -// NewRefundPrepaymentAggregatedErrorsResponse is a constructor for RefundPrepaymentAggregatedErrorsResponse. +// NewRefundPrepaymentAggregatedErrorsResponse is a constructor for RefundPrepaymentAggregatedErrorsResponse. // It creates and returns a pointer to a new RefundPrepaymentAggregatedErrorsResponse instance with the given statusCode and body. func NewRefundPrepaymentAggregatedErrorsResponse(apiError https.ApiError) error { - return &RefundPrepaymentAggregatedErrorsResponse{ApiError: apiError} + return &RefundPrepaymentAggregatedErrorsResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for RefundPrepaymentAggregatedErrorsResponse. func (r *RefundPrepaymentAggregatedErrorsResponse) Error() string { - return fmt.Sprintf("RefundPrepaymentAggregatedErrorsResponse occured: %v", r.Message) + return fmt.Sprintf("RefundPrepaymentAggregatedErrorsResponse occured: %v", r.Message) } -// RefundPrepaymentBaseErrorsResponse is a custom error. +// RefundPrepaymentBaseErrorsResponse is a custom error. // Errors returned on creating a refund prepayment when bad request type RefundPrepaymentBaseErrorsResponse struct { - https.ApiError - Errors *models.RefundPrepaymentBaseRefundError `json:"errors,omitempty"` + https.ApiError + Errors *models.RefundPrepaymentBaseRefundError `json:"errors,omitempty"` } -// NewRefundPrepaymentBaseErrorsResponse is a constructor for RefundPrepaymentBaseErrorsResponse. +// NewRefundPrepaymentBaseErrorsResponse is a constructor for RefundPrepaymentBaseErrorsResponse. // It creates and returns a pointer to a new RefundPrepaymentBaseErrorsResponse instance with the given statusCode and body. func NewRefundPrepaymentBaseErrorsResponse(apiError https.ApiError) error { - return &RefundPrepaymentBaseErrorsResponse{ApiError: apiError} + return &RefundPrepaymentBaseErrorsResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for RefundPrepaymentBaseErrorsResponse. func (r *RefundPrepaymentBaseErrorsResponse) Error() string { - return fmt.Sprintf("RefundPrepaymentBaseErrorsResponse occured: %v", r.Message) + return fmt.Sprintf("RefundPrepaymentBaseErrorsResponse occured: %v", r.Message) } // SingleErrorResponse is a custom error. type SingleErrorResponse struct { - https.ApiError - MError string `json:"error"` + https.ApiError + MError string `json:"error"` } -// NewSingleErrorResponse is a constructor for SingleErrorResponse. +// NewSingleErrorResponse is a constructor for SingleErrorResponse. // It creates and returns a pointer to a new SingleErrorResponse instance with the given statusCode and body. func NewSingleErrorResponse(apiError https.ApiError) error { - return &SingleErrorResponse{ApiError: apiError} + return &SingleErrorResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for SingleErrorResponse. func (s *SingleErrorResponse) Error() string { - return fmt.Sprintf("SingleErrorResponse occured: %v", s.Message) + return fmt.Sprintf("SingleErrorResponse occured: %v", s.Message) } // SingleStringErrorResponse is a custom error. type SingleStringErrorResponse struct { - https.ApiError - Errors *string `json:"errors,omitempty"` + https.ApiError + Errors *string `json:"errors,omitempty"` } -// NewSingleStringErrorResponse is a constructor for SingleStringErrorResponse. +// NewSingleStringErrorResponse is a constructor for SingleStringErrorResponse. // It creates and returns a pointer to a new SingleStringErrorResponse instance with the given statusCode and body. func NewSingleStringErrorResponse(apiError https.ApiError) error { - return &SingleStringErrorResponse{ApiError: apiError} + return &SingleStringErrorResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for SingleStringErrorResponse. func (s *SingleStringErrorResponse) Error() string { - return fmt.Sprintf("SingleStringErrorResponse occured: %v", s.Message) + return fmt.Sprintf("SingleStringErrorResponse occured: %v", s.Message) } // SubscriptionAddCouponError is a custom error. type SubscriptionAddCouponError struct { - https.ApiError - Codes []string `json:"codes,omitempty"` - CouponCode []string `json:"coupon_code,omitempty"` - CouponCodes []string `json:"coupon_codes,omitempty"` - Subscription []string `json:"subscription,omitempty"` + https.ApiError + Codes []string `json:"codes,omitempty"` + CouponCode []string `json:"coupon_code,omitempty"` + CouponCodes []string `json:"coupon_codes,omitempty"` + Subscription []string `json:"subscription,omitempty"` } -// NewSubscriptionAddCouponError is a constructor for SubscriptionAddCouponError. +// NewSubscriptionAddCouponError is a constructor for SubscriptionAddCouponError. // It creates and returns a pointer to a new SubscriptionAddCouponError instance with the given statusCode and body. func NewSubscriptionAddCouponError(apiError https.ApiError) error { - return &SubscriptionAddCouponError{ApiError: apiError} + return &SubscriptionAddCouponError{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for SubscriptionAddCouponError. func (s *SubscriptionAddCouponError) Error() string { - return fmt.Sprintf("SubscriptionAddCouponError occured: %v", s.Message) + return fmt.Sprintf("SubscriptionAddCouponError occured: %v", s.Message) } // SubscriptionComponentAllocationError is a custom error. type SubscriptionComponentAllocationError struct { - https.ApiError - Errors []models.SubscriptionComponentAllocationErrorItem `json:"errors,omitempty"` + https.ApiError + Errors []models.SubscriptionComponentAllocationErrorItem `json:"errors,omitempty"` } -// NewSubscriptionComponentAllocationError is a constructor for SubscriptionComponentAllocationError. +// NewSubscriptionComponentAllocationError is a constructor for SubscriptionComponentAllocationError. // It creates and returns a pointer to a new SubscriptionComponentAllocationError instance with the given statusCode and body. func NewSubscriptionComponentAllocationError(apiError https.ApiError) error { - return &SubscriptionComponentAllocationError{ApiError: apiError} + return &SubscriptionComponentAllocationError{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for SubscriptionComponentAllocationError. func (s *SubscriptionComponentAllocationError) Error() string { - return fmt.Sprintf("SubscriptionComponentAllocationError occured: %v", s.Message) + return fmt.Sprintf("SubscriptionComponentAllocationError occured: %v", s.Message) +} + +// SubscriptionGroupCreateErrorResponse is a custom error. +type SubscriptionGroupCreateErrorResponse struct { + https.ApiError + Errors models.SubscriptionGroupCreateErrorResponseErrors `json:"errors"` +} + +// NewSubscriptionGroupCreateErrorResponse is a constructor for SubscriptionGroupCreateErrorResponse. +// It creates and returns a pointer to a new SubscriptionGroupCreateErrorResponse instance with the given statusCode and body. +func NewSubscriptionGroupCreateErrorResponse(apiError https.ApiError) error { + return &SubscriptionGroupCreateErrorResponse{ApiError: apiError} +} + +// Error implements the Error method for the error interface. +// It returns a formatted error message for SubscriptionGroupCreateErrorResponse. +func (s *SubscriptionGroupCreateErrorResponse) Error() string { + return fmt.Sprintf("SubscriptionGroupCreateErrorResponse occured: %v", s.Message) } // SubscriptionGroupSignupErrorResponse is a custom error. type SubscriptionGroupSignupErrorResponse struct { - https.ApiError - Errors models.SubscriptionGroupSignupError `json:"errors"` + https.ApiError + Errors models.SubscriptionGroupSignupError `json:"errors"` } -// NewSubscriptionGroupSignupErrorResponse is a constructor for SubscriptionGroupSignupErrorResponse. +// NewSubscriptionGroupSignupErrorResponse is a constructor for SubscriptionGroupSignupErrorResponse. // It creates and returns a pointer to a new SubscriptionGroupSignupErrorResponse instance with the given statusCode and body. func NewSubscriptionGroupSignupErrorResponse(apiError https.ApiError) error { - return &SubscriptionGroupSignupErrorResponse{ApiError: apiError} + return &SubscriptionGroupSignupErrorResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for SubscriptionGroupSignupErrorResponse. func (s *SubscriptionGroupSignupErrorResponse) Error() string { - return fmt.Sprintf("SubscriptionGroupSignupErrorResponse occured: %v", s.Message) + return fmt.Sprintf("SubscriptionGroupSignupErrorResponse occured: %v", s.Message) } // SubscriptionGroupUpdateErrorResponse is a custom error. type SubscriptionGroupUpdateErrorResponse struct { - https.ApiError - Errors *models.SubscriptionGroupUpdateError `json:"errors,omitempty"` + https.ApiError + Errors *models.SubscriptionGroupUpdateError `json:"errors,omitempty"` } -// NewSubscriptionGroupUpdateErrorResponse is a constructor for SubscriptionGroupUpdateErrorResponse. +// NewSubscriptionGroupUpdateErrorResponse is a constructor for SubscriptionGroupUpdateErrorResponse. // It creates and returns a pointer to a new SubscriptionGroupUpdateErrorResponse instance with the given statusCode and body. func NewSubscriptionGroupUpdateErrorResponse(apiError https.ApiError) error { - return &SubscriptionGroupUpdateErrorResponse{ApiError: apiError} + return &SubscriptionGroupUpdateErrorResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for SubscriptionGroupUpdateErrorResponse. func (s *SubscriptionGroupUpdateErrorResponse) Error() string { - return fmt.Sprintf("SubscriptionGroupUpdateErrorResponse occured: %v", s.Message) + return fmt.Sprintf("SubscriptionGroupUpdateErrorResponse occured: %v", s.Message) } // SubscriptionRemoveCouponErrors is a custom error. type SubscriptionRemoveCouponErrors struct { - https.ApiError - Subscription []string `json:"subscription"` + https.ApiError + Subscription []string `json:"subscription"` } -// NewSubscriptionRemoveCouponErrors is a constructor for SubscriptionRemoveCouponErrors. +// NewSubscriptionRemoveCouponErrors is a constructor for SubscriptionRemoveCouponErrors. // It creates and returns a pointer to a new SubscriptionRemoveCouponErrors instance with the given statusCode and body. func NewSubscriptionRemoveCouponErrors(apiError https.ApiError) error { - return &SubscriptionRemoveCouponErrors{ApiError: apiError} + return &SubscriptionRemoveCouponErrors{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for SubscriptionRemoveCouponErrors. func (s *SubscriptionRemoveCouponErrors) Error() string { - return fmt.Sprintf("SubscriptionRemoveCouponErrors occured: %v", s.Message) + return fmt.Sprintf("SubscriptionRemoveCouponErrors occured: %v", s.Message) } // SubscriptionsMrrErrorResponse is a custom error. type SubscriptionsMrrErrorResponse struct { - https.ApiError - Errors models.AttributeError `json:"errors"` + https.ApiError + Errors models.AttributeError `json:"errors"` } -// NewSubscriptionsMrrErrorResponse is a constructor for SubscriptionsMrrErrorResponse. +// NewSubscriptionsMrrErrorResponse is a constructor for SubscriptionsMrrErrorResponse. // It creates and returns a pointer to a new SubscriptionsMrrErrorResponse instance with the given statusCode and body. func NewSubscriptionsMrrErrorResponse(apiError https.ApiError) error { - return &SubscriptionsMrrErrorResponse{ApiError: apiError} + return &SubscriptionsMrrErrorResponse{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for SubscriptionsMrrErrorResponse. func (s *SubscriptionsMrrErrorResponse) Error() string { - return fmt.Sprintf("SubscriptionsMrrErrorResponse occured: %v", s.Message) + return fmt.Sprintf("SubscriptionsMrrErrorResponse occured: %v", s.Message) } // TooManyManagementLinkRequestsError is a custom error. type TooManyManagementLinkRequestsError struct { - https.ApiError - Errors models.TooManyManagementLinkRequests `json:"errors"` + https.ApiError + Errors models.TooManyManagementLinkRequests `json:"errors"` } -// NewTooManyManagementLinkRequestsError is a constructor for TooManyManagementLinkRequestsError. +// NewTooManyManagementLinkRequestsError is a constructor for TooManyManagementLinkRequestsError. // It creates and returns a pointer to a new TooManyManagementLinkRequestsError instance with the given statusCode and body. func NewTooManyManagementLinkRequestsError(apiError https.ApiError) error { - return &TooManyManagementLinkRequestsError{ApiError: apiError} + return &TooManyManagementLinkRequestsError{ApiError: apiError} } -// Error implements the Error method for the error interface. +// Error implements the Error method for the error interface. // It returns a formatted error message for TooManyManagementLinkRequestsError. func (t *TooManyManagementLinkRequestsError) Error() string { - return fmt.Sprintf("TooManyManagementLinkRequestsError occured: %v", t.Message) + return fmt.Sprintf("TooManyManagementLinkRequestsError occured: %v", t.Message) } diff --git a/events_based_billing_segments_controller.go b/events_based_billing_segments_controller.go index 12a04f01..1cc40f81 100644 --- a/events_based_billing_segments_controller.go +++ b/events_based_billing_segments_controller.go @@ -1,261 +1,276 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" ) // EventsBasedBillingSegmentsController represents a controller struct. type EventsBasedBillingSegmentsController struct { - baseController + baseController } -// NewEventsBasedBillingSegmentsController creates a new instance of EventsBasedBillingSegmentsController. +// NewEventsBasedBillingSegmentsController creates a new instance of EventsBasedBillingSegmentsController. // It takes a baseController as a parameter and returns a pointer to the EventsBasedBillingSegmentsController. func NewEventsBasedBillingSegmentsController(baseController baseController) *EventsBasedBillingSegmentsController { - eventsBasedBillingSegmentsController := EventsBasedBillingSegmentsController{baseController: baseController} - return &eventsBasedBillingSegmentsController + eventsBasedBillingSegmentsController := EventsBasedBillingSegmentsController{baseController: baseController} + return &eventsBasedBillingSegmentsController } -// CreateSegment takes context, componentId, pricePointId, body as parameters and -// returns an models.ApiResponse with models.SegmentResponse data and -// an error if there was an issue with the request or response. -// This endpoint creates a new Segment for a Component with segmented Metric. It allows you to specify properties to bill upon and prices for each Segment. You can only pass as many "property_values" as the related Metric has segmenting properties defined. +// CreateSegment takes context, componentId, pricePointId, body as parameters and +// returns an models.ApiResponse with models.SegmentResponse data and +// an error if there was an issue with the request or response. +// This endpoint creates a new Segment for a Component with segmented Metric. It allows you to specify properties to bill upon and prices for each Segment. You can only pass as many "property_values" as the related Metric has segmenting properties defined. // You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. func (e *EventsBasedBillingSegmentsController) CreateSegment( - ctx context.Context, - componentId string, - pricePointId string, - body *models.CreateSegmentRequest) ( - models.ApiResponse[models.SegmentResponse], - error) { - req := e.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/components/%v/price_points/%v/segments.json", componentId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewEventBasedBillingSegmentErrors}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SegmentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SegmentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + componentId string, + pricePointId string, + body *models.CreateSegmentRequest) ( + models.ApiResponse[models.SegmentResponse], + error) { + req := e.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/components/%v/price_points/%v/segments.json", componentId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewEventBasedBillingSegmentErrors}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SegmentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SegmentResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListSegmentsForPricePointInput represents the input of the ListSegmentsForPricePoint endpoint. +type ListSegmentsForPricePointInput struct { + // ID or Handle for the Component + ComponentId string + // ID or Handle for the Price Point belonging to the Component + PricePointId string + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 30. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The value passed here would be used to filter segments. Pass a value related to `segment_property_1` on attached Metric. If empty string is passed, this filter would be rejected. Use in query `filter[segment_property_1_value]=EU`. + FilterSegmentProperty1Value *string + // The value passed here would be used to filter segments. Pass a value related to `segment_property_2` on attached Metric. If empty string is passed, this filter would be rejected. + FilterSegmentProperty2Value *string + // The value passed here would be used to filter segments. Pass a value related to `segment_property_3` on attached Metric. If empty string is passed, this filter would be rejected. + FilterSegmentProperty3Value *string + // The value passed here would be used to filter segments. Pass a value related to `segment_property_4` on attached Metric. If empty string is passed, this filter would be rejected. + FilterSegmentProperty4Value *string } -// ListSegmentsForPricePoint takes context, componentId, pricePointId, page, perPage, filterSegmentProperty1Value, filterSegmentProperty2Value, filterSegmentProperty3Value, filterSegmentProperty4Value as parameters and -// returns an models.ApiResponse with models.ListSegmentsResponse data and -// an error if there was an issue with the request or response. -// This endpoint allows you to fetch Segments created for a given Price Point. They will be returned in the order of creation. -// You can pass `page` and `per_page` parameters in order to access all of the segments. By default it will return `30` records. You can set `per_page` to `200` at most. +// ListSegmentsForPricePoint takes context, componentId, pricePointId, page, perPage, filterSegmentProperty1Value, filterSegmentProperty2Value, filterSegmentProperty3Value, filterSegmentProperty4Value as parameters and +// returns an models.ApiResponse with models.ListSegmentsResponse data and +// an error if there was an issue with the request or response. +// This endpoint allows you to fetch Segments created for a given Price Point. They will be returned in the order of creation. +// You can pass `page` and `per_page` parameters in order to access all of the segments. By default it will return `30` records. You can set `per_page` to `200` at most. // You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. func (e *EventsBasedBillingSegmentsController) ListSegmentsForPricePoint( - ctx context.Context, - componentId string, - pricePointId string, - page *int, - perPage *int, - filterSegmentProperty1Value *string, - filterSegmentProperty2Value *string, - filterSegmentProperty3Value *string, - filterSegmentProperty4Value *string) ( - models.ApiResponse[models.ListSegmentsResponse], - error) { - req := e.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/components/%v/price_points/%v/segments.json", componentId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewEventBasedBillingListSegmentsErrors}, - }) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if filterSegmentProperty1Value != nil { - req.QueryParam("filter[segment_property_1_value]", *filterSegmentProperty1Value) - } - if filterSegmentProperty2Value != nil { - req.QueryParam("filter[segment_property_2_value]", *filterSegmentProperty2Value) - } - if filterSegmentProperty3Value != nil { - req.QueryParam("filter[segment_property_3_value]", *filterSegmentProperty3Value) - } - if filterSegmentProperty4Value != nil { - req.QueryParam("filter[segment_property_4_value]", *filterSegmentProperty4Value) - } - - var result models.ListSegmentsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListSegmentsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListSegmentsForPricePointInput) ( + models.ApiResponse[models.ListSegmentsResponse], + error) { + req := e.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/components/%v/price_points/%v/segments.json", input.ComponentId, input.PricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewEventBasedBillingListSegmentsErrors}, + }) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.FilterSegmentProperty1Value != nil { + req.QueryParam("filter[segment_property_1_value]", *input.FilterSegmentProperty1Value) + } + if input.FilterSegmentProperty2Value != nil { + req.QueryParam("filter[segment_property_2_value]", *input.FilterSegmentProperty2Value) + } + if input.FilterSegmentProperty3Value != nil { + req.QueryParam("filter[segment_property_3_value]", *input.FilterSegmentProperty3Value) + } + if input.FilterSegmentProperty4Value != nil { + req.QueryParam("filter[segment_property_4_value]", *input.FilterSegmentProperty4Value) + } + + var result models.ListSegmentsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListSegmentsResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateSegment takes context, componentId, pricePointId, id, body as parameters and -// returns an models.ApiResponse with models.SegmentResponse data and -// an error if there was an issue with the request or response. -// This endpoint updates a single Segment for a Component with a segmented Metric. It allows you to update the pricing for the segment. +// UpdateSegment takes context, componentId, pricePointId, id, body as parameters and +// returns an models.ApiResponse with models.SegmentResponse data and +// an error if there was an issue with the request or response. +// This endpoint updates a single Segment for a Component with a segmented Metric. It allows you to update the pricing for the segment. // You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. func (e *EventsBasedBillingSegmentsController) UpdateSegment( - ctx context.Context, - componentId string, - pricePointId string, - id float64, - body *models.UpdateSegmentRequest) ( - models.ApiResponse[models.SegmentResponse], - error) { - req := e.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/components/%v/price_points/%v/segments/%v.json", componentId, pricePointId, id), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewEventBasedBillingSegmentErrors}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SegmentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SegmentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + componentId string, + pricePointId string, + id float64, + body *models.UpdateSegmentRequest) ( + models.ApiResponse[models.SegmentResponse], + error) { + req := e.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/components/%v/price_points/%v/segments/%v.json", componentId, pricePointId, id), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewEventBasedBillingSegmentErrors}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SegmentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SegmentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// DeleteSegment takes context, componentId, pricePointId, id as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// This endpoint allows you to delete a Segment with specified ID. +// DeleteSegment takes context, componentId, pricePointId, id as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// This endpoint allows you to delete a Segment with specified ID. // You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. func (e *EventsBasedBillingSegmentsController) DeleteSegment( - ctx context.Context, - componentId string, - pricePointId string, - id float64) ( - *http.Response, - error) { - req := e.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/components/%v/price_points/%v/segments/%v.json", componentId, pricePointId, id), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'."}, - }) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + componentId string, + pricePointId string, + id float64) ( + *http.Response, + error) { + req := e.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/components/%v/price_points/%v/segments/%v.json", componentId, pricePointId, id), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'."}, + }) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// BulkCreateSegments takes context, componentId, pricePointId, body as parameters and -// returns an models.ApiResponse with models.ListSegmentsResponse data and -// an error if there was an issue with the request or response. -// This endpoint allows you to create multiple segments in one request. The array of segments can contain up to `2000` records. -// If any of the records contain an error the whole request would fail and none of the requested segments get created. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. +// BulkCreateSegments takes context, componentId, pricePointId, body as parameters and +// returns an models.ApiResponse with models.ListSegmentsResponse data and +// an error if there was an issue with the request or response. +// This endpoint allows you to create multiple segments in one request. The array of segments can contain up to `2000` records. +// If any of the records contain an error the whole request would fail and none of the requested segments get created. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. // You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. func (e *EventsBasedBillingSegmentsController) BulkCreateSegments( - ctx context.Context, - componentId string, - pricePointId string, - body *models.BulkCreateSegments) ( - models.ApiResponse[models.ListSegmentsResponse], - error) { - req := e.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/components/%v/price_points/%v/segments/bulk.json", componentId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewEventBasedBillingSegment}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ListSegmentsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListSegmentsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + componentId string, + pricePointId string, + body *models.BulkCreateSegments) ( + models.ApiResponse[models.ListSegmentsResponse], + error) { + req := e.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/components/%v/price_points/%v/segments/bulk.json", componentId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewEventBasedBillingSegment}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ListSegmentsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListSegmentsResponse](decoder) + return models.NewApiResponse(result, resp), err } -// BulkUpdateSegments takes context, componentId, pricePointId, body as parameters and -// returns an models.ApiResponse with models.ListSegmentsResponse data and -// an error if there was an issue with the request or response. -// This endpoint allows you to update multiple segments in one request. The array of segments can contain up to `1000` records. -// If any of the records contain an error the whole request would fail and none of the requested segments get updated. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. +// BulkUpdateSegments takes context, componentId, pricePointId, body as parameters and +// returns an models.ApiResponse with models.ListSegmentsResponse data and +// an error if there was an issue with the request or response. +// This endpoint allows you to update multiple segments in one request. The array of segments can contain up to `1000` records. +// If any of the records contain an error the whole request would fail and none of the requested segments get updated. The error response contains a message for only the one segment that failed validation, with the corresponding index in the array. // You may specify component and/or price point by using either the numeric ID or the `handle:gold` syntax. func (e *EventsBasedBillingSegmentsController) BulkUpdateSegments( - ctx context.Context, - componentId string, - pricePointId string, - body *models.BulkUpdateSegments) ( - models.ApiResponse[models.ListSegmentsResponse], - error) { - req := e.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/components/%v/price_points/%v/segments/bulk.json", componentId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewEventBasedBillingSegment}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ListSegmentsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListSegmentsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + componentId string, + pricePointId string, + body *models.BulkUpdateSegments) ( + models.ApiResponse[models.ListSegmentsResponse], + error) { + req := e.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/components/%v/price_points/%v/segments/bulk.json", componentId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewEventBasedBillingSegment}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ListSegmentsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListSegmentsResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/events_controller.go b/events_controller.go index 6699518e..6367e7f9 100644 --- a/events_controller.go +++ b/events_controller.go @@ -1,226 +1,274 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/models" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/models" ) // EventsController represents a controller struct. type EventsController struct { - baseController + baseController } -// NewEventsController creates a new instance of EventsController. +// NewEventsController creates a new instance of EventsController. // It takes a baseController as a parameter and returns a pointer to the EventsController. func NewEventsController(baseController baseController) *EventsController { - eventsController := EventsController{baseController: baseController} - return &eventsController + eventsController := EventsController{baseController: baseController} + return &eventsController } -// ListEvents takes context, page, perPage, sinceId, maxId, direction, filter, dateField, startDate, endDate, startDatetime, endDatetime as parameters and -// returns an models.ApiResponse with []models.EventResponse data and -// an error if there was an issue with the request or response. -// ## Events Intro -// Chargify Events include various activity that happens around a Site. This information is **especially** useful to track down issues that arise when subscriptions are not created due to errors. -// Within the Chargify UI, "Events" are referred to as "Site Activity". Full documentation on how to record view Events / Site Activty in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407864698139). -// ## List Events for a Site -// This method will retrieve a list of events for a site. Use query string filters to narrow down results. You may use the `key` filter as part of your query string to narrow down results. -// ### Legacy Filters -// The following keys are no longer supported. -// + `payment_failure_recreated` -// + `payment_success_recreated` -// + `renewal_failure_recreated` -// + `renewal_success_recreated` -// + `zferral_revenue_post_failure` - (Specific to the deprecated Zferral integration) -// + `zferral_revenue_post_success` - (Specific to the deprecated Zferral integration) -// ## Event Specific Data -// Event Specific Data -// Each event type has its own `event_specific_data` specified. -// Here’s an example event for the `subscription_product_change` event: -// ``` -// { -// "event": { -// "id": 351, -// "key": "subscription_product_change", -// "message": "Product changed on Marky Mark's subscription from 'Basic' to 'Pro'", -// "subscription_id": 205, -// "event_specific_data": { -// "new_product_id": 3, -// "previous_product_id": 2 -// }, -// "created_at": "2012-01-30T10:43:31-05:00" -// } -// } -// ``` -// Here’s an example event for the `subscription_state_change` event: -// ``` -// { -// "event": { -// "id": 353, -// "key": "subscription_state_change", -// "message": "State changed on Marky Mark's subscription to Pro from trialing to active", -// "subscription_id": 205, -// "event_specific_data": { -// "new_subscription_state": "active", -// "previous_subscription_state": "trialing" -// }, -// "created_at": "2012-01-30T10:43:33-05:00" -// } -// } +// ListEventsInput represents the input of the ListEvents endpoint. +type ListEventsInput struct { + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // Returns events with an id greater than or equal to the one specified + SinceId *int + // Returns events with an id less than or equal to the one specified + MaxId *int + // The sort direction of the returned events. + Direction *models.Direction + // You can pass multiple event keys after comma. + // Use in query `filter=signup_success,payment_success`. + Filter []models.EventType + // The type of filter you would like to apply to your search. + DateField *models.ListEventsDateField + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + StartDate *string + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + EndDate *string + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. + StartDatetime *string + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. + EndDatetime *string +} + +// ListEvents takes context, page, perPage, sinceId, maxId, direction, filter, dateField, startDate, endDate, startDatetime, endDatetime as parameters and +// returns an models.ApiResponse with []models.EventResponse data and +// an error if there was an issue with the request or response. +// ## Events Intro +// Chargify Events include various activity that happens around a Site. This information is **especially** useful to track down issues that arise when subscriptions are not created due to errors. +// Within the Chargify UI, "Events" are referred to as "Site Activity". Full documentation on how to record view Events / Site Activty in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407864698139). +// ## List Events for a Site +// This method will retrieve a list of events for a site. Use query string filters to narrow down results. You may use the `key` filter as part of your query string to narrow down results. +// ### Legacy Filters +// The following keys are no longer supported. +// + `payment_failure_recreated` +// + `payment_success_recreated` +// + `renewal_failure_recreated` +// + `renewal_success_recreated` +// + `zferral_revenue_post_failure` - (Specific to the deprecated Zferral integration) +// + `zferral_revenue_post_success` - (Specific to the deprecated Zferral integration) +// ## Event Specific Data +// Event Specific Data +// Each event type has its own `event_specific_data` specified. +// Here’s an example event for the `subscription_product_change` event: +// ``` +// { +// "event": { +// "id": 351, +// "key": "subscription_product_change", +// "message": "Product changed on Marky Mark's subscription from 'Basic' to 'Pro'", +// "subscription_id": 205, +// "event_specific_data": { +// "new_product_id": 3, +// "previous_product_id": 2 +// }, +// "created_at": "2012-01-30T10:43:31-05:00" +// } +// } +// ``` +// Here’s an example event for the `subscription_state_change` event: +// ``` +// { +// "event": { +// "id": 353, +// "key": "subscription_state_change", +// "message": "State changed on Marky Mark's subscription to Pro from trialing to active", +// "subscription_id": 205, +// "event_specific_data": { +// "new_subscription_state": "active", +// "previous_subscription_state": "trialing" +// }, +// "created_at": "2012-01-30T10:43:33-05:00" +// } +// } // ``` func (e *EventsController) ListEvents( - ctx context.Context, - page *int, - perPage *int, - sinceId *int, - maxId *int, - direction *models.Direction, - filter []models.EventType, - dateField *models.ListEventsDateField, - startDate *string, - endDate *string, - startDatetime *string, - endDatetime *string) ( - models.ApiResponse[[]models.EventResponse], - error) { - req := e.prepareRequest(ctx, "GET", "/events.json") - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if sinceId != nil { - req.QueryParam("since_id", *sinceId) - } - if maxId != nil { - req.QueryParam("max_id", *maxId) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - if filter != nil { - req.QueryParam("filter", filter) - } - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if startDate != nil { - req.QueryParam("start_date", *startDate) - } - if endDate != nil { - req.QueryParam("end_date", *endDate) - } - if startDatetime != nil { - req.QueryParam("start_datetime", *startDatetime) - } - if endDatetime != nil { - req.QueryParam("end_datetime", *endDatetime) - } - var result []models.EventResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.EventResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListEventsInput) ( + models.ApiResponse[[]models.EventResponse], + error) { + req := e.prepareRequest(ctx, "GET", "/events.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.SinceId != nil { + req.QueryParam("since_id", *input.SinceId) + } + if input.MaxId != nil { + req.QueryParam("max_id", *input.MaxId) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + if input.Filter != nil { + req.QueryParam("filter", input.Filter) + } + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.StartDate != nil { + req.QueryParam("start_date", *input.StartDate) + } + if input.EndDate != nil { + req.QueryParam("end_date", *input.EndDate) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", *input.StartDatetime) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", *input.EndDatetime) + } + var result []models.EventResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.EventResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListSubscriptionEvents takes context, subscriptionId, page, perPage, sinceId, maxId, direction, filter as parameters and -// returns an models.ApiResponse with []models.EventResponse data and -// an error if there was an issue with the request or response. -// The following request will return a list of events for a subscription. +// ListSubscriptionEventsInput represents the input of the ListSubscriptionEvents endpoint. +type ListSubscriptionEventsInput struct { + // The Chargify id of the subscription + SubscriptionId int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // Returns events with an id greater than or equal to the one specified + SinceId *int + // Returns events with an id less than or equal to the one specified + MaxId *int + // The sort direction of the returned events. + Direction *models.Direction + // You can pass multiple event keys after comma. + // Use in query `filter=signup_success,payment_success`. + Filter []models.EventType +} + +// ListSubscriptionEvents takes context, subscriptionId, page, perPage, sinceId, maxId, direction, filter as parameters and +// returns an models.ApiResponse with []models.EventResponse data and +// an error if there was an issue with the request or response. +// The following request will return a list of events for a subscription. // Each event type has its own `event_specific_data` specified. func (e *EventsController) ListSubscriptionEvents( - ctx context.Context, - subscriptionId int, - page *int, - perPage *int, - sinceId *int, - maxId *int, - direction *models.Direction, - filter []models.EventType) ( - models.ApiResponse[[]models.EventResponse], - error) { - req := e.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v/events.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if sinceId != nil { - req.QueryParam("since_id", *sinceId) - } - if maxId != nil { - req.QueryParam("max_id", *maxId) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - if filter != nil { - req.QueryParam("filter", filter) - } - - var result []models.EventResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.EventResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListSubscriptionEventsInput) ( + models.ApiResponse[[]models.EventResponse], + error) { + req := e.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v/events.json", input.SubscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.SinceId != nil { + req.QueryParam("since_id", *input.SinceId) + } + if input.MaxId != nil { + req.QueryParam("max_id", *input.MaxId) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + if input.Filter != nil { + req.QueryParam("filter", input.Filter) + } + + var result []models.EventResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.EventResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadEventsCount takes context, page, perPage, sinceId, maxId, direction, filter as parameters and -// returns an models.ApiResponse with models.CountResponse data and -// an error if there was an issue with the request or response. +// ReadEventsCountInput represents the input of the ReadEventsCount endpoint. +type ReadEventsCountInput struct { + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // Returns events with an id greater than or equal to the one specified + SinceId *int + // Returns events with an id less than or equal to the one specified + MaxId *int + // The sort direction of the returned events. + Direction *models.Direction + // You can pass multiple event keys after comma. + // Use in query `filter=signup_success,payment_success`. + Filter []models.EventType +} + +// ReadEventsCount takes context, page, perPage, sinceId, maxId, direction, filter as parameters and +// returns an models.ApiResponse with models.CountResponse data and +// an error if there was an issue with the request or response. // Get a count of all the events for a given site by using this method. func (e *EventsController) ReadEventsCount( - ctx context.Context, - page *int, - perPage *int, - sinceId *int, - maxId *int, - direction *models.Direction, - filter []models.EventType) ( - models.ApiResponse[models.CountResponse], - error) { - req := e.prepareRequest(ctx, "GET", "/events/count.json") - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if sinceId != nil { - req.QueryParam("since_id", *sinceId) - } - if maxId != nil { - req.QueryParam("max_id", *maxId) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - if filter != nil { - req.QueryParam("filter", filter) - } - var result models.CountResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CountResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ReadEventsCountInput) ( + models.ApiResponse[models.CountResponse], + error) { + req := e.prepareRequest(ctx, "GET", "/events/count.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.SinceId != nil { + req.QueryParam("since_id", *input.SinceId) + } + if input.MaxId != nil { + req.QueryParam("max_id", *input.MaxId) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + if input.Filter != nil { + req.QueryParam("filter", input.Filter) + } + var result models.CountResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CountResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/go.mod b/go.mod index 93c38606..33e185ad 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module github.com/maxio-com/ab-golang-sdk go 1.18 -require github.com/apimatic/go-core-runtime v0.0.16 +require github.com/apimatic/go-core-runtime v0.0.18 require ( github.com/go-openapi/jsonpointer v0.20.2 // indirect diff --git a/go.sum b/go.sum index 9f8a4ac9..db8247ab 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -github.com/apimatic/go-core-runtime v0.0.16 h1:tj14lVDfe03ukFv2krPLZO+9DZldWdyWnlHfG4gmoGc= -github.com/apimatic/go-core-runtime v0.0.16/go.mod h1:CqQWJAOScv0NLQQVBVKCRvw83iq7sygbvpZgVvWLiFw= +github.com/apimatic/go-core-runtime v0.0.18 h1:WlbvjWK88+RjlIrSDXqwPaT1/mKsBbl9MmHNPbZFfqs= +github.com/apimatic/go-core-runtime v0.0.18/go.mod h1:CqQWJAOScv0NLQQVBVKCRvw83iq7sygbvpZgVvWLiFw= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/go-openapi/jsonpointer v0.20.2 h1:mQc3nmndL8ZBzStEo3JYF8wzmeWffDH4VbXz58sAx6Q= github.com/go-openapi/jsonpointer v0.20.2/go.mod h1:bHen+N0u1KEO3YlmqOjTT9Adn1RfD91Ar825/PuiRVs= diff --git a/insights_controller.go b/insights_controller.go index 44994003..b4db0ae2 100644 --- a/insights_controller.go +++ b/insights_controller.go @@ -1,169 +1,193 @@ package advancedbilling import ( - "context" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "time" + "context" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "time" ) // InsightsController represents a controller struct. type InsightsController struct { - baseController + baseController } -// NewInsightsController creates a new instance of InsightsController. +// NewInsightsController creates a new instance of InsightsController. // It takes a baseController as a parameter and returns a pointer to the InsightsController. func NewInsightsController(baseController baseController) *InsightsController { - insightsController := InsightsController{baseController: baseController} - return &insightsController + insightsController := InsightsController{baseController: baseController} + return &insightsController } -// ReadSiteStats takes context as parameters and -// returns an models.ApiResponse with models.SiteSummary data and -// an error if there was an issue with the request or response. -// The Stats API is a very basic view of some Site-level stats. This API call only answers with JSON responses. An XML version is not provided. -// ## Stats Documentation -// There currently is not a complimentary matching set of documentation that compliments this endpoint. However, each Site's dashboard will reflect the summary of information provided in the Stats reposnse. -// ``` -// https://subdomain.chargify.com/dashboard +// ReadSiteStats takes context as parameters and +// returns an models.ApiResponse with models.SiteSummary data and +// an error if there was an issue with the request or response. +// The Stats API is a very basic view of some Site-level stats. This API call only answers with JSON responses. An XML version is not provided. +// ## Stats Documentation +// There currently is not a complimentary matching set of documentation that compliments this endpoint. However, each Site's dashboard will reflect the summary of information provided in the Stats reposnse. +// ``` +// https://subdomain.chargify.com/dashboard // ``` func (i *InsightsController) ReadSiteStats(ctx context.Context) ( - models.ApiResponse[models.SiteSummary], - error) { - req := i.prepareRequest(ctx, "GET", "/stats.json") - req.Authenticate(NewAuth("BasicAuth")) - var result models.SiteSummary - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SiteSummary](decoder) - return models.NewApiResponse(result, resp), err + models.ApiResponse[models.SiteSummary], + error) { + req := i.prepareRequest(ctx, "GET", "/stats.json") + req.Authenticate(NewAuth("BasicAuth")) + var result models.SiteSummary + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SiteSummary](decoder) + return models.NewApiResponse(result, resp), err } -// ReadMrr takes context, atTime, subscriptionId as parameters and -// returns an models.ApiResponse with models.MRRResponse data and -// an error if there was an issue with the request or response. -// Deprecated: readMrr is deprecated +// ReadMrr takes context, atTime, subscriptionId as parameters and +// returns an models.ApiResponse with models.MRRResponse data and +// an error if there was an issue with the request or response. +// Deprecated: readMrr is deprecated // This endpoint returns your site's current MRR, including plan and usage breakouts. func (i *InsightsController) ReadMrr( - ctx context.Context, - atTime *time.Time, - subscriptionId *int) ( - models.ApiResponse[models.MRRResponse], - error) { - req := i.prepareRequest(ctx, "GET", "/mrr.json") - req.Authenticate(NewAuth("BasicAuth")) - if atTime != nil { - req.QueryParam("at_time", atTime.Format(time.RFC3339)) - } - if subscriptionId != nil { - req.QueryParam("subscription_id", *subscriptionId) - } - var result models.MRRResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.MRRResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + atTime *time.Time, + subscriptionId *int) ( + models.ApiResponse[models.MRRResponse], + error) { + req := i.prepareRequest(ctx, "GET", "/mrr.json") + req.Authenticate(NewAuth("BasicAuth")) + if atTime != nil { + req.QueryParam("at_time", atTime.Format(time.RFC3339)) + } + if subscriptionId != nil { + req.QueryParam("subscription_id", *subscriptionId) + } + var result models.MRRResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.MRRResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListMrrMovementsInput represents the input of the ListMrrMovements endpoint. +type ListMrrMovementsInput struct { + // optionally filter results by subscription + SubscriptionId *int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 10. The maximum allowed values is 50; any per_page value over 50 will be changed to 50. + // Use in query `per_page=20`. + PerPage *int + // Controls the order in which results are returned. + // Use in query `direction=asc`. + Direction *models.SortingDirection } -// ListMrrMovements takes context, subscriptionId, page, perPage, direction as parameters and -// returns an models.ApiResponse with models.ListMRRResponse data and -// an error if there was an issue with the request or response. -// Deprecated: listMrrMovements is deprecated -// This endpoint returns your site's MRR movements. -// ## Understanding MRR movements -// This endpoint will aid in accessing your site's [MRR Report](https://chargify.zendesk.com/hc/en-us/articles/4407838249627) data. -// Whenever a subscription event occurs that causes your site's MRR to change (such as a signup or upgrade), we record an MRR movement. These records are accessible via the MRR Movements endpoint. -// Each MRR Movement belongs to a subscription and contains a timestamp, category, and an amount. `line_items` represent the subscription's product configuration at the time of the movement. -// ### Plan & Usage Breakouts -// In the MRR Report UI, we support a setting to [include or exclude](https://chargify.zendesk.com/hc/en-us/articles/4407838249627#displaying-component-based-metered-usage-in-mrr) usage revenue. In the MRR APIs, responses include `plan` and `usage` breakouts. -// Plan includes revenue from: -// * Products -// * Quantity-Based Components -// * On/Off Components -// Usage includes revenue from: -// * Metered Components +// ListMrrMovements takes context, subscriptionId, page, perPage, direction as parameters and +// returns an models.ApiResponse with models.ListMRRResponse data and +// an error if there was an issue with the request or response. +// Deprecated: listMrrMovements is deprecated +// This endpoint returns your site's MRR movements. +// ## Understanding MRR movements +// This endpoint will aid in accessing your site's [MRR Report](https://chargify.zendesk.com/hc/en-us/articles/4407838249627) data. +// Whenever a subscription event occurs that causes your site's MRR to change (such as a signup or upgrade), we record an MRR movement. These records are accessible via the MRR Movements endpoint. +// Each MRR Movement belongs to a subscription and contains a timestamp, category, and an amount. `line_items` represent the subscription's product configuration at the time of the movement. +// ### Plan & Usage Breakouts +// In the MRR Report UI, we support a setting to [include or exclude](https://chargify.zendesk.com/hc/en-us/articles/4407838249627#displaying-component-based-metered-usage-in-mrr) usage revenue. In the MRR APIs, responses include `plan` and `usage` breakouts. +// Plan includes revenue from: +// * Products +// * Quantity-Based Components +// * On/Off Components +// Usage includes revenue from: +// * Metered Components // * Prepaid Usage Components func (i *InsightsController) ListMrrMovements( - ctx context.Context, - subscriptionId *int, - page *int, - perPage *int, - direction *models.SortingDirection) ( - models.ApiResponse[models.ListMRRResponse], - error) { - req := i.prepareRequest(ctx, "GET", "/mrr_movements.json") - req.Authenticate(NewAuth("BasicAuth")) - if subscriptionId != nil { - req.QueryParam("subscription_id", *subscriptionId) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - var result models.ListMRRResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListMRRResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListMrrMovementsInput) ( + models.ApiResponse[models.ListMRRResponse], + error) { + req := i.prepareRequest(ctx, "GET", "/mrr_movements.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.SubscriptionId != nil { + req.QueryParam("subscription_id", *input.SubscriptionId) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + var result models.ListMRRResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListMRRResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListMrrPerSubscriptionInput represents the input of the ListMrrPerSubscription endpoint. +type ListMrrPerSubscriptionInput struct { + // Submit ids in order to limit results. Use in query: `filter[subscription_ids]=1,2,3`. + FilterSubscriptionIds []int + // Submit a timestamp in ISO8601 format to request MRR for a historic time. Use in query: `at_time=2022-01-10T10:00:00-05:00`. + AtTime *string + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // Controls the order in which results are returned. Records are ordered by subscription_id in ascending order by default. Use in query `direction=desc`. + Direction *models.Direction } -// ListMrrPerSubscription takes context, filterSubscriptionIds, atTime, page, perPage, direction as parameters and -// returns an models.ApiResponse with models.SubscriptionMRRResponse data and -// an error if there was an issue with the request or response. -// Deprecated: listMrrPerSubscription is deprecated +// ListMrrPerSubscription takes context, filterSubscriptionIds, atTime, page, perPage, direction as parameters and +// returns an models.ApiResponse with models.SubscriptionMRRResponse data and +// an error if there was an issue with the request or response. +// Deprecated: listMrrPerSubscription is deprecated // This endpoint returns your site's current MRR, including plan and usage breakouts split per subscription. func (i *InsightsController) ListMrrPerSubscription( - ctx context.Context, - filterSubscriptionIds []int, - atTime *string, - page *int, - perPage *int, - direction *models.Direction) ( - models.ApiResponse[models.SubscriptionMRRResponse], - error) { - req := i.prepareRequest(ctx, "GET", "/subscriptions_mrr.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "400": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionsMrrErrorResponse}, - }) - if filterSubscriptionIds != nil { - req.QueryParam("filter[subscription_ids]", filterSubscriptionIds) - } - if atTime != nil { - req.QueryParam("at_time", *atTime) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - var result models.SubscriptionMRRResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionMRRResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListMrrPerSubscriptionInput) ( + models.ApiResponse[models.SubscriptionMRRResponse], + error) { + req := i.prepareRequest(ctx, "GET", "/subscriptions_mrr.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "400": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionsMrrErrorResponse}, + }) + if input.FilterSubscriptionIds != nil { + req.QueryParam("filter[subscription_ids]", input.FilterSubscriptionIds) + } + if input.AtTime != nil { + req.QueryParam("at_time", *input.AtTime) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + var result models.SubscriptionMRRResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionMRRResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/invoices_controller.go b/invoices_controller.go index dc9e99c8..4055ab03 100644 --- a/invoices_controller.go +++ b/invoices_controller.go @@ -1,866 +1,934 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" ) // InvoicesController represents a controller struct. type InvoicesController struct { - baseController + baseController } -// NewInvoicesController creates a new instance of InvoicesController. +// NewInvoicesController creates a new instance of InvoicesController. // It takes a baseController as a parameter and returns a pointer to the InvoicesController. func NewInvoicesController(baseController baseController) *InvoicesController { - invoicesController := InvoicesController{baseController: baseController} - return &invoicesController + invoicesController := InvoicesController{baseController: baseController} + return &invoicesController } -// RefundInvoice takes context, uid, body as parameters and -// returns an models.ApiResponse with models.Invoice data and -// an error if there was an issue with the request or response. -// Refund an invoice, segment, or consolidated invoice. -// ## Partial Refund for Consolidated Invoice -// A refund less than the total of a consolidated invoice will be split across its segments. +// RefundInvoice takes context, uid, body as parameters and +// returns an models.ApiResponse with models.Invoice data and +// an error if there was an issue with the request or response. +// Refund an invoice, segment, or consolidated invoice. +// ## Partial Refund for Consolidated Invoice +// A refund less than the total of a consolidated invoice will be split across its segments. // A $50.00 refund on a $100.00 consolidated invoice with one $60.00 and one $40.00 segment, the refunded amount will be applied as 50% of each ($30.00 and $20.00 respectively). func (i *InvoicesController) RefundInvoice( - ctx context.Context, - uid string, - body *models.RefundInvoiceRequest) ( - models.ApiResponse[models.Invoice], - error) { - req := i.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/invoices/%v/refunds.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.Invoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.Invoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string, + body *models.RefundInvoiceRequest) ( + models.ApiResponse[models.Invoice], + error) { + req := i.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/invoices/%v/refunds.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.Invoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.Invoice](decoder) + return models.NewApiResponse(result, resp), err } -// ListInvoices takes context, startDate, endDate, status, subscriptionId, subscriptionGroupUid, page, perPage, direction, lineItems, discounts, taxes, credits, payments, customFields, refunds, dateField, startDatetime, endDatetime, customerIds, number, productIds, sort as parameters and -// returns an models.ApiResponse with models.ListInvoicesResponse data and -// an error if there was an issue with the request or response. +// ListInvoicesInput represents the input of the ListInvoices endpoint. +type ListInvoicesInput struct { + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns invoices with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + StartDate *string + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns invoices with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + EndDate *string + // The current status of the invoice. Allowed Values: draft, open, paid, pending, voided + Status *models.InvoiceStatus + // The subscription's ID. + SubscriptionId *int + // The UID of the subscription group you want to fetch consolidated invoices for. This will return a paginated list of consolidated invoices for the specified group. + SubscriptionGroupUid *string + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The sort direction of the returned invoices. + Direction *models.Direction + // Include line items data + LineItems *bool + // Include discounts data + Discounts *bool + // Include taxes data + Taxes *bool + // Include credits data + Credits *bool + // Include payments data + Payments *bool + // Include custom fields data + CustomFields *bool + // Include refunds data + Refunds *bool + // The type of filter you would like to apply to your search. Use in query `date_field=issue_date`. + DateField *models.InvoiceDateField + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns invoices with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Allowed to be used only along with date_field set to created_at or updated_at. + StartDatetime *string + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns invoices with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Allowed to be used only along with date_field set to created_at or updated_at. + EndDatetime *string + // Allows fetching invoices with matching customer id based on provided values. Use in query `customer_ids=1,2,3`. + CustomerIds []int + // Allows fetching invoices with matching invoice number based on provided values. Use in query `number=1234,1235`. + Number []string + // Allows fetching invoices with matching line items product ids based on provided values. Use in query `product_ids=23,34`. + ProductIds []int + // Allows specification of the order of the returned list. Use in query `sort=total_amount`. + Sort *models.InvoiceSortField +} + +// ListInvoices takes context, startDate, endDate, status, subscriptionId, subscriptionGroupUid, page, perPage, direction, lineItems, discounts, taxes, credits, payments, customFields, refunds, dateField, startDatetime, endDatetime, customerIds, number, productIds, sort as parameters and +// returns an models.ApiResponse with models.ListInvoicesResponse data and +// an error if there was an issue with the request or response. // By default, invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`, or `refunds`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. func (i *InvoicesController) ListInvoices( - ctx context.Context, - startDate *string, - endDate *string, - status *models.InvoiceStatus, - subscriptionId *int, - subscriptionGroupUid *string, - page *int, - perPage *int, - direction *models.Direction, - lineItems *bool, - discounts *bool, - taxes *bool, - credits *bool, - payments *bool, - customFields *bool, - refunds *bool, - dateField *models.InvoiceDateField, - startDatetime *string, - endDatetime *string, - customerIds []int, - number []string, - productIds []int, - sort *models.InvoiceSortField) ( - models.ApiResponse[models.ListInvoicesResponse], - error) { - req := i.prepareRequest(ctx, "GET", "/invoices.json") - req.Authenticate(NewAuth("BasicAuth")) - if startDate != nil { - req.QueryParam("start_date", *startDate) - } - if endDate != nil { - req.QueryParam("end_date", *endDate) - } - if status != nil { - req.QueryParam("status", *status) - } - if subscriptionId != nil { - req.QueryParam("subscription_id", *subscriptionId) - } - if subscriptionGroupUid != nil { - req.QueryParam("subscription_group_uid", *subscriptionGroupUid) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - if lineItems != nil { - req.QueryParam("line_items", *lineItems) - } - if discounts != nil { - req.QueryParam("discounts", *discounts) - } - if taxes != nil { - req.QueryParam("taxes", *taxes) - } - if credits != nil { - req.QueryParam("credits", *credits) - } - if payments != nil { - req.QueryParam("payments", *payments) - } - if customFields != nil { - req.QueryParam("custom_fields", *customFields) - } - if refunds != nil { - req.QueryParam("refunds", *refunds) - } - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if startDatetime != nil { - req.QueryParam("start_datetime", *startDatetime) - } - if endDatetime != nil { - req.QueryParam("end_datetime", *endDatetime) - } - if customerIds != nil { - req.QueryParam("customer_ids", customerIds) - } - if number != nil { - req.QueryParam("number", number) - } - if productIds != nil { - req.QueryParam("product_ids", productIds) - } - if sort != nil { - req.QueryParam("sort", *sort) - } - var result models.ListInvoicesResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListInvoicesResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListInvoicesInput) ( + models.ApiResponse[models.ListInvoicesResponse], + error) { + req := i.prepareRequest(ctx, "GET", "/invoices.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.StartDate != nil { + req.QueryParam("start_date", *input.StartDate) + } + if input.EndDate != nil { + req.QueryParam("end_date", *input.EndDate) + } + if input.Status != nil { + req.QueryParam("status", *input.Status) + } + if input.SubscriptionId != nil { + req.QueryParam("subscription_id", *input.SubscriptionId) + } + if input.SubscriptionGroupUid != nil { + req.QueryParam("subscription_group_uid", *input.SubscriptionGroupUid) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + if input.LineItems != nil { + req.QueryParam("line_items", *input.LineItems) + } + if input.Discounts != nil { + req.QueryParam("discounts", *input.Discounts) + } + if input.Taxes != nil { + req.QueryParam("taxes", *input.Taxes) + } + if input.Credits != nil { + req.QueryParam("credits", *input.Credits) + } + if input.Payments != nil { + req.QueryParam("payments", *input.Payments) + } + if input.CustomFields != nil { + req.QueryParam("custom_fields", *input.CustomFields) + } + if input.Refunds != nil { + req.QueryParam("refunds", *input.Refunds) + } + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", *input.StartDatetime) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", *input.EndDatetime) + } + if input.CustomerIds != nil { + req.QueryParam("customer_ids", input.CustomerIds) + } + if input.Number != nil { + req.QueryParam("number", input.Number) + } + if input.ProductIds != nil { + req.QueryParam("product_ids", input.ProductIds) + } + if input.Sort != nil { + req.QueryParam("sort", *input.Sort) + } + var result models.ListInvoicesResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListInvoicesResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadInvoice takes context, uid as parameters and -// returns an models.ApiResponse with models.Invoice data and -// an error if there was an issue with the request or response. +// ReadInvoice takes context, uid as parameters and +// returns an models.ApiResponse with models.Invoice data and +// an error if there was an issue with the request or response. // Use this endpoint to retrieve the details for an invoice. func (i *InvoicesController) ReadInvoice( - ctx context.Context, - uid string) ( - models.ApiResponse[models.Invoice], - error) { - req := i.prepareRequest(ctx, "GET", fmt.Sprintf("/invoices/%v.json", uid)) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.Invoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.Invoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string) ( + models.ApiResponse[models.Invoice], + error) { + req := i.prepareRequest(ctx, "GET", fmt.Sprintf("/invoices/%v.json", uid)) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.Invoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.Invoice](decoder) + return models.NewApiResponse(result, resp), err } -// ListInvoiceEvents takes context, sinceDate, sinceId, page, perPage, invoiceUid, withChangeInvoiceStatus, eventTypes as parameters and -// returns an models.ApiResponse with models.ListInvoiceEventsResponse data and -// an error if there was an issue with the request or response. -// This endpoint returns a list of invoice events. Each event contains event "data" (such as an applied payment) as well as a snapshot of the `invoice` at the time of event completion. -// Exposed event types are: -// + issue_invoice -// + apply_credit_note -// + apply_payment -// + refund_invoice -// + void_invoice -// + void_remainder -// + backport_invoice -// + change_invoice_status -// + change_invoice_collection_method -// + remove_payment -// + failed_payment -// + apply_debit_note -// + create_debit_note -// + change_chargeback_status -// Invoice events are returned in ascending order. -// If both a `since_date` and `since_id` are provided in request parameters, the `since_date` will be used. +// ListInvoiceEventsInput represents the input of the ListInvoiceEvents endpoint. +type ListInvoiceEventsInput struct { + // The timestamp in a format `YYYY-MM-DD T HH:MM:SS Z`, or `YYYY-MM-DD`(in this case, it returns data from the beginning of the day). of the event from which you want to start the search. All the events before the `since_date` timestamp are not returned in the response. + SinceDate *string + // The ID of the event from which you want to start the search(ID is not included. e.g. if ID is set to 2, then all events with ID 3 and more will be shown) This parameter is not used if since_date is defined. + SinceId *int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 100. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + PerPage *int + // Providing an invoice_uid allows for scoping of the invoice events to a single invoice or credit note. + InvoiceUid *string + // Use this parameter if you want to fetch also invoice events with change_invoice_status type. + WithChangeInvoiceStatus *string + // Filter results by event_type. Supply a comma separated list of event types (listed above). Use in query: `event_types=void_invoice,void_remainder`. + EventTypes []models.InvoiceEventType +} + +// ListInvoiceEvents takes context, sinceDate, sinceId, page, perPage, invoiceUid, withChangeInvoiceStatus, eventTypes as parameters and +// returns an models.ApiResponse with models.ListInvoiceEventsResponse data and +// an error if there was an issue with the request or response. +// This endpoint returns a list of invoice events. Each event contains event "data" (such as an applied payment) as well as a snapshot of the `invoice` at the time of event completion. +// Exposed event types are: +// + issue_invoice +// + apply_credit_note +// + apply_payment +// + refund_invoice +// + void_invoice +// + void_remainder +// + backport_invoice +// + change_invoice_status +// + change_invoice_collection_method +// + remove_payment +// + failed_payment +// + apply_debit_note +// + create_debit_note +// + change_chargeback_status +// Invoice events are returned in ascending order. +// If both a `since_date` and `since_id` are provided in request parameters, the `since_date` will be used. // Note - invoice events that occurred prior to 09/05/2018 __will not__ contain an `invoice` snapshot. func (i *InvoicesController) ListInvoiceEvents( - ctx context.Context, - sinceDate *string, - sinceId *int, - page *int, - perPage *int, - invoiceUid *string, - withChangeInvoiceStatus *string, - eventTypes []models.InvoiceEventType) ( - models.ApiResponse[models.ListInvoiceEventsResponse], - error) { - req := i.prepareRequest(ctx, "GET", "/invoices/events.json") - req.Authenticate(NewAuth("BasicAuth")) - if sinceDate != nil { - req.QueryParam("since_date", *sinceDate) - } - if sinceId != nil { - req.QueryParam("since_id", *sinceId) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if invoiceUid != nil { - req.QueryParam("invoice_uid", *invoiceUid) - } - if withChangeInvoiceStatus != nil { - req.QueryParam("with_change_invoice_status", *withChangeInvoiceStatus) - } - if eventTypes != nil { - req.QueryParam("event_types", eventTypes) - } - var result models.ListInvoiceEventsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListInvoiceEventsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListInvoiceEventsInput) ( + models.ApiResponse[models.ListInvoiceEventsResponse], + error) { + req := i.prepareRequest(ctx, "GET", "/invoices/events.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.SinceDate != nil { + req.QueryParam("since_date", *input.SinceDate) + } + if input.SinceId != nil { + req.QueryParam("since_id", *input.SinceId) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.InvoiceUid != nil { + req.QueryParam("invoice_uid", *input.InvoiceUid) + } + if input.WithChangeInvoiceStatus != nil { + req.QueryParam("with_change_invoice_status", *input.WithChangeInvoiceStatus) + } + if input.EventTypes != nil { + req.QueryParam("event_types", input.EventTypes) + } + var result models.ListInvoiceEventsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListInvoiceEventsResponse](decoder) + return models.NewApiResponse(result, resp), err } -// RecordPaymentForInvoice takes context, uid, body as parameters and -// returns an models.ApiResponse with models.Invoice data and -// an error if there was an issue with the request or response. -// This API call should be used when you want to record a payment of a given type against a specific invoice. If you would like to apply a payment across multiple invoices, you can use the Bulk Payment endpoint. -// ## Create a Payment from the existing payment profile -// In order to apply a payment to an invoice using an existing payment profile, specify `type` as `payment`, the amount less than the invoice total, and the customer's `payment_profile_id`. The ID of a payment profile might be retrieved via the Payment Profiles API endpoint. -// ``` -// { -// "type": "payment", -// "payment": { -// "amount": 10.00, -// "payment_profile_id": 123 -// } -// } -// ``` -// ## Create a Payment from the Subscription's Prepayment Account -// In order apply a prepayment to an invoice, specify the `type` as `prepayment`, and also the `amount`. -// ``` -// { -// "type": "prepayment", -// "payment": { -// "amount": 10.00 -// } -// } -// ``` -// Note that the `amount` must be less than or equal to the Subscription's Prepayment account balance. -// ## Create a Payment from the Subscription's Service Credit Account -// In order to apply a service credit to an invoice, specify the `type` as `service_credit`, and also the `amount`: -// ``` -// { -// "type": "service_credit", -// "payment": { -// "amount": 10.00 -// } -// } -// ``` +// RecordPaymentForInvoice takes context, uid, body as parameters and +// returns an models.ApiResponse with models.Invoice data and +// an error if there was an issue with the request or response. +// This API call should be used when you want to record a payment of a given type against a specific invoice. If you would like to apply a payment across multiple invoices, you can use the Bulk Payment endpoint. +// ## Create a Payment from the existing payment profile +// In order to apply a payment to an invoice using an existing payment profile, specify `type` as `payment`, the amount less than the invoice total, and the customer's `payment_profile_id`. The ID of a payment profile might be retrieved via the Payment Profiles API endpoint. +// ``` +// { +// "type": "payment", +// "payment": { +// "amount": 10.00, +// "payment_profile_id": 123 +// } +// } +// ``` +// ## Create a Payment from the Subscription's Prepayment Account +// In order apply a prepayment to an invoice, specify the `type` as `prepayment`, and also the `amount`. +// ``` +// { +// "type": "prepayment", +// "payment": { +// "amount": 10.00 +// } +// } +// ``` +// Note that the `amount` must be less than or equal to the Subscription's Prepayment account balance. +// ## Create a Payment from the Subscription's Service Credit Account +// In order to apply a service credit to an invoice, specify the `type` as `service_credit`, and also the `amount`: +// ``` +// { +// "type": "service_credit", +// "payment": { +// "amount": 10.00 +// } +// } +// ``` // Note that Chargify will attempt to fully pay the invoice's `due_amount` from the Subscription's Service Credit account. At this time, partial payments from a Service Credit Account are only allowed for consolidated invoices (subscription groups). Therefore, for normal invoices the Service Credit account balance must be greater than or equal to the invoice's `due_amount`. func (i *InvoicesController) RecordPaymentForInvoice( - ctx context.Context, - uid string, - body *models.CreateInvoicePaymentRequest) ( - models.ApiResponse[models.Invoice], - error) { - req := i.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/invoices/%v/payments.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.Invoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.Invoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string, + body *models.CreateInvoicePaymentRequest) ( + models.ApiResponse[models.Invoice], + error) { + req := i.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/invoices/%v/payments.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.Invoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.Invoice](decoder) + return models.NewApiResponse(result, resp), err } -// RecordPaymentForMultipleInvoices takes context, body as parameters and -// returns an models.ApiResponse with models.MultiInvoicePaymentResponse data and -// an error if there was an issue with the request or response. -// This API call should be used when you want to record an external payment against multiple invoices. -// In order apply a payment to multiple invoices, at minimum, specify the `amount` and `applications` (i.e., `invoice_uid` and `amount`) details. -// ``` -// { -// "payment": { -// "memo": "to pay the bills", -// "details": "check number 8675309", -// "method": "check", -// "amount": "250.00", -// "applications": [ -// { -// "invoice_uid": "inv_8gk5bwkct3gqt", -// "amount": "100.00" -// }, -// { -// "invoice_uid": "inv_7bc6bwkct3lyt", -// "amount": "150.00" -// } -// ] -// } -// } -// ``` +// RecordPaymentForMultipleInvoices takes context, body as parameters and +// returns an models.ApiResponse with models.MultiInvoicePaymentResponse data and +// an error if there was an issue with the request or response. +// This API call should be used when you want to record an external payment against multiple invoices. +// In order apply a payment to multiple invoices, at minimum, specify the `amount` and `applications` (i.e., `invoice_uid` and `amount`) details. +// ``` +// { +// "payment": { +// "memo": "to pay the bills", +// "details": "check number 8675309", +// "method": "check", +// "amount": "250.00", +// "applications": [ +// { +// "invoice_uid": "inv_8gk5bwkct3gqt", +// "amount": "100.00" +// }, +// { +// "invoice_uid": "inv_7bc6bwkct3lyt", +// "amount": "150.00" +// } +// ] +// } +// } +// ``` // Note that the invoice payment amounts must be greater than 0. Total amount must be greater or equal to invoices payment amount sum. func (i *InvoicesController) RecordPaymentForMultipleInvoices( - ctx context.Context, - body *models.CreateMultiInvoicePaymentRequest) ( - models.ApiResponse[models.MultiInvoicePaymentResponse], - error) { - req := i.prepareRequest(ctx, "POST", "/invoices/payments.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.MultiInvoicePaymentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.MultiInvoicePaymentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.CreateMultiInvoicePaymentRequest) ( + models.ApiResponse[models.MultiInvoicePaymentResponse], + error) { + req := i.prepareRequest(ctx, "POST", "/invoices/payments.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.MultiInvoicePaymentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.MultiInvoicePaymentResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListCreditNotesInput represents the input of the ListCreditNotes endpoint. +type ListCreditNotesInput struct { + // The subscription's Chargify id + SubscriptionId *int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // Include line items data + LineItems *bool + // Include discounts data + Discounts *bool + // Include taxes data + Taxes *bool + // Include refunds data + Refunds *bool + // Include applications data + Applications *bool } -// ListCreditNotes takes context, subscriptionId, page, perPage, lineItems, discounts, taxes, refunds, applications as parameters and -// returns an models.ApiResponse with models.ListCreditNotesResponse data and -// an error if there was an issue with the request or response. -// Credit Notes are like inverse invoices. They reduce the amount a customer owes. +// ListCreditNotes takes context, subscriptionId, page, perPage, lineItems, discounts, taxes, refunds, applications as parameters and +// returns an models.ApiResponse with models.ListCreditNotesResponse data and +// an error if there was an issue with the request or response. +// Credit Notes are like inverse invoices. They reduce the amount a customer owes. // By default, the credit notes returned by this endpoint will exclude the arrays of `line_items`, `discounts`, `taxes`, `applications`, or `refunds`. To include these arrays, pass the specific field as a key in the query with a value set to `true`. func (i *InvoicesController) ListCreditNotes( - ctx context.Context, - subscriptionId *int, - page *int, - perPage *int, - lineItems *bool, - discounts *bool, - taxes *bool, - refunds *bool, - applications *bool) ( - models.ApiResponse[models.ListCreditNotesResponse], - error) { - req := i.prepareRequest(ctx, "GET", "/credit_notes.json") - req.Authenticate(NewAuth("BasicAuth")) - if subscriptionId != nil { - req.QueryParam("subscription_id", *subscriptionId) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if lineItems != nil { - req.QueryParam("line_items", *lineItems) - } - if discounts != nil { - req.QueryParam("discounts", *discounts) - } - if taxes != nil { - req.QueryParam("taxes", *taxes) - } - if refunds != nil { - req.QueryParam("refunds", *refunds) - } - if applications != nil { - req.QueryParam("applications", *applications) - } - var result models.ListCreditNotesResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListCreditNotesResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListCreditNotesInput) ( + models.ApiResponse[models.ListCreditNotesResponse], + error) { + req := i.prepareRequest(ctx, "GET", "/credit_notes.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.SubscriptionId != nil { + req.QueryParam("subscription_id", *input.SubscriptionId) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.LineItems != nil { + req.QueryParam("line_items", *input.LineItems) + } + if input.Discounts != nil { + req.QueryParam("discounts", *input.Discounts) + } + if input.Taxes != nil { + req.QueryParam("taxes", *input.Taxes) + } + if input.Refunds != nil { + req.QueryParam("refunds", *input.Refunds) + } + if input.Applications != nil { + req.QueryParam("applications", *input.Applications) + } + var result models.ListCreditNotesResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListCreditNotesResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadCreditNote takes context, uid as parameters and -// returns an models.ApiResponse with models.CreditNote data and -// an error if there was an issue with the request or response. +// ReadCreditNote takes context, uid as parameters and +// returns an models.ApiResponse with models.CreditNote data and +// an error if there was an issue with the request or response. // Use this endpoint to retrieve the details for a credit note. func (i *InvoicesController) ReadCreditNote( - ctx context.Context, - uid string) ( - models.ApiResponse[models.CreditNote], - error) { - req := i.prepareRequest(ctx, "GET", fmt.Sprintf("/credit_notes/%v.json", uid)) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.CreditNote - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CreditNote](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string) ( + models.ApiResponse[models.CreditNote], + error) { + req := i.prepareRequest(ctx, "GET", fmt.Sprintf("/credit_notes/%v.json", uid)) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.CreditNote + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CreditNote](decoder) + return models.NewApiResponse(result, resp), err } -// RecordPaymentForSubscription takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.RecordPaymentResponse data and -// an error if there was an issue with the request or response. -// Record an external payment made against a subscription that will pay partially or in full one or more invoices. -// Payment will be applied starting with the oldest open invoice and then next oldest, and so on until the amount of the payment is fully consumed. -// Excess payment will result in the creation of a prepayment on the Invoice Account. +// RecordPaymentForSubscription takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.RecordPaymentResponse data and +// an error if there was an issue with the request or response. +// Record an external payment made against a subscription that will pay partially or in full one or more invoices. +// Payment will be applied starting with the oldest open invoice and then next oldest, and so on until the amount of the payment is fully consumed. +// Excess payment will result in the creation of a prepayment on the Invoice Account. // Only ungrouped or primary subscriptions may be paid using the "bulk" payment request. func (i *InvoicesController) RecordPaymentForSubscription( - ctx context.Context, - subscriptionId int, - body *models.RecordPaymentRequest) ( - models.ApiResponse[models.RecordPaymentResponse], - error) { - req := i.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/payments.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.RecordPaymentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.RecordPaymentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.RecordPaymentRequest) ( + models.ApiResponse[models.RecordPaymentResponse], + error) { + req := i.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/payments.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.RecordPaymentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.RecordPaymentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReopenInvoice takes context, uid as parameters and -// returns an models.ApiResponse with models.Invoice data and -// an error if there was an issue with the request or response. -// This endpoint allows you to reopen any invoice with the "canceled" status. Invoices enter "canceled" status if they were open at the time the subscription was canceled (whether through dunning or an intentional cancellation). -// Invoices with "canceled" status are no longer considered to be due. Once reopened, they are considered due for payment. Payment may then be captured in one of the following ways: -// - Reactivating the subscription, which will capture all open invoices (See note below about automatic reopening of invoices.) -// - Recording a payment directly against the invoice -// A note about reactivations: any canceled invoices from the most recent active period are automatically opened as a part of the reactivation process. Reactivating via this endpoint prior to reactivation is only necessary when you wish to capture older invoices from previous periods during the reactivation. -// ### Reopening Consolidated Invoices +// ReopenInvoice takes context, uid as parameters and +// returns an models.ApiResponse with models.Invoice data and +// an error if there was an issue with the request or response. +// This endpoint allows you to reopen any invoice with the "canceled" status. Invoices enter "canceled" status if they were open at the time the subscription was canceled (whether through dunning or an intentional cancellation). +// Invoices with "canceled" status are no longer considered to be due. Once reopened, they are considered due for payment. Payment may then be captured in one of the following ways: +// - Reactivating the subscription, which will capture all open invoices (See note below about automatic reopening of invoices.) +// - Recording a payment directly against the invoice +// A note about reactivations: any canceled invoices from the most recent active period are automatically opened as a part of the reactivation process. Reactivating via this endpoint prior to reactivation is only necessary when you wish to capture older invoices from previous periods during the reactivation. +// ### Reopening Consolidated Invoices // When reopening a consolidated invoice, all of its canceled segments will also be reopened. func (i *InvoicesController) ReopenInvoice( - ctx context.Context, - uid string) ( - models.ApiResponse[models.Invoice], - error) { - req := i.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/invoices/%v/reopen.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.Invoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.Invoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string) ( + models.ApiResponse[models.Invoice], + error) { + req := i.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/invoices/%v/reopen.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.Invoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.Invoice](decoder) + return models.NewApiResponse(result, resp), err } -// VoidInvoice takes context, uid, body as parameters and -// returns an models.ApiResponse with models.Invoice data and -// an error if there was an issue with the request or response. +// VoidInvoice takes context, uid, body as parameters and +// returns an models.ApiResponse with models.Invoice data and +// an error if there was an issue with the request or response. // This endpoint allows you to void any invoice with the "open" or "canceled" status. It will also allow voiding of an invoice with the "pending" status if it is not a consolidated invoice. func (i *InvoicesController) VoidInvoice( - ctx context.Context, - uid string, - body *models.VoidInvoiceRequest) ( - models.ApiResponse[models.Invoice], - error) { - req := i.prepareRequest(ctx, "POST", fmt.Sprintf("/invoices/%v/void.json", uid)) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.Invoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.Invoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string, + body *models.VoidInvoiceRequest) ( + models.ApiResponse[models.Invoice], + error) { + req := i.prepareRequest(ctx, "POST", fmt.Sprintf("/invoices/%v/void.json", uid)) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.Invoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.Invoice](decoder) + return models.NewApiResponse(result, resp), err } -// ListConsolidatedInvoiceSegments takes context, invoiceUid, page, perPage, direction as parameters and -// returns an models.ApiResponse with models.ConsolidatedInvoice data and -// an error if there was an issue with the request or response. +// ListConsolidatedInvoiceSegmentsInput represents the input of the ListConsolidatedInvoiceSegments endpoint. +type ListConsolidatedInvoiceSegmentsInput struct { + // The unique identifier of the consolidated invoice + InvoiceUid string + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // Sort direction of the returned segments. + Direction *models.Direction +} + +// ListConsolidatedInvoiceSegments takes context, invoiceUid, page, perPage, direction as parameters and +// returns an models.ApiResponse with models.ConsolidatedInvoice data and +// an error if there was an issue with the request or response. // Invoice segments returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, or `custom_fields`. func (i *InvoicesController) ListConsolidatedInvoiceSegments( - ctx context.Context, - invoiceUid string, - page *int, - perPage *int, - direction *models.Direction) ( - models.ApiResponse[models.ConsolidatedInvoice], - error) { - req := i.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/invoices/%v/segments.json", invoiceUid), - ) - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - - var result models.ConsolidatedInvoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ConsolidatedInvoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListConsolidatedInvoiceSegmentsInput) ( + models.ApiResponse[models.ConsolidatedInvoice], + error) { + req := i.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/invoices/%v/segments.json", input.InvoiceUid), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + + var result models.ConsolidatedInvoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ConsolidatedInvoice](decoder) + return models.NewApiResponse(result, resp), err } -// CreateInvoice takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.InvoiceResponse data and -// an error if there was an issue with the request or response. -// This endpoint will allow you to create an ad hoc invoice. -// ### Basic Behavior -// You can create a basic invoice by sending an array of line items to this endpoint. Each line item, at a minimum, must include a title, a quantity and a unit price. Example: -// ```json -// { -// "invoice": { -// "line_items": [ -// { -// "title": "A Product", -// "quantity": 12, -// "unit_price": "150.00" -// } -// ] -// } -// } -// ``` -// ### Catalog items -// Instead of creating custom products like in above example, You can pass existing items like products, components. -// ```json -// { -// "invoice": { -// "line_items": [ -// { -// "product_id": "handle:gold-product", -// "quantity": 2, -// } -// ] -// } -// } -// ``` -// The price for each line item will be calculated as well as a total due amount for the invoice. Multiple line items can be sent. -// ### Line items types -// When defining line item, You can choose one of 3 types for one line item: -// #### Custom item -// Like in basic behavior example above, You can pass `title` and `unit_price` for custom item. -// #### Product id -// Product handle (with handle: prefix) or id from the scope of current subscription's site can be provided with `product_id`. By default `unit_price` is taken from product's default price point, but can be overwritten by passing `unit_price` or `product_price_point_id`. If `product_id` is used, following fields cannot be used: `title`, `component_id`. -// #### Component id -// Component handle (with handle: prefix) or id from the scope of current subscription's site can be provided with `component_id`. If `component_id` is used, following fields cannot be used: `title`, `product_id`. By default `unit_price` is taken from product's default price point, but can be overwritten by passing `unit_price` or `price_point_id`. At this moment price points are supportted only for quantity based, on/off and metered components. For prepaid and event based billing components `unit_price` is required. -// ### Coupons -// When creating ad hoc invoice, new discounts can be applied in following way: -// ```json -// { -// "invoice": { -// "line_items": [ -// { -// "product_id": "handle:gold-product", -// "quantity": 1 -// } -// ], -// "coupons": [ -// { -// "code": "COUPONCODE", -// "percentage": 50.0 -// } -// ] -// } -// } -// ``` -// If You want to use existing coupon for discount creation, only `code` and optional `product_family_id` is needed -// ```json -// ... -// "coupons": [ -// { -// "code": "FREESETUP", -// "product_family_id": 1 -// } -// ] -// ... -// ``` -// ### Coupon options -// #### Code -// Coupon `code` will be displayed on invoice discount section. -// Coupon code can only contain uppercase letters, numbers, and allowed special characters. -// Lowercase letters will be converted to uppercase. It can be used to select an existing coupon from the catalog, or as an ad hoc coupon when passed with `percentage` or `amount`. -// #### Percentage -// Coupon `percentage` can take values from 0 to 100 and up to 4 decimal places. It cannot be used with `amount`. Only for ad hoc coupons, will be ignored if `code` is used to select an existing coupon from the catalog. -// #### Amount -// Coupon `amount` takes number value. It cannot be used with `percentage`. Used only when not matching existing coupon by `code`. -// #### Description -// Optional `description` will be displayed with coupon `code`. Used only when not matching existing coupon by `code`. -// #### Product Family id -// Optional `product_family_id` handle (with handle: prefix) or id is used to match existing coupon within site, when codes are not unique. -// #### Compounding Strategy -// Optional `compounding_strategy` for percentage coupons, can take values `compound` or `full-price`. -// For amount coupons, discounts will be always calculated against the original item price, before other discounts are applied. -// `compound` strategy: -// Percentage-based discounts will be calculated against the remaining price, after prior discounts have been calculated. It is set by default. -// `full-price` strategy: -// Percentage-based discounts will always be calculated against the original item price, before other discounts are applied. -// ### Line Item Options -// #### Period Date Range -// A custom period date range can be defined for each line item with the `period_range_start` and `period_range_end` parameters. Dates must be sent in the `YYYY-MM-DD` format. -// `period_range_end` must be greater or equal `period_range_start`. -// #### Taxes -// The `taxable` parameter can be sent as `true` if taxes should be calculated for a specific line item. For this to work, the site should be configured to use and calculate taxes. Further, if the site uses Avalara for tax calculations, a `tax_code` parameter should also be sent. For existing catalog items: products/components taxes cannot be overwritten. -// #### Price Point -// Price point handle (with handle: prefix) or id from the scope of current subscription's site can be provided with `price_point_id` for components with `component_id` or `product_price_point_id` for products with `product_id` parameter. If price point is passed `unit_price` cannot be used. It can be used only with catalog items products and components. -// #### Description -// Optional `description` parameter, it will overwrite default generated description for line item. -// ### Invoice Options -// #### Issue Date -// By default, invoices will be created with a issue date set to today. `issue_date` parameter can be send to alter that. Only dates in the past can be send. `issue_date` should be send in `YYYY-MM-DD` format. -// #### Net Terms -// By default, invoices will be created with a due date matching the date of invoice creation. If a different due date is desired, the `net_terms` parameter can be sent indicating the number of days in advance the due date should be. -// #### Addresses -// The seller, shipping and billing addresses can be sent to override the site's defaults. Each address requires to send a `first_name` at a minimum in order to work. Please see below for the details on which parameters can be sent for each address object. -// #### Memo and Payment Instructions -// A custom memo can be sent with the `memo` parameter to override the site's default. Likewise, custom payment instructions can be sent with the `payment_instrucions` parameter. -// #### Status +// CreateInvoice takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.InvoiceResponse data and +// an error if there was an issue with the request or response. +// This endpoint will allow you to create an ad hoc invoice. +// ### Basic Behavior +// You can create a basic invoice by sending an array of line items to this endpoint. Each line item, at a minimum, must include a title, a quantity and a unit price. Example: +// ```json +// { +// "invoice": { +// "line_items": [ +// { +// "title": "A Product", +// "quantity": 12, +// "unit_price": "150.00" +// } +// ] +// } +// } +// ``` +// ### Catalog items +// Instead of creating custom products like in above example, You can pass existing items like products, components. +// ```json +// { +// "invoice": { +// "line_items": [ +// { +// "product_id": "handle:gold-product", +// "quantity": 2, +// } +// ] +// } +// } +// ``` +// The price for each line item will be calculated as well as a total due amount for the invoice. Multiple line items can be sent. +// ### Line items types +// When defining line item, You can choose one of 3 types for one line item: +// #### Custom item +// Like in basic behavior example above, You can pass `title` and `unit_price` for custom item. +// #### Product id +// Product handle (with handle: prefix) or id from the scope of current subscription's site can be provided with `product_id`. By default `unit_price` is taken from product's default price point, but can be overwritten by passing `unit_price` or `product_price_point_id`. If `product_id` is used, following fields cannot be used: `title`, `component_id`. +// #### Component id +// Component handle (with handle: prefix) or id from the scope of current subscription's site can be provided with `component_id`. If `component_id` is used, following fields cannot be used: `title`, `product_id`. By default `unit_price` is taken from product's default price point, but can be overwritten by passing `unit_price` or `price_point_id`. At this moment price points are supportted only for quantity based, on/off and metered components. For prepaid and event based billing components `unit_price` is required. +// ### Coupons +// When creating ad hoc invoice, new discounts can be applied in following way: +// ```json +// { +// "invoice": { +// "line_items": [ +// { +// "product_id": "handle:gold-product", +// "quantity": 1 +// } +// ], +// "coupons": [ +// { +// "code": "COUPONCODE", +// "percentage": 50.0 +// } +// ] +// } +// } +// ``` +// If You want to use existing coupon for discount creation, only `code` and optional `product_family_id` is needed +// ```json +// ... +// "coupons": [ +// { +// "code": "FREESETUP", +// "product_family_id": 1 +// } +// ] +// ... +// ``` +// ### Coupon options +// #### Code +// Coupon `code` will be displayed on invoice discount section. +// Coupon code can only contain uppercase letters, numbers, and allowed special characters. +// Lowercase letters will be converted to uppercase. It can be used to select an existing coupon from the catalog, or as an ad hoc coupon when passed with `percentage` or `amount`. +// #### Percentage +// Coupon `percentage` can take values from 0 to 100 and up to 4 decimal places. It cannot be used with `amount`. Only for ad hoc coupons, will be ignored if `code` is used to select an existing coupon from the catalog. +// #### Amount +// Coupon `amount` takes number value. It cannot be used with `percentage`. Used only when not matching existing coupon by `code`. +// #### Description +// Optional `description` will be displayed with coupon `code`. Used only when not matching existing coupon by `code`. +// #### Product Family id +// Optional `product_family_id` handle (with handle: prefix) or id is used to match existing coupon within site, when codes are not unique. +// #### Compounding Strategy +// Optional `compounding_strategy` for percentage coupons, can take values `compound` or `full-price`. +// For amount coupons, discounts will be always calculated against the original item price, before other discounts are applied. +// `compound` strategy: +// Percentage-based discounts will be calculated against the remaining price, after prior discounts have been calculated. It is set by default. +// `full-price` strategy: +// Percentage-based discounts will always be calculated against the original item price, before other discounts are applied. +// ### Line Item Options +// #### Period Date Range +// A custom period date range can be defined for each line item with the `period_range_start` and `period_range_end` parameters. Dates must be sent in the `YYYY-MM-DD` format. +// `period_range_end` must be greater or equal `period_range_start`. +// #### Taxes +// The `taxable` parameter can be sent as `true` if taxes should be calculated for a specific line item. For this to work, the site should be configured to use and calculate taxes. Further, if the site uses Avalara for tax calculations, a `tax_code` parameter should also be sent. For existing catalog items: products/components taxes cannot be overwritten. +// #### Price Point +// Price point handle (with handle: prefix) or id from the scope of current subscription's site can be provided with `price_point_id` for components with `component_id` or `product_price_point_id` for products with `product_id` parameter. If price point is passed `unit_price` cannot be used. It can be used only with catalog items products and components. +// #### Description +// Optional `description` parameter, it will overwrite default generated description for line item. +// ### Invoice Options +// #### Issue Date +// By default, invoices will be created with a issue date set to today. `issue_date` parameter can be send to alter that. Only dates in the past can be send. `issue_date` should be send in `YYYY-MM-DD` format. +// #### Net Terms +// By default, invoices will be created with a due date matching the date of invoice creation. If a different due date is desired, the `net_terms` parameter can be sent indicating the number of days in advance the due date should be. +// #### Addresses +// The seller, shipping and billing addresses can be sent to override the site's defaults. Each address requires to send a `first_name` at a minimum in order to work. Please see below for the details on which parameters can be sent for each address object. +// #### Memo and Payment Instructions +// A custom memo can be sent with the `memo` parameter to override the site's default. Likewise, custom payment instructions can be sent with the `payment_instrucions` parameter. +// #### Status // By default, invoices will be created with open status. Possible alternative is `draft`. func (i *InvoicesController) CreateInvoice( - ctx context.Context, - subscriptionId int, - body *models.CreateInvoiceRequest) ( - models.ApiResponse[models.InvoiceResponse], - error) { - req := i.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/invoices.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.InvoiceResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.InvoiceResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.CreateInvoiceRequest) ( + models.ApiResponse[models.InvoiceResponse], + error) { + req := i.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/invoices.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.InvoiceResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.InvoiceResponse](decoder) + return models.NewApiResponse(result, resp), err } -// SendInvoice takes context, uid, body as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// This endpoint allows for invoices to be programmatically delivered via email. This endpoint supports the delivery of both ad-hoc and automatically generated invoices. Additionally, this endpoint supports email delivery to direct recipients, carbon-copy (cc) recipients, and blind carbon-copy (bcc) recipients. -// Please note that if no recipient email addresses are specified in the request, then the subscription's default email configuration will be used. For example, if `recipient_emails` is left blank, then the invoice will be delivered to the subscription's customer email address. +// SendInvoice takes context, uid, body as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// This endpoint allows for invoices to be programmatically delivered via email. This endpoint supports the delivery of both ad-hoc and automatically generated invoices. Additionally, this endpoint supports email delivery to direct recipients, carbon-copy (cc) recipients, and blind carbon-copy (bcc) recipients. +// Please note that if no recipient email addresses are specified in the request, then the subscription's default email configuration will be used. For example, if `recipient_emails` is left blank, then the invoice will be delivered to the subscription's customer email address. // On success, a 204 no-content response will be returned. Please note that this does not indicate that email(s) have been delivered, but instead indicates that emails have been successfully queued for delivery. If _any_ invalid or malformed email address is found in the request body, the entire request will be rejected and a 422 response will be returned. func (i *InvoicesController) SendInvoice( - ctx context.Context, - uid string, - body *models.SendInvoiceRequest) ( - *http.Response, - error) { - req := i.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/invoices/%v/deliveries.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + uid string, + body *models.SendInvoiceRequest) ( + *http.Response, + error) { + req := i.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/invoices/%v/deliveries.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// PreviewCustomerInformationChanges takes context, uid as parameters and -// returns an models.ApiResponse with models.CustomerChangesPreviewResponse data and -// an error if there was an issue with the request or response. -// Customer information may change after an invoice is issued which may lead to a mismatch between customer information that are present on an open invoice and actual customer information. This endpoint allows to preview these differences, if any. +// PreviewCustomerInformationChanges takes context, uid as parameters and +// returns an models.ApiResponse with models.CustomerChangesPreviewResponse data and +// an error if there was an issue with the request or response. +// Customer information may change after an invoice is issued which may lead to a mismatch between customer information that are present on an open invoice and actual customer information. This endpoint allows to preview these differences, if any. // The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. func (i *InvoicesController) PreviewCustomerInformationChanges( - ctx context.Context, - uid string) ( - models.ApiResponse[models.CustomerChangesPreviewResponse], - error) { - req := i.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/invoices/%v/customer_information/preview.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'", Unmarshaller: errors.NewErrorListResponse}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.CustomerChangesPreviewResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CustomerChangesPreviewResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string) ( + models.ApiResponse[models.CustomerChangesPreviewResponse], + error) { + req := i.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/invoices/%v/customer_information/preview.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'", Unmarshaller: errors.NewErrorListResponse}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.CustomerChangesPreviewResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CustomerChangesPreviewResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateCustomerInformation takes context, uid as parameters and -// returns an models.ApiResponse with models.Invoice data and -// an error if there was an issue with the request or response. -// This endpoint updates customer information on an open invoice and returns the updated invoice. If you would like to preview changes that will be applied, use the `/invoices/{uid}/customer_information/preview.json` endpoint before. +// UpdateCustomerInformation takes context, uid as parameters and +// returns an models.ApiResponse with models.Invoice data and +// an error if there was an issue with the request or response. +// This endpoint updates customer information on an open invoice and returns the updated invoice. If you would like to preview changes that will be applied, use the `/invoices/{uid}/customer_information/preview.json` endpoint before. // The endpoint doesn't accept a request body. Customer information differences are calculated on the application side. func (i *InvoicesController) UpdateCustomerInformation( - ctx context.Context, - uid string) ( - models.ApiResponse[models.Invoice], - error) { - req := i.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/invoices/%v/customer_information.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'", Unmarshaller: errors.NewErrorListResponse}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.Invoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.Invoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string) ( + models.ApiResponse[models.Invoice], + error) { + req := i.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/invoices/%v/customer_information.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'", Unmarshaller: errors.NewErrorListResponse}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.Invoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.Invoice](decoder) + return models.NewApiResponse(result, resp), err } -// IssueInvoice takes context, uid, body as parameters and -// returns an models.ApiResponse with models.Invoice data and -// an error if there was an issue with the request or response. -// This endpoint allows you to issue an invoice that is in "pending" status. For example, you can issue an invoice that was created when allocating new quantity on a component and using "accrue charges" option. -// You cannot issue a pending child invoice that was created for a member subscription in a group. -// For Remittance subscriptions, the invoice will go into "open" status and payment won't be attempted. The value for `on_failed_payment` would be rejected if sent. Any prepayments or service credits that exist on subscription will be automatically applied. Additionally, if setting is on, an email will be sent for issued invoice. -// For Automatic subscriptions, prepayments and service credits will apply to the invoice and before payment is attempted. On successful payment, the invoice will go into "paid" status and email will be sent to the customer (if setting applies). When payment fails, the next event depends on the `on_failed_payment` value: -// - `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. -// - `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. +// IssueInvoice takes context, uid, body as parameters and +// returns an models.ApiResponse with models.Invoice data and +// an error if there was an issue with the request or response. +// This endpoint allows you to issue an invoice that is in "pending" status. For example, you can issue an invoice that was created when allocating new quantity on a component and using "accrue charges" option. +// You cannot issue a pending child invoice that was created for a member subscription in a group. +// For Remittance subscriptions, the invoice will go into "open" status and payment won't be attempted. The value for `on_failed_payment` would be rejected if sent. Any prepayments or service credits that exist on subscription will be automatically applied. Additionally, if setting is on, an email will be sent for issued invoice. +// For Automatic subscriptions, prepayments and service credits will apply to the invoice and before payment is attempted. On successful payment, the invoice will go into "paid" status and email will be sent to the customer (if setting applies). When payment fails, the next event depends on the `on_failed_payment` value: +// - `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. +// - `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. // - `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). func (i *InvoicesController) IssueInvoice( - ctx context.Context, - uid string, - body *models.IssueInvoiceRequest) ( - models.ApiResponse[models.Invoice], - error) { - req := i.prepareRequest(ctx, "POST", fmt.Sprintf("/invoices/%v/issue.json", uid)) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.Invoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.Invoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string, + body *models.IssueInvoiceRequest) ( + models.ApiResponse[models.Invoice], + error) { + req := i.prepareRequest(ctx, "POST", fmt.Sprintf("/invoices/%v/issue.json", uid)) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.Invoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.Invoice](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/models/account_balance.go b/models/account_balance.go index eee7f8ce..8d8b471f 100644 --- a/models/account_balance.go +++ b/models/account_balance.go @@ -1,43 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" ) // AccountBalance represents a AccountBalance struct. type AccountBalance struct { - // The balance in cents. - BalanceInCents *int64 `json:"balance_in_cents,omitempty"` + // The balance in cents. + BalanceInCents *int64 `json:"balance_in_cents,omitempty"` + // The automatic balance in cents. + AutomaticBalanceInCents Optional[int64] `json:"automatic_balance_in_cents"` + // The remittance balance in cents. + RemittanceBalanceInCents Optional[int64] `json:"remittance_balance_in_cents"` } -// MarshalJSON implements the json.Marshaler interface for AccountBalance. +// MarshalJSON implements the json.Marshaler interface for AccountBalance. // It customizes the JSON marshaling process for AccountBalance objects. func (a *AccountBalance) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AccountBalance object to a map representation for JSON marshaling. func (a *AccountBalance) toMap() map[string]any { - structMap := make(map[string]any) - if a.BalanceInCents != nil { - structMap["balance_in_cents"] = a.BalanceInCents - } - return structMap + structMap := make(map[string]any) + if a.BalanceInCents != nil { + structMap["balance_in_cents"] = a.BalanceInCents + } + if a.AutomaticBalanceInCents.IsValueSet() { + if a.AutomaticBalanceInCents.Value() != nil { + structMap["automatic_balance_in_cents"] = a.AutomaticBalanceInCents.Value() + } else { + structMap["automatic_balance_in_cents"] = nil + } + } + if a.RemittanceBalanceInCents.IsValueSet() { + if a.RemittanceBalanceInCents.Value() != nil { + structMap["remittance_balance_in_cents"] = a.RemittanceBalanceInCents.Value() + } else { + structMap["remittance_balance_in_cents"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AccountBalance. +// UnmarshalJSON implements the json.Unmarshaler interface for AccountBalance. // It customizes the JSON unmarshaling process for AccountBalance objects. func (a *AccountBalance) UnmarshalJSON(input []byte) error { - temp := &struct { - BalanceInCents *int64 `json:"balance_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.BalanceInCents = temp.BalanceInCents - return nil + var temp accountBalance + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.BalanceInCents = temp.BalanceInCents + a.AutomaticBalanceInCents = temp.AutomaticBalanceInCents + a.RemittanceBalanceInCents = temp.RemittanceBalanceInCents + return nil +} + +// TODO +type accountBalance struct { + BalanceInCents *int64 `json:"balance_in_cents,omitempty"` + AutomaticBalanceInCents Optional[int64] `json:"automatic_balance_in_cents"` + RemittanceBalanceInCents Optional[int64] `json:"remittance_balance_in_cents"` } diff --git a/models/account_balances.go b/models/account_balances.go index d98b360d..8ec3b1e3 100644 --- a/models/account_balances.go +++ b/models/account_balances.go @@ -1,64 +1,73 @@ package models import ( - "encoding/json" + "encoding/json" ) // AccountBalances represents a AccountBalances struct. type AccountBalances struct { - // The balance, in cents, of the sum of the subscription's open, payable invoices. - OpenInvoices *AccountBalance `json:"open_invoices,omitempty"` - // The balance, in cents, of the subscription's Pending Discount account. - PendingDiscounts *AccountBalance `json:"pending_discounts,omitempty"` - // The balance, in cents, of the subscription's Service Credit account. - ServiceCredits *AccountBalance `json:"service_credits,omitempty"` - // The balance, in cents, of the subscription's Prepayment account. - Prepayments *AccountBalance `json:"prepayments,omitempty"` + // The balance, in cents, of the sum of the subscription's open, payable invoices. + OpenInvoices *AccountBalance `json:"open_invoices,omitempty"` + // The balance, in cents, of the sum of the subscription's pending, payable invoices. + PendingInvoices *AccountBalance `json:"pending_invoices,omitempty"` + // The balance, in cents, of the subscription's Pending Discount account. + PendingDiscounts *AccountBalance `json:"pending_discounts,omitempty"` + // The balance, in cents, of the subscription's Service Credit account. + ServiceCredits *AccountBalance `json:"service_credits,omitempty"` + // The balance, in cents, of the subscription's Prepayment account. + Prepayments *AccountBalance `json:"prepayments,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for AccountBalances. +// MarshalJSON implements the json.Marshaler interface for AccountBalances. // It customizes the JSON marshaling process for AccountBalances objects. func (a *AccountBalances) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AccountBalances object to a map representation for JSON marshaling. func (a *AccountBalances) toMap() map[string]any { - structMap := make(map[string]any) - if a.OpenInvoices != nil { - structMap["open_invoices"] = a.OpenInvoices.toMap() - } - if a.PendingDiscounts != nil { - structMap["pending_discounts"] = a.PendingDiscounts.toMap() - } - if a.ServiceCredits != nil { - structMap["service_credits"] = a.ServiceCredits.toMap() - } - if a.Prepayments != nil { - structMap["prepayments"] = a.Prepayments.toMap() - } - return structMap + structMap := make(map[string]any) + if a.OpenInvoices != nil { + structMap["open_invoices"] = a.OpenInvoices.toMap() + } + if a.PendingInvoices != nil { + structMap["pending_invoices"] = a.PendingInvoices.toMap() + } + if a.PendingDiscounts != nil { + structMap["pending_discounts"] = a.PendingDiscounts.toMap() + } + if a.ServiceCredits != nil { + structMap["service_credits"] = a.ServiceCredits.toMap() + } + if a.Prepayments != nil { + structMap["prepayments"] = a.Prepayments.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AccountBalances. +// UnmarshalJSON implements the json.Unmarshaler interface for AccountBalances. // It customizes the JSON unmarshaling process for AccountBalances objects. func (a *AccountBalances) UnmarshalJSON(input []byte) error { - temp := &struct { - OpenInvoices *AccountBalance `json:"open_invoices,omitempty"` - PendingDiscounts *AccountBalance `json:"pending_discounts,omitempty"` - ServiceCredits *AccountBalance `json:"service_credits,omitempty"` - Prepayments *AccountBalance `json:"prepayments,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.OpenInvoices = temp.OpenInvoices - a.PendingDiscounts = temp.PendingDiscounts - a.ServiceCredits = temp.ServiceCredits - a.Prepayments = temp.Prepayments - return nil + var temp accountBalances + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.OpenInvoices = temp.OpenInvoices + a.PendingInvoices = temp.PendingInvoices + a.PendingDiscounts = temp.PendingDiscounts + a.ServiceCredits = temp.ServiceCredits + a.Prepayments = temp.Prepayments + return nil +} + +// TODO +type accountBalances struct { + OpenInvoices *AccountBalance `json:"open_invoices,omitempty"` + PendingInvoices *AccountBalance `json:"pending_invoices,omitempty"` + PendingDiscounts *AccountBalance `json:"pending_discounts,omitempty"` + ServiceCredits *AccountBalance `json:"service_credits,omitempty"` + Prepayments *AccountBalance `json:"prepayments,omitempty"` } diff --git a/models/ach_agreement.go b/models/ach_agreement.go index 37d81bdb..539ebbea 100644 --- a/models/ach_agreement.go +++ b/models/ach_agreement.go @@ -1,65 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" ) -// ACHAgreement represents a ACHAgreement struct. +// ACHAgreement represents a ACHAgreement struct. // (Optional) If passed, the proof of the authorized ACH agreement terms will be persisted. type ACHAgreement struct { - // (Required when providing ACH agreement params) The ACH authorization agreement terms. - AgreementTerms *string `json:"agreement_terms,omitempty"` - // (Required when providing ACH agreement params) The first name of the person authorizing the ACH agreement. - AuthorizerFirstName *string `json:"authorizer_first_name,omitempty"` - // (Required when providing ACH agreement params) The last name of the person authorizing the ACH agreement. - AuthorizerLastName *string `json:"authorizer_last_name,omitempty"` - // (Required when providing ACH agreement params) The IP address of the person authorizing the ACH agreement. - IpAddress *string `json:"ip_address,omitempty"` + // (Required when providing ACH agreement params) The ACH authorization agreement terms. + AgreementTerms *string `json:"agreement_terms,omitempty"` + // (Required when providing ACH agreement params) The first name of the person authorizing the ACH agreement. + AuthorizerFirstName *string `json:"authorizer_first_name,omitempty"` + // (Required when providing ACH agreement params) The last name of the person authorizing the ACH agreement. + AuthorizerLastName *string `json:"authorizer_last_name,omitempty"` + // (Required when providing ACH agreement params) The IP address of the person authorizing the ACH agreement. + IpAddress *string `json:"ip_address,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ACHAgreement. +// MarshalJSON implements the json.Marshaler interface for ACHAgreement. // It customizes the JSON marshaling process for ACHAgreement objects. func (a *ACHAgreement) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the ACHAgreement object to a map representation for JSON marshaling. func (a *ACHAgreement) toMap() map[string]any { - structMap := make(map[string]any) - if a.AgreementTerms != nil { - structMap["agreement_terms"] = a.AgreementTerms - } - if a.AuthorizerFirstName != nil { - structMap["authorizer_first_name"] = a.AuthorizerFirstName - } - if a.AuthorizerLastName != nil { - structMap["authorizer_last_name"] = a.AuthorizerLastName - } - if a.IpAddress != nil { - structMap["ip_address"] = a.IpAddress - } - return structMap + structMap := make(map[string]any) + if a.AgreementTerms != nil { + structMap["agreement_terms"] = a.AgreementTerms + } + if a.AuthorizerFirstName != nil { + structMap["authorizer_first_name"] = a.AuthorizerFirstName + } + if a.AuthorizerLastName != nil { + structMap["authorizer_last_name"] = a.AuthorizerLastName + } + if a.IpAddress != nil { + structMap["ip_address"] = a.IpAddress + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ACHAgreement. +// UnmarshalJSON implements the json.Unmarshaler interface for ACHAgreement. // It customizes the JSON unmarshaling process for ACHAgreement objects. func (a *ACHAgreement) UnmarshalJSON(input []byte) error { - temp := &struct { - AgreementTerms *string `json:"agreement_terms,omitempty"` - AuthorizerFirstName *string `json:"authorizer_first_name,omitempty"` - AuthorizerLastName *string `json:"authorizer_last_name,omitempty"` - IpAddress *string `json:"ip_address,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.AgreementTerms = temp.AgreementTerms - a.AuthorizerFirstName = temp.AuthorizerFirstName - a.AuthorizerLastName = temp.AuthorizerLastName - a.IpAddress = temp.IpAddress - return nil + var temp achAgreement + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.AgreementTerms = temp.AgreementTerms + a.AuthorizerFirstName = temp.AuthorizerFirstName + a.AuthorizerLastName = temp.AuthorizerLastName + a.IpAddress = temp.IpAddress + return nil +} + +// TODO +type achAgreement struct { + AgreementTerms *string `json:"agreement_terms,omitempty"` + AuthorizerFirstName *string `json:"authorizer_first_name,omitempty"` + AuthorizerLastName *string `json:"authorizer_last_name,omitempty"` + IpAddress *string `json:"ip_address,omitempty"` } diff --git a/models/activate_subscription_request.go b/models/activate_subscription_request.go index 5f037d57..3c7da158 100644 --- a/models/activate_subscription_request.go +++ b/models/activate_subscription_request.go @@ -1,43 +1,49 @@ package models import ( - "encoding/json" + "encoding/json" ) // ActivateSubscriptionRequest represents a ActivateSubscriptionRequest struct. type ActivateSubscriptionRequest struct { - // You may choose how to handle the activation failure. `true` means do not change the subscription’s state and billing period. `false` means to continue through with the activation and enter an end of life state. If this parameter is omitted or `null` is passed it will default to value set in the site settings (default: `true`) - RevertOnFailure Optional[bool] `json:"revert_on_failure"` + // You may choose how to handle the activation failure. `true` means do not change the subscription’s state and billing period. `false` means to continue through with the activation and enter an end of life state. If this parameter is omitted or `null` is passed it will default to value set in the site settings (default: `true`) + RevertOnFailure Optional[bool] `json:"revert_on_failure"` } -// MarshalJSON implements the json.Marshaler interface for ActivateSubscriptionRequest. +// MarshalJSON implements the json.Marshaler interface for ActivateSubscriptionRequest. // It customizes the JSON marshaling process for ActivateSubscriptionRequest objects. func (a *ActivateSubscriptionRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the ActivateSubscriptionRequest object to a map representation for JSON marshaling. func (a *ActivateSubscriptionRequest) toMap() map[string]any { - structMap := make(map[string]any) - if a.RevertOnFailure.IsValueSet() { - structMap["revert_on_failure"] = a.RevertOnFailure.Value() - } - return structMap + structMap := make(map[string]any) + if a.RevertOnFailure.IsValueSet() { + if a.RevertOnFailure.Value() != nil { + structMap["revert_on_failure"] = a.RevertOnFailure.Value() + } else { + structMap["revert_on_failure"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ActivateSubscriptionRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for ActivateSubscriptionRequest. // It customizes the JSON unmarshaling process for ActivateSubscriptionRequest objects. func (a *ActivateSubscriptionRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - RevertOnFailure Optional[bool] `json:"revert_on_failure"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.RevertOnFailure = temp.RevertOnFailure - return nil + var temp activateSubscriptionRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.RevertOnFailure = temp.RevertOnFailure + return nil +} + +// TODO +type activateSubscriptionRequest struct { + RevertOnFailure Optional[bool] `json:"revert_on_failure"` } diff --git a/models/add_coupons_request.go b/models/add_coupons_request.go index 2db65b3e..d8a3388d 100644 --- a/models/add_coupons_request.go +++ b/models/add_coupons_request.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // AddCouponsRequest represents a AddCouponsRequest struct. type AddCouponsRequest struct { - Codes []string `json:"codes,omitempty"` + Codes []string `json:"codes,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for AddCouponsRequest. +// MarshalJSON implements the json.Marshaler interface for AddCouponsRequest. // It customizes the JSON marshaling process for AddCouponsRequest objects. func (a *AddCouponsRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AddCouponsRequest object to a map representation for JSON marshaling. func (a *AddCouponsRequest) toMap() map[string]any { - structMap := make(map[string]any) - if a.Codes != nil { - structMap["codes"] = a.Codes - } - return structMap + structMap := make(map[string]any) + if a.Codes != nil { + structMap["codes"] = a.Codes + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AddCouponsRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for AddCouponsRequest. // It customizes the JSON unmarshaling process for AddCouponsRequest objects. func (a *AddCouponsRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Codes []string `json:"codes,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.Codes = temp.Codes - return nil + var temp addCouponsRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.Codes = temp.Codes + return nil +} + +// TODO +type addCouponsRequest struct { + Codes []string `json:"codes,omitempty"` } diff --git a/models/add_subscription_to_a_group.go b/models/add_subscription_to_a_group.go index f4cd38fd..08ea72eb 100644 --- a/models/add_subscription_to_a_group.go +++ b/models/add_subscription_to_a_group.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // AddSubscriptionToAGroup represents a AddSubscriptionToAGroup struct. type AddSubscriptionToAGroup struct { - Group *interface{} `json:"group,omitempty"` + Group *AddSubscriptionToAGroupGroup `json:"group,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for AddSubscriptionToAGroup. +// MarshalJSON implements the json.Marshaler interface for AddSubscriptionToAGroup. // It customizes the JSON marshaling process for AddSubscriptionToAGroup objects. func (a *AddSubscriptionToAGroup) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AddSubscriptionToAGroup object to a map representation for JSON marshaling. func (a *AddSubscriptionToAGroup) toMap() map[string]any { - structMap := make(map[string]any) - if a.Group != nil { - structMap["group"] = a.Group - } - return structMap + structMap := make(map[string]any) + if a.Group != nil { + structMap["group"] = a.Group.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AddSubscriptionToAGroup. +// UnmarshalJSON implements the json.Unmarshaler interface for AddSubscriptionToAGroup. // It customizes the JSON unmarshaling process for AddSubscriptionToAGroup objects. func (a *AddSubscriptionToAGroup) UnmarshalJSON(input []byte) error { - temp := &struct { - Group *interface{} `json:"group,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.Group = temp.Group - return nil + var temp addSubscriptionToAGroup + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.Group = temp.Group + return nil +} + +// TODO +type addSubscriptionToAGroup struct { + Group *AddSubscriptionToAGroupGroup `json:"group,omitempty"` } diff --git a/models/add_subscription_to_a_group_group.go b/models/add_subscription_to_a_group_group.go new file mode 100644 index 00000000..2e799cd7 --- /dev/null +++ b/models/add_subscription_to_a_group_group.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// AddSubscriptionToAGroupGroup represents a AddSubscriptionToAGroupGroup struct. +// This is a container for one-of cases. +type AddSubscriptionToAGroupGroup struct { + value any + isGroupSettings bool + isBoolean bool +} + +// String converts the AddSubscriptionToAGroupGroup object to a string representation. +func (a AddSubscriptionToAGroupGroup) String() string { + if bytes, err := json.Marshal(a.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for AddSubscriptionToAGroupGroup. +// It customizes the JSON marshaling process for AddSubscriptionToAGroupGroup objects. +func (a *AddSubscriptionToAGroupGroup) MarshalJSON() ( + []byte, + error) { + if a.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.AddSubscriptionToAGroupGroupContainer.From*` functions to initialize the AddSubscriptionToAGroupGroup object.") + } + return json.Marshal(a.toMap()) +} + +// toMap converts the AddSubscriptionToAGroupGroup object to a map representation for JSON marshaling. +func (a *AddSubscriptionToAGroupGroup) toMap() any { + switch obj := a.value.(type) { + case *GroupSettings: + return obj.toMap() + case *bool: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for AddSubscriptionToAGroupGroup. +// It customizes the JSON unmarshaling process for AddSubscriptionToAGroupGroup objects. +func (a *AddSubscriptionToAGroupGroup) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&GroupSettings{}, false, &a.isGroupSettings), + NewTypeHolder(new(bool), false, &a.isBoolean), + ) + + a.value = result + return err +} + +func (a *AddSubscriptionToAGroupGroup) AsGroupSettings() ( + *GroupSettings, + bool) { + if !a.isGroupSettings { + return nil, false + } + return a.value.(*GroupSettings), true +} + +func (a *AddSubscriptionToAGroupGroup) AsBoolean() ( + *bool, + bool) { + if !a.isBoolean { + return nil, false + } + return a.value.(*bool), true +} + +// internalAddSubscriptionToAGroupGroup represents a addSubscriptionToAGroupGroup struct. +// This is a container for one-of cases. +type internalAddSubscriptionToAGroupGroup struct{} + +var AddSubscriptionToAGroupGroupContainer internalAddSubscriptionToAGroupGroup + +func (a *internalAddSubscriptionToAGroupGroup) FromGroupSettings(val GroupSettings) AddSubscriptionToAGroupGroup { + return AddSubscriptionToAGroupGroup{value: &val} +} + +func (a *internalAddSubscriptionToAGroupGroup) FromBoolean(val bool) AddSubscriptionToAGroupGroup { + return AddSubscriptionToAGroupGroup{value: &val} +} diff --git a/models/address_change.go b/models/address_change.go index fb42b377..b9c6eb74 100644 --- a/models/address_change.go +++ b/models/address_change.go @@ -1,44 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // AddressChange represents a AddressChange struct. type AddressChange struct { - Before InvoiceAddress `json:"before"` - After InvoiceAddress `json:"after"` + Before InvoiceAddress `json:"before"` + After InvoiceAddress `json:"after"` } -// MarshalJSON implements the json.Marshaler interface for AddressChange. +// MarshalJSON implements the json.Marshaler interface for AddressChange. // It customizes the JSON marshaling process for AddressChange objects. func (a *AddressChange) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AddressChange object to a map representation for JSON marshaling. func (a *AddressChange) toMap() map[string]any { - structMap := make(map[string]any) - structMap["before"] = a.Before.toMap() - structMap["after"] = a.After.toMap() - return structMap + structMap := make(map[string]any) + structMap["before"] = a.Before.toMap() + structMap["after"] = a.After.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AddressChange. +// UnmarshalJSON implements the json.Unmarshaler interface for AddressChange. // It customizes the JSON unmarshaling process for AddressChange objects. func (a *AddressChange) UnmarshalJSON(input []byte) error { - temp := &struct { - Before InvoiceAddress `json:"before"` - After InvoiceAddress `json:"after"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.Before = temp.Before - a.After = temp.After - return nil + var temp addressChange + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + a.Before = *temp.Before + a.After = *temp.After + return nil +} + +// TODO +type addressChange struct { + Before *InvoiceAddress `json:"before"` + After *InvoiceAddress `json:"after"` +} + +func (a *addressChange) validate() error { + var errs []string + if a.Before == nil { + errs = append(errs, "required field `before` is missing for type `Address Change`") + } + if a.After == nil { + errs = append(errs, "required field `after` is missing for type `Address Change`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/agreement_acceptance.go b/models/agreement_acceptance.go index d7879357..74c6d624 100644 --- a/models/agreement_acceptance.go +++ b/models/agreement_acceptance.go @@ -1,75 +1,77 @@ package models import ( - "encoding/json" + "encoding/json" ) -// AgreementAcceptance represents a AgreementAcceptance struct. +// AgreementAcceptance represents a AgreementAcceptance struct. // Required when creating a subscription with Maxio Payments. type AgreementAcceptance struct { - // Required when providing agreement acceptance params. - IpAddress *string `json:"ip_address,omitempty"` - // Required when creating a subscription with Maxio Payments. Either terms_url or provacy_policy_url required when providing agreement_acceptance params. - TermsUrl *string `json:"terms_url,omitempty"` - PrivacyPolicyUrl *string `json:"privacy_policy_url,omitempty"` - ReturnRefundPolicyUrl *string `json:"return_refund_policy_url,omitempty"` - DeliveryPolicyUrl *string `json:"delivery_policy_url,omitempty"` - SecureCheckoutPolicyUrl *string `json:"secure_checkout_policy_url,omitempty"` + // Required when providing agreement acceptance params. + IpAddress *string `json:"ip_address,omitempty"` + // Required when creating a subscription with Maxio Payments. Either terms_url or provacy_policy_url required when providing agreement_acceptance params. + TermsUrl *string `json:"terms_url,omitempty"` + PrivacyPolicyUrl *string `json:"privacy_policy_url,omitempty"` + ReturnRefundPolicyUrl *string `json:"return_refund_policy_url,omitempty"` + DeliveryPolicyUrl *string `json:"delivery_policy_url,omitempty"` + SecureCheckoutPolicyUrl *string `json:"secure_checkout_policy_url,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for AgreementAcceptance. +// MarshalJSON implements the json.Marshaler interface for AgreementAcceptance. // It customizes the JSON marshaling process for AgreementAcceptance objects. func (a *AgreementAcceptance) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AgreementAcceptance object to a map representation for JSON marshaling. func (a *AgreementAcceptance) toMap() map[string]any { - structMap := make(map[string]any) - if a.IpAddress != nil { - structMap["ip_address"] = a.IpAddress - } - if a.TermsUrl != nil { - structMap["terms_url"] = a.TermsUrl - } - if a.PrivacyPolicyUrl != nil { - structMap["privacy_policy_url"] = a.PrivacyPolicyUrl - } - if a.ReturnRefundPolicyUrl != nil { - structMap["return_refund_policy_url"] = a.ReturnRefundPolicyUrl - } - if a.DeliveryPolicyUrl != nil { - structMap["delivery_policy_url"] = a.DeliveryPolicyUrl - } - if a.SecureCheckoutPolicyUrl != nil { - structMap["secure_checkout_policy_url"] = a.SecureCheckoutPolicyUrl - } - return structMap + structMap := make(map[string]any) + if a.IpAddress != nil { + structMap["ip_address"] = a.IpAddress + } + if a.TermsUrl != nil { + structMap["terms_url"] = a.TermsUrl + } + if a.PrivacyPolicyUrl != nil { + structMap["privacy_policy_url"] = a.PrivacyPolicyUrl + } + if a.ReturnRefundPolicyUrl != nil { + structMap["return_refund_policy_url"] = a.ReturnRefundPolicyUrl + } + if a.DeliveryPolicyUrl != nil { + structMap["delivery_policy_url"] = a.DeliveryPolicyUrl + } + if a.SecureCheckoutPolicyUrl != nil { + structMap["secure_checkout_policy_url"] = a.SecureCheckoutPolicyUrl + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AgreementAcceptance. +// UnmarshalJSON implements the json.Unmarshaler interface for AgreementAcceptance. // It customizes the JSON unmarshaling process for AgreementAcceptance objects. func (a *AgreementAcceptance) UnmarshalJSON(input []byte) error { - temp := &struct { - IpAddress *string `json:"ip_address,omitempty"` - TermsUrl *string `json:"terms_url,omitempty"` - PrivacyPolicyUrl *string `json:"privacy_policy_url,omitempty"` - ReturnRefundPolicyUrl *string `json:"return_refund_policy_url,omitempty"` - DeliveryPolicyUrl *string `json:"delivery_policy_url,omitempty"` - SecureCheckoutPolicyUrl *string `json:"secure_checkout_policy_url,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.IpAddress = temp.IpAddress - a.TermsUrl = temp.TermsUrl - a.PrivacyPolicyUrl = temp.PrivacyPolicyUrl - a.ReturnRefundPolicyUrl = temp.ReturnRefundPolicyUrl - a.DeliveryPolicyUrl = temp.DeliveryPolicyUrl - a.SecureCheckoutPolicyUrl = temp.SecureCheckoutPolicyUrl - return nil + var temp agreementAcceptance + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.IpAddress = temp.IpAddress + a.TermsUrl = temp.TermsUrl + a.PrivacyPolicyUrl = temp.PrivacyPolicyUrl + a.ReturnRefundPolicyUrl = temp.ReturnRefundPolicyUrl + a.DeliveryPolicyUrl = temp.DeliveryPolicyUrl + a.SecureCheckoutPolicyUrl = temp.SecureCheckoutPolicyUrl + return nil +} + +// TODO +type agreementAcceptance struct { + IpAddress *string `json:"ip_address,omitempty"` + TermsUrl *string `json:"terms_url,omitempty"` + PrivacyPolicyUrl *string `json:"privacy_policy_url,omitempty"` + ReturnRefundPolicyUrl *string `json:"return_refund_policy_url,omitempty"` + DeliveryPolicyUrl *string `json:"delivery_policy_url,omitempty"` + SecureCheckoutPolicyUrl *string `json:"secure_checkout_policy_url,omitempty"` } diff --git a/models/allocate_components.go b/models/allocate_components.go index ad1f2730..fa236b14 100644 --- a/models/allocate_components.go +++ b/models/allocate_components.go @@ -1,91 +1,101 @@ package models import ( - "encoding/json" + "encoding/json" ) // AllocateComponents represents a AllocateComponents struct. type AllocateComponents struct { - ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` // Deprecated - ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` // Deprecated - Allocations []CreateAllocation `json:"allocations,omitempty"` - AccrueCharge *bool `json:"accrue_charge,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - // (Optional) If not passed, the allocation(s) will use the payment collection method on the subscription - PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` - // If true, if the immediate component payment fails, initiate dunning for the subscription. - // Otherwise, leave the charges on the subscription to pay for at renewal. - InitiateDunning *bool `json:"initiate_dunning,omitempty"` + ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` // Deprecated + ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` // Deprecated + Allocations []CreateAllocation `json:"allocations,omitempty"` + AccrueCharge *bool `json:"accrue_charge,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + // (Optional) If not passed, the allocation(s) will use the payment collection method on the subscription + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` + // If true, if the immediate component payment fails, initiate dunning for the subscription. + // Otherwise, leave the charges on the subscription to pay for at renewal. + InitiateDunning *bool `json:"initiate_dunning,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for AllocateComponents. +// MarshalJSON implements the json.Marshaler interface for AllocateComponents. // It customizes the JSON marshaling process for AllocateComponents objects. func (a *AllocateComponents) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AllocateComponents object to a map representation for JSON marshaling. func (a *AllocateComponents) toMap() map[string]any { - structMap := make(map[string]any) - if a.ProrationUpgradeScheme != nil { - structMap["proration_upgrade_scheme"] = a.ProrationUpgradeScheme - } - if a.ProrationDowngradeScheme != nil { - structMap["proration_downgrade_scheme"] = a.ProrationDowngradeScheme - } - if a.Allocations != nil { - structMap["allocations"] = a.Allocations - } - if a.AccrueCharge != nil { - structMap["accrue_charge"] = a.AccrueCharge - } - if a.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = a.UpgradeCharge.Value() - } - if a.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = a.DowngradeCredit.Value() - } - if a.PaymentCollectionMethod != nil { - structMap["payment_collection_method"] = a.PaymentCollectionMethod - } - if a.InitiateDunning != nil { - structMap["initiate_dunning"] = a.InitiateDunning - } - return structMap + structMap := make(map[string]any) + if a.ProrationUpgradeScheme != nil { + structMap["proration_upgrade_scheme"] = a.ProrationUpgradeScheme + } + if a.ProrationDowngradeScheme != nil { + structMap["proration_downgrade_scheme"] = a.ProrationDowngradeScheme + } + if a.Allocations != nil { + structMap["allocations"] = a.Allocations + } + if a.AccrueCharge != nil { + structMap["accrue_charge"] = a.AccrueCharge + } + if a.UpgradeCharge.IsValueSet() { + if a.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = a.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if a.DowngradeCredit.IsValueSet() { + if a.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = a.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if a.PaymentCollectionMethod != nil { + structMap["payment_collection_method"] = a.PaymentCollectionMethod + } + if a.InitiateDunning != nil { + structMap["initiate_dunning"] = a.InitiateDunning + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AllocateComponents. +// UnmarshalJSON implements the json.Unmarshaler interface for AllocateComponents. // It customizes the JSON unmarshaling process for AllocateComponents objects. func (a *AllocateComponents) UnmarshalJSON(input []byte) error { - temp := &struct { - ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` - ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` - Allocations []CreateAllocation `json:"allocations,omitempty"` - AccrueCharge *bool `json:"accrue_charge,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` - InitiateDunning *bool `json:"initiate_dunning,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.ProrationUpgradeScheme = temp.ProrationUpgradeScheme - a.ProrationDowngradeScheme = temp.ProrationDowngradeScheme - a.Allocations = temp.Allocations - a.AccrueCharge = temp.AccrueCharge - a.UpgradeCharge = temp.UpgradeCharge - a.DowngradeCredit = temp.DowngradeCredit - a.PaymentCollectionMethod = temp.PaymentCollectionMethod - a.InitiateDunning = temp.InitiateDunning - return nil + var temp allocateComponents + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.ProrationUpgradeScheme = temp.ProrationUpgradeScheme + a.ProrationDowngradeScheme = temp.ProrationDowngradeScheme + a.Allocations = temp.Allocations + a.AccrueCharge = temp.AccrueCharge + a.UpgradeCharge = temp.UpgradeCharge + a.DowngradeCredit = temp.DowngradeCredit + a.PaymentCollectionMethod = temp.PaymentCollectionMethod + a.InitiateDunning = temp.InitiateDunning + return nil +} + +// TODO +type allocateComponents struct { + ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` + ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` + Allocations []CreateAllocation `json:"allocations,omitempty"` + AccrueCharge *bool `json:"accrue_charge,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` + InitiateDunning *bool `json:"initiate_dunning,omitempty"` } diff --git a/models/allocation.go b/models/allocation.go index f969bdb7..9bdafaea 100644 --- a/models/allocation.go +++ b/models/allocation.go @@ -1,226 +1,248 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Allocation represents a Allocation struct. type Allocation struct { - // The allocation unique id - AllocationId *int `json:"allocation_id,omitempty"` - // The integer component ID for the allocation. This references a component that you have created in your Product setup - ComponentId *int `json:"component_id,omitempty"` - // The handle of the component. This references a component that you have created in your Product setup - ComponentHandle Optional[string] `json:"component_handle"` - // The integer subscription ID for the allocation. This references a unique subscription in your Site - SubscriptionId *int `json:"subscription_id,omitempty"` - // The allocated quantity set in to effect by the allocation. String for components supporting fractional quantities - Quantity *interface{} `json:"quantity,omitempty"` - // The allocated quantity that was in effect before this allocation was created. String for components supporting fractional quantities - PreviousQuantity *interface{} `json:"previous_quantity,omitempty"` - // The memo passed when the allocation was created - Memo Optional[string] `json:"memo"` - // The time that the allocation was recorded, in format and UTC timezone, i.e. 2012-11-20T22:00:37Z - Timestamp *time.Time `json:"timestamp,omitempty"` - // Timestamp indicating when this allocation was created - CreatedAt *time.Time `json:"created_at,omitempty"` - // The scheme used if the proration was an upgrade. This is only present when the allocation was created mid-period. - ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` // Deprecated - // The scheme used if the proration was a downgrade. This is only present when the allocation was created mid-period. - ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` // Deprecated - PricePointId *int `json:"price_point_id,omitempty"` - PricePointName *string `json:"price_point_name,omitempty"` - PricePointHandle *string `json:"price_point_handle,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - PreviousPricePointId *int `json:"previous_price_point_id,omitempty"` - // If the change in cost is an upgrade, this determines if the charge should accrue to the next renewal or if capture should be attempted immediately. - AccrueCharge *bool `json:"accrue_charge,omitempty"` - // If true, if the immediate component payment fails, initiate dunning for the subscription. - // Otherwise, leave the charges on the subscription to pay for at renewal. - InitiateDunning *bool `json:"initiate_dunning,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - Payment Optional[PaymentForAllocation] `json:"payment"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` - UsedQuantity *int64 `json:"used_quantity,omitempty"` - ChargeId *int64 `json:"charge_id,omitempty"` + // The allocation unique id + AllocationId *int `json:"allocation_id,omitempty"` + // The integer component ID for the allocation. This references a component that you have created in your Product setup + ComponentId *int `json:"component_id,omitempty"` + // The handle of the component. This references a component that you have created in your Product setup + ComponentHandle Optional[string] `json:"component_handle"` + // The integer subscription ID for the allocation. This references a unique subscription in your Site + SubscriptionId *int `json:"subscription_id,omitempty"` + // The allocated quantity set in to effect by the allocation. String for components supporting fractional quantities + Quantity *AllocationQuantity `json:"quantity,omitempty"` + // The allocated quantity that was in effect before this allocation was created. String for components supporting fractional quantities + PreviousQuantity *AllocationPreviousQuantity `json:"previous_quantity,omitempty"` + // The memo passed when the allocation was created + Memo Optional[string] `json:"memo"` + // The time that the allocation was recorded, in format and UTC timezone, i.e. 2012-11-20T22:00:37Z + Timestamp *time.Time `json:"timestamp,omitempty"` + // Timestamp indicating when this allocation was created + CreatedAt *time.Time `json:"created_at,omitempty"` + // The scheme used if the proration was an upgrade. This is only present when the allocation was created mid-period. + ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` // Deprecated + // The scheme used if the proration was a downgrade. This is only present when the allocation was created mid-period. + ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` // Deprecated + PricePointId *int `json:"price_point_id,omitempty"` + PricePointName *string `json:"price_point_name,omitempty"` + PricePointHandle *string `json:"price_point_handle,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + PreviousPricePointId *int `json:"previous_price_point_id,omitempty"` + // If the change in cost is an upgrade, this determines if the charge should accrue to the next renewal or if capture should be attempted immediately. + AccrueCharge *bool `json:"accrue_charge,omitempty"` + // If true, if the immediate component payment fails, initiate dunning for the subscription. + // Otherwise, leave the charges on the subscription to pay for at renewal. + InitiateDunning *bool `json:"initiate_dunning,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + Payment Optional[AllocationPayment] `json:"payment"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + UsedQuantity *int64 `json:"used_quantity,omitempty"` + ChargeId *int64 `json:"charge_id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Allocation. +// MarshalJSON implements the json.Marshaler interface for Allocation. // It customizes the JSON marshaling process for Allocation objects. func (a *Allocation) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the Allocation object to a map representation for JSON marshaling. func (a *Allocation) toMap() map[string]any { - structMap := make(map[string]any) - if a.AllocationId != nil { - structMap["allocation_id"] = a.AllocationId - } - if a.ComponentId != nil { - structMap["component_id"] = a.ComponentId - } - if a.ComponentHandle.IsValueSet() { - structMap["component_handle"] = a.ComponentHandle.Value() - } - if a.SubscriptionId != nil { - structMap["subscription_id"] = a.SubscriptionId - } - if a.Quantity != nil { - structMap["quantity"] = a.Quantity - } - if a.PreviousQuantity != nil { - structMap["previous_quantity"] = a.PreviousQuantity - } - if a.Memo.IsValueSet() { - structMap["memo"] = a.Memo.Value() - } - if a.Timestamp != nil { - structMap["timestamp"] = a.Timestamp.Format(time.RFC3339) - } - if a.CreatedAt != nil { - structMap["created_at"] = a.CreatedAt.Format(time.RFC3339) - } - if a.ProrationUpgradeScheme != nil { - structMap["proration_upgrade_scheme"] = a.ProrationUpgradeScheme - } - if a.ProrationDowngradeScheme != nil { - structMap["proration_downgrade_scheme"] = a.ProrationDowngradeScheme - } - if a.PricePointId != nil { - structMap["price_point_id"] = a.PricePointId - } - if a.PricePointName != nil { - structMap["price_point_name"] = a.PricePointName - } - if a.PricePointHandle != nil { - structMap["price_point_handle"] = a.PricePointHandle - } - if a.Interval != nil { - structMap["interval"] = a.Interval - } - if a.IntervalUnit != nil { - structMap["interval_unit"] = a.IntervalUnit - } - if a.PreviousPricePointId != nil { - structMap["previous_price_point_id"] = a.PreviousPricePointId - } - if a.AccrueCharge != nil { - structMap["accrue_charge"] = a.AccrueCharge - } - if a.InitiateDunning != nil { - structMap["initiate_dunning"] = a.InitiateDunning - } - if a.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = a.UpgradeCharge.Value() - } - if a.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = a.DowngradeCredit.Value() - } - if a.Payment.IsValueSet() { - structMap["payment"] = a.Payment.Value() - } - if a.ExpiresAt != nil { - structMap["expires_at"] = a.ExpiresAt.Format(time.RFC3339) - } - if a.UsedQuantity != nil { - structMap["used_quantity"] = a.UsedQuantity - } - if a.ChargeId != nil { - structMap["charge_id"] = a.ChargeId - } - return structMap + structMap := make(map[string]any) + if a.AllocationId != nil { + structMap["allocation_id"] = a.AllocationId + } + if a.ComponentId != nil { + structMap["component_id"] = a.ComponentId + } + if a.ComponentHandle.IsValueSet() { + if a.ComponentHandle.Value() != nil { + structMap["component_handle"] = a.ComponentHandle.Value() + } else { + structMap["component_handle"] = nil + } + } + if a.SubscriptionId != nil { + structMap["subscription_id"] = a.SubscriptionId + } + if a.Quantity != nil { + structMap["quantity"] = a.Quantity.toMap() + } + if a.PreviousQuantity != nil { + structMap["previous_quantity"] = a.PreviousQuantity.toMap() + } + if a.Memo.IsValueSet() { + if a.Memo.Value() != nil { + structMap["memo"] = a.Memo.Value() + } else { + structMap["memo"] = nil + } + } + if a.Timestamp != nil { + structMap["timestamp"] = a.Timestamp.Format(time.RFC3339) + } + if a.CreatedAt != nil { + structMap["created_at"] = a.CreatedAt.Format(time.RFC3339) + } + if a.ProrationUpgradeScheme != nil { + structMap["proration_upgrade_scheme"] = a.ProrationUpgradeScheme + } + if a.ProrationDowngradeScheme != nil { + structMap["proration_downgrade_scheme"] = a.ProrationDowngradeScheme + } + if a.PricePointId != nil { + structMap["price_point_id"] = a.PricePointId + } + if a.PricePointName != nil { + structMap["price_point_name"] = a.PricePointName + } + if a.PricePointHandle != nil { + structMap["price_point_handle"] = a.PricePointHandle + } + if a.Interval != nil { + structMap["interval"] = a.Interval + } + if a.IntervalUnit != nil { + structMap["interval_unit"] = a.IntervalUnit + } + if a.PreviousPricePointId != nil { + structMap["previous_price_point_id"] = a.PreviousPricePointId + } + if a.AccrueCharge != nil { + structMap["accrue_charge"] = a.AccrueCharge + } + if a.InitiateDunning != nil { + structMap["initiate_dunning"] = a.InitiateDunning + } + if a.UpgradeCharge.IsValueSet() { + if a.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = a.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if a.DowngradeCredit.IsValueSet() { + if a.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = a.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if a.Payment.IsValueSet() { + if a.Payment.Value() != nil { + structMap["payment"] = a.Payment.Value().toMap() + } else { + structMap["payment"] = nil + } + } + if a.ExpiresAt != nil { + structMap["expires_at"] = a.ExpiresAt.Format(time.RFC3339) + } + if a.UsedQuantity != nil { + structMap["used_quantity"] = a.UsedQuantity + } + if a.ChargeId != nil { + structMap["charge_id"] = a.ChargeId + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Allocation. +// UnmarshalJSON implements the json.Unmarshaler interface for Allocation. // It customizes the JSON unmarshaling process for Allocation objects. func (a *Allocation) UnmarshalJSON(input []byte) error { - temp := &struct { - AllocationId *int `json:"allocation_id,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - ComponentHandle Optional[string] `json:"component_handle"` - SubscriptionId *int `json:"subscription_id,omitempty"` - Quantity *interface{} `json:"quantity,omitempty"` - PreviousQuantity *interface{} `json:"previous_quantity,omitempty"` - Memo Optional[string] `json:"memo"` - Timestamp *string `json:"timestamp,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` - ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - PricePointName *string `json:"price_point_name,omitempty"` - PricePointHandle *string `json:"price_point_handle,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - PreviousPricePointId *int `json:"previous_price_point_id,omitempty"` - AccrueCharge *bool `json:"accrue_charge,omitempty"` - InitiateDunning *bool `json:"initiate_dunning,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - Payment Optional[PaymentForAllocation] `json:"payment"` - ExpiresAt *string `json:"expires_at,omitempty"` - UsedQuantity *int64 `json:"used_quantity,omitempty"` - ChargeId *int64 `json:"charge_id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.AllocationId = temp.AllocationId - a.ComponentId = temp.ComponentId - a.ComponentHandle = temp.ComponentHandle - a.SubscriptionId = temp.SubscriptionId - a.Quantity = temp.Quantity - a.PreviousQuantity = temp.PreviousQuantity - a.Memo = temp.Memo - if temp.Timestamp != nil { - TimestampVal, err := time.Parse(time.RFC3339, *temp.Timestamp) - if err != nil { - log.Fatalf("Cannot Parse timestamp as % s format.", time.RFC3339) - } - a.Timestamp = &TimestampVal - } - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - a.CreatedAt = &CreatedAtVal - } - a.ProrationUpgradeScheme = temp.ProrationUpgradeScheme - a.ProrationDowngradeScheme = temp.ProrationDowngradeScheme - a.PricePointId = temp.PricePointId - a.PricePointName = temp.PricePointName - a.PricePointHandle = temp.PricePointHandle - a.Interval = temp.Interval - a.IntervalUnit = temp.IntervalUnit - a.PreviousPricePointId = temp.PreviousPricePointId - a.AccrueCharge = temp.AccrueCharge - a.InitiateDunning = temp.InitiateDunning - a.UpgradeCharge = temp.UpgradeCharge - a.DowngradeCredit = temp.DowngradeCredit - a.Payment = temp.Payment - if temp.ExpiresAt != nil { - ExpiresAtVal, err := time.Parse(time.RFC3339, *temp.ExpiresAt) - if err != nil { - log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) - } - a.ExpiresAt = &ExpiresAtVal - } - a.UsedQuantity = temp.UsedQuantity - a.ChargeId = temp.ChargeId - return nil + var temp allocation + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.AllocationId = temp.AllocationId + a.ComponentId = temp.ComponentId + a.ComponentHandle = temp.ComponentHandle + a.SubscriptionId = temp.SubscriptionId + a.Quantity = temp.Quantity + a.PreviousQuantity = temp.PreviousQuantity + a.Memo = temp.Memo + if temp.Timestamp != nil { + TimestampVal, err := time.Parse(time.RFC3339, *temp.Timestamp) + if err != nil { + log.Fatalf("Cannot Parse timestamp as % s format.", time.RFC3339) + } + a.Timestamp = &TimestampVal + } + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + a.CreatedAt = &CreatedAtVal + } + a.ProrationUpgradeScheme = temp.ProrationUpgradeScheme + a.ProrationDowngradeScheme = temp.ProrationDowngradeScheme + a.PricePointId = temp.PricePointId + a.PricePointName = temp.PricePointName + a.PricePointHandle = temp.PricePointHandle + a.Interval = temp.Interval + a.IntervalUnit = temp.IntervalUnit + a.PreviousPricePointId = temp.PreviousPricePointId + a.AccrueCharge = temp.AccrueCharge + a.InitiateDunning = temp.InitiateDunning + a.UpgradeCharge = temp.UpgradeCharge + a.DowngradeCredit = temp.DowngradeCredit + a.Payment = temp.Payment + if temp.ExpiresAt != nil { + ExpiresAtVal, err := time.Parse(time.RFC3339, *temp.ExpiresAt) + if err != nil { + log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) + } + a.ExpiresAt = &ExpiresAtVal + } + a.UsedQuantity = temp.UsedQuantity + a.ChargeId = temp.ChargeId + return nil +} + +// TODO +type allocation struct { + AllocationId *int `json:"allocation_id,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + ComponentHandle Optional[string] `json:"component_handle"` + SubscriptionId *int `json:"subscription_id,omitempty"` + Quantity *AllocationQuantity `json:"quantity,omitempty"` + PreviousQuantity *AllocationPreviousQuantity `json:"previous_quantity,omitempty"` + Memo Optional[string] `json:"memo"` + Timestamp *string `json:"timestamp,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` + ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + PricePointName *string `json:"price_point_name,omitempty"` + PricePointHandle *string `json:"price_point_handle,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + PreviousPricePointId *int `json:"previous_price_point_id,omitempty"` + AccrueCharge *bool `json:"accrue_charge,omitempty"` + InitiateDunning *bool `json:"initiate_dunning,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + Payment Optional[AllocationPayment] `json:"payment"` + ExpiresAt *string `json:"expires_at,omitempty"` + UsedQuantity *int64 `json:"used_quantity,omitempty"` + ChargeId *int64 `json:"charge_id,omitempty"` } diff --git a/models/allocation_expiration_date.go b/models/allocation_expiration_date.go index f1ec3cec..b6e3b173 100644 --- a/models/allocation_expiration_date.go +++ b/models/allocation_expiration_date.go @@ -1,50 +1,52 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // AllocationExpirationDate represents a AllocationExpirationDate struct. type AllocationExpirationDate struct { - ExpiresAt *time.Time `json:"expires_at,omitempty"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for AllocationExpirationDate. +// MarshalJSON implements the json.Marshaler interface for AllocationExpirationDate. // It customizes the JSON marshaling process for AllocationExpirationDate objects. func (a *AllocationExpirationDate) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AllocationExpirationDate object to a map representation for JSON marshaling. func (a *AllocationExpirationDate) toMap() map[string]any { - structMap := make(map[string]any) - if a.ExpiresAt != nil { - structMap["expires_at"] = a.ExpiresAt.Format(time.RFC3339) - } - return structMap + structMap := make(map[string]any) + if a.ExpiresAt != nil { + structMap["expires_at"] = a.ExpiresAt.Format(time.RFC3339) + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AllocationExpirationDate. +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationExpirationDate. // It customizes the JSON unmarshaling process for AllocationExpirationDate objects. func (a *AllocationExpirationDate) UnmarshalJSON(input []byte) error { - temp := &struct { - ExpiresAt *string `json:"expires_at,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - if temp.ExpiresAt != nil { - ExpiresAtVal, err := time.Parse(time.RFC3339, *temp.ExpiresAt) - if err != nil { - log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) - } - a.ExpiresAt = &ExpiresAtVal - } - return nil + var temp allocationExpirationDate + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + if temp.ExpiresAt != nil { + ExpiresAtVal, err := time.Parse(time.RFC3339, *temp.ExpiresAt) + if err != nil { + log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) + } + a.ExpiresAt = &ExpiresAtVal + } + return nil +} + +// TODO +type allocationExpirationDate struct { + ExpiresAt *string `json:"expires_at,omitempty"` } diff --git a/models/allocation_payment.go b/models/allocation_payment.go new file mode 100644 index 00000000..05f504c8 --- /dev/null +++ b/models/allocation_payment.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// AllocationPayment represents a AllocationPayment struct. +// This is a container for one-of cases. +type AllocationPayment struct { + value any + isPaymentForAllocation bool +} + +// String converts the AllocationPayment object to a string representation. +func (a AllocationPayment) String() string { + if bytes, err := json.Marshal(a.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for AllocationPayment. +// It customizes the JSON marshaling process for AllocationPayment objects. +func (a *AllocationPayment) MarshalJSON() ( + []byte, + error) { + if a.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.AllocationPaymentContainer.From*` functions to initialize the AllocationPayment object.") + } + return json.Marshal(a.toMap()) +} + +// toMap converts the AllocationPayment object to a map representation for JSON marshaling. +func (a *AllocationPayment) toMap() any { + switch obj := a.value.(type) { + case *PaymentForAllocation: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPayment. +// It customizes the JSON unmarshaling process for AllocationPayment objects. +func (a *AllocationPayment) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&PaymentForAllocation{}, false, &a.isPaymentForAllocation), + ) + + a.value = result + return err +} + +func (a *AllocationPayment) AsPaymentForAllocation() ( + *PaymentForAllocation, + bool) { + if !a.isPaymentForAllocation { + return nil, false + } + return a.value.(*PaymentForAllocation), true +} + +// internalAllocationPayment represents a allocationPayment struct. +// This is a container for one-of cases. +type internalAllocationPayment struct{} + +var AllocationPaymentContainer internalAllocationPayment + +func (a *internalAllocationPayment) FromPaymentForAllocation(val PaymentForAllocation) AllocationPayment { + return AllocationPayment{value: &val} +} diff --git a/models/allocation_preview.go b/models/allocation_preview.go index 112d936e..583855cf 100644 --- a/models/allocation_preview.go +++ b/models/allocation_preview.go @@ -1,129 +1,131 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // AllocationPreview represents a AllocationPreview struct. type AllocationPreview struct { - StartDate *time.Time `json:"start_date,omitempty"` - EndDate *time.Time `json:"end_date,omitempty"` - SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` - TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` - TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` - TotalInCents *int64 `json:"total_in_cents,omitempty"` - Direction *AllocationPreviewDirection `json:"direction,omitempty"` - ProrationScheme *string `json:"proration_scheme,omitempty"` - LineItems []AllocationPreviewLineItem `json:"line_items,omitempty"` - AccrueCharge *bool `json:"accrue_charge,omitempty"` - Allocations []AllocationPreviewItem `json:"allocations,omitempty"` - PeriodType *string `json:"period_type,omitempty"` - // An integer representing the amount of the subscription's current balance - ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` + StartDate *time.Time `json:"start_date,omitempty"` + EndDate *time.Time `json:"end_date,omitempty"` + SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` + TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` + TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` + TotalInCents *int64 `json:"total_in_cents,omitempty"` + Direction *AllocationPreviewDirection `json:"direction,omitempty"` + ProrationScheme *string `json:"proration_scheme,omitempty"` + LineItems []AllocationPreviewLineItem `json:"line_items,omitempty"` + AccrueCharge *bool `json:"accrue_charge,omitempty"` + Allocations []AllocationPreviewItem `json:"allocations,omitempty"` + PeriodType *string `json:"period_type,omitempty"` + // An integer representing the amount of the subscription's current balance + ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for AllocationPreview. +// MarshalJSON implements the json.Marshaler interface for AllocationPreview. // It customizes the JSON marshaling process for AllocationPreview objects. func (a *AllocationPreview) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AllocationPreview object to a map representation for JSON marshaling. func (a *AllocationPreview) toMap() map[string]any { - structMap := make(map[string]any) - if a.StartDate != nil { - structMap["start_date"] = a.StartDate.Format(time.RFC3339) - } - if a.EndDate != nil { - structMap["end_date"] = a.EndDate.Format(time.RFC3339) - } - if a.SubtotalInCents != nil { - structMap["subtotal_in_cents"] = a.SubtotalInCents - } - if a.TotalTaxInCents != nil { - structMap["total_tax_in_cents"] = a.TotalTaxInCents - } - if a.TotalDiscountInCents != nil { - structMap["total_discount_in_cents"] = a.TotalDiscountInCents - } - if a.TotalInCents != nil { - structMap["total_in_cents"] = a.TotalInCents - } - if a.Direction != nil { - structMap["direction"] = a.Direction - } - if a.ProrationScheme != nil { - structMap["proration_scheme"] = a.ProrationScheme - } - if a.LineItems != nil { - structMap["line_items"] = a.LineItems - } - if a.AccrueCharge != nil { - structMap["accrue_charge"] = a.AccrueCharge - } - if a.Allocations != nil { - structMap["allocations"] = a.Allocations - } - if a.PeriodType != nil { - structMap["period_type"] = a.PeriodType - } - if a.ExistingBalanceInCents != nil { - structMap["existing_balance_in_cents"] = a.ExistingBalanceInCents - } - return structMap + structMap := make(map[string]any) + if a.StartDate != nil { + structMap["start_date"] = a.StartDate.Format(time.RFC3339) + } + if a.EndDate != nil { + structMap["end_date"] = a.EndDate.Format(time.RFC3339) + } + if a.SubtotalInCents != nil { + structMap["subtotal_in_cents"] = a.SubtotalInCents + } + if a.TotalTaxInCents != nil { + structMap["total_tax_in_cents"] = a.TotalTaxInCents + } + if a.TotalDiscountInCents != nil { + structMap["total_discount_in_cents"] = a.TotalDiscountInCents + } + if a.TotalInCents != nil { + structMap["total_in_cents"] = a.TotalInCents + } + if a.Direction != nil { + structMap["direction"] = a.Direction + } + if a.ProrationScheme != nil { + structMap["proration_scheme"] = a.ProrationScheme + } + if a.LineItems != nil { + structMap["line_items"] = a.LineItems + } + if a.AccrueCharge != nil { + structMap["accrue_charge"] = a.AccrueCharge + } + if a.Allocations != nil { + structMap["allocations"] = a.Allocations + } + if a.PeriodType != nil { + structMap["period_type"] = a.PeriodType + } + if a.ExistingBalanceInCents != nil { + structMap["existing_balance_in_cents"] = a.ExistingBalanceInCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPreview. +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPreview. // It customizes the JSON unmarshaling process for AllocationPreview objects. func (a *AllocationPreview) UnmarshalJSON(input []byte) error { - temp := &struct { - StartDate *string `json:"start_date,omitempty"` - EndDate *string `json:"end_date,omitempty"` - SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` - TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` - TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` - TotalInCents *int64 `json:"total_in_cents,omitempty"` - Direction *AllocationPreviewDirection `json:"direction,omitempty"` - ProrationScheme *string `json:"proration_scheme,omitempty"` - LineItems []AllocationPreviewLineItem `json:"line_items,omitempty"` - AccrueCharge *bool `json:"accrue_charge,omitempty"` - Allocations []AllocationPreviewItem `json:"allocations,omitempty"` - PeriodType *string `json:"period_type,omitempty"` - ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - if temp.StartDate != nil { - StartDateVal, err := time.Parse(time.RFC3339, *temp.StartDate) - if err != nil { - log.Fatalf("Cannot Parse start_date as % s format.", time.RFC3339) - } - a.StartDate = &StartDateVal - } - if temp.EndDate != nil { - EndDateVal, err := time.Parse(time.RFC3339, *temp.EndDate) - if err != nil { - log.Fatalf("Cannot Parse end_date as % s format.", time.RFC3339) - } - a.EndDate = &EndDateVal - } - a.SubtotalInCents = temp.SubtotalInCents - a.TotalTaxInCents = temp.TotalTaxInCents - a.TotalDiscountInCents = temp.TotalDiscountInCents - a.TotalInCents = temp.TotalInCents - a.Direction = temp.Direction - a.ProrationScheme = temp.ProrationScheme - a.LineItems = temp.LineItems - a.AccrueCharge = temp.AccrueCharge - a.Allocations = temp.Allocations - a.PeriodType = temp.PeriodType - a.ExistingBalanceInCents = temp.ExistingBalanceInCents - return nil + var temp allocationPreview + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + if temp.StartDate != nil { + StartDateVal, err := time.Parse(time.RFC3339, *temp.StartDate) + if err != nil { + log.Fatalf("Cannot Parse start_date as % s format.", time.RFC3339) + } + a.StartDate = &StartDateVal + } + if temp.EndDate != nil { + EndDateVal, err := time.Parse(time.RFC3339, *temp.EndDate) + if err != nil { + log.Fatalf("Cannot Parse end_date as % s format.", time.RFC3339) + } + a.EndDate = &EndDateVal + } + a.SubtotalInCents = temp.SubtotalInCents + a.TotalTaxInCents = temp.TotalTaxInCents + a.TotalDiscountInCents = temp.TotalDiscountInCents + a.TotalInCents = temp.TotalInCents + a.Direction = temp.Direction + a.ProrationScheme = temp.ProrationScheme + a.LineItems = temp.LineItems + a.AccrueCharge = temp.AccrueCharge + a.Allocations = temp.Allocations + a.PeriodType = temp.PeriodType + a.ExistingBalanceInCents = temp.ExistingBalanceInCents + return nil +} + +// TODO +type allocationPreview struct { + StartDate *string `json:"start_date,omitempty"` + EndDate *string `json:"end_date,omitempty"` + SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` + TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` + TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` + TotalInCents *int64 `json:"total_in_cents,omitempty"` + Direction *AllocationPreviewDirection `json:"direction,omitempty"` + ProrationScheme *string `json:"proration_scheme,omitempty"` + LineItems []AllocationPreviewLineItem `json:"line_items,omitempty"` + AccrueCharge *bool `json:"accrue_charge,omitempty"` + Allocations []AllocationPreviewItem `json:"allocations,omitempty"` + PeriodType *string `json:"period_type,omitempty"` + ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` } diff --git a/models/allocation_preview_item.go b/models/allocation_preview_item.go index c1fd8e49..66c5db31 100644 --- a/models/allocation_preview_item.go +++ b/models/allocation_preview_item.go @@ -1,150 +1,172 @@ package models import ( - "encoding/json" + "encoding/json" ) // AllocationPreviewItem represents a AllocationPreviewItem struct. type AllocationPreviewItem struct { - ComponentId *int `json:"component_id,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - Quantity *interface{} `json:"quantity,omitempty"` - PreviousQuantity *interface{} `json:"previous_quantity,omitempty"` - Memo Optional[string] `json:"memo"` - Timestamp Optional[string] `json:"timestamp"` - ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` // Deprecated - ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` // Deprecated - AccrueCharge *bool `json:"accrue_charge,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePointId *int `json:"price_point_id,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - PreviousPricePointId *int `json:"previous_price_point_id,omitempty"` - PricePointHandle *string `json:"price_point_handle,omitempty"` - PricePointName *string `json:"price_point_name,omitempty"` - ComponentHandle Optional[string] `json:"component_handle"` + ComponentId *int `json:"component_id,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + Quantity *AllocationPreviewItemQuantity `json:"quantity,omitempty"` + PreviousQuantity *AllocationPreviewItemPreviousQuantity `json:"previous_quantity,omitempty"` + Memo Optional[string] `json:"memo"` + Timestamp Optional[string] `json:"timestamp"` + ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` // Deprecated + ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` // Deprecated + AccrueCharge *bool `json:"accrue_charge,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePointId *int `json:"price_point_id,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + PreviousPricePointId *int `json:"previous_price_point_id,omitempty"` + PricePointHandle *string `json:"price_point_handle,omitempty"` + PricePointName *string `json:"price_point_name,omitempty"` + ComponentHandle Optional[string] `json:"component_handle"` } -// MarshalJSON implements the json.Marshaler interface for AllocationPreviewItem. +// MarshalJSON implements the json.Marshaler interface for AllocationPreviewItem. // It customizes the JSON marshaling process for AllocationPreviewItem objects. func (a *AllocationPreviewItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AllocationPreviewItem object to a map representation for JSON marshaling. func (a *AllocationPreviewItem) toMap() map[string]any { - structMap := make(map[string]any) - if a.ComponentId != nil { - structMap["component_id"] = a.ComponentId - } - if a.SubscriptionId != nil { - structMap["subscription_id"] = a.SubscriptionId - } - if a.Quantity != nil { - structMap["quantity"] = a.Quantity - } - if a.PreviousQuantity != nil { - structMap["previous_quantity"] = a.PreviousQuantity - } - if a.Memo.IsValueSet() { - structMap["memo"] = a.Memo.Value() - } - if a.Timestamp.IsValueSet() { - structMap["timestamp"] = a.Timestamp.Value() - } - if a.ProrationUpgradeScheme != nil { - structMap["proration_upgrade_scheme"] = a.ProrationUpgradeScheme - } - if a.ProrationDowngradeScheme != nil { - structMap["proration_downgrade_scheme"] = a.ProrationDowngradeScheme - } - if a.AccrueCharge != nil { - structMap["accrue_charge"] = a.AccrueCharge - } - if a.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = a.UpgradeCharge.Value() - } - if a.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = a.DowngradeCredit.Value() - } - if a.PricePointId != nil { - structMap["price_point_id"] = a.PricePointId - } - if a.Interval != nil { - structMap["interval"] = a.Interval - } - if a.IntervalUnit != nil { - structMap["interval_unit"] = a.IntervalUnit - } - if a.PreviousPricePointId != nil { - structMap["previous_price_point_id"] = a.PreviousPricePointId - } - if a.PricePointHandle != nil { - structMap["price_point_handle"] = a.PricePointHandle - } - if a.PricePointName != nil { - structMap["price_point_name"] = a.PricePointName - } - if a.ComponentHandle.IsValueSet() { - structMap["component_handle"] = a.ComponentHandle.Value() - } - return structMap + structMap := make(map[string]any) + if a.ComponentId != nil { + structMap["component_id"] = a.ComponentId + } + if a.SubscriptionId != nil { + structMap["subscription_id"] = a.SubscriptionId + } + if a.Quantity != nil { + structMap["quantity"] = a.Quantity.toMap() + } + if a.PreviousQuantity != nil { + structMap["previous_quantity"] = a.PreviousQuantity.toMap() + } + if a.Memo.IsValueSet() { + if a.Memo.Value() != nil { + structMap["memo"] = a.Memo.Value() + } else { + structMap["memo"] = nil + } + } + if a.Timestamp.IsValueSet() { + if a.Timestamp.Value() != nil { + structMap["timestamp"] = a.Timestamp.Value() + } else { + structMap["timestamp"] = nil + } + } + if a.ProrationUpgradeScheme != nil { + structMap["proration_upgrade_scheme"] = a.ProrationUpgradeScheme + } + if a.ProrationDowngradeScheme != nil { + structMap["proration_downgrade_scheme"] = a.ProrationDowngradeScheme + } + if a.AccrueCharge != nil { + structMap["accrue_charge"] = a.AccrueCharge + } + if a.UpgradeCharge.IsValueSet() { + if a.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = a.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if a.DowngradeCredit.IsValueSet() { + if a.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = a.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if a.PricePointId != nil { + structMap["price_point_id"] = a.PricePointId + } + if a.Interval != nil { + structMap["interval"] = a.Interval + } + if a.IntervalUnit != nil { + structMap["interval_unit"] = a.IntervalUnit + } + if a.PreviousPricePointId != nil { + structMap["previous_price_point_id"] = a.PreviousPricePointId + } + if a.PricePointHandle != nil { + structMap["price_point_handle"] = a.PricePointHandle + } + if a.PricePointName != nil { + structMap["price_point_name"] = a.PricePointName + } + if a.ComponentHandle.IsValueSet() { + if a.ComponentHandle.Value() != nil { + structMap["component_handle"] = a.ComponentHandle.Value() + } else { + structMap["component_handle"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPreviewItem. +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPreviewItem. // It customizes the JSON unmarshaling process for AllocationPreviewItem objects. func (a *AllocationPreviewItem) UnmarshalJSON(input []byte) error { - temp := &struct { - ComponentId *int `json:"component_id,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - Quantity *interface{} `json:"quantity,omitempty"` - PreviousQuantity *interface{} `json:"previous_quantity,omitempty"` - Memo Optional[string] `json:"memo"` - Timestamp Optional[string] `json:"timestamp"` - ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` - ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` - AccrueCharge *bool `json:"accrue_charge,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePointId *int `json:"price_point_id,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - PreviousPricePointId *int `json:"previous_price_point_id,omitempty"` - PricePointHandle *string `json:"price_point_handle,omitempty"` - PricePointName *string `json:"price_point_name,omitempty"` - ComponentHandle Optional[string] `json:"component_handle"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.ComponentId = temp.ComponentId - a.SubscriptionId = temp.SubscriptionId - a.Quantity = temp.Quantity - a.PreviousQuantity = temp.PreviousQuantity - a.Memo = temp.Memo - a.Timestamp = temp.Timestamp - a.ProrationUpgradeScheme = temp.ProrationUpgradeScheme - a.ProrationDowngradeScheme = temp.ProrationDowngradeScheme - a.AccrueCharge = temp.AccrueCharge - a.UpgradeCharge = temp.UpgradeCharge - a.DowngradeCredit = temp.DowngradeCredit - a.PricePointId = temp.PricePointId - a.Interval = temp.Interval - a.IntervalUnit = temp.IntervalUnit - a.PreviousPricePointId = temp.PreviousPricePointId - a.PricePointHandle = temp.PricePointHandle - a.PricePointName = temp.PricePointName - a.ComponentHandle = temp.ComponentHandle - return nil + var temp allocationPreviewItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.ComponentId = temp.ComponentId + a.SubscriptionId = temp.SubscriptionId + a.Quantity = temp.Quantity + a.PreviousQuantity = temp.PreviousQuantity + a.Memo = temp.Memo + a.Timestamp = temp.Timestamp + a.ProrationUpgradeScheme = temp.ProrationUpgradeScheme + a.ProrationDowngradeScheme = temp.ProrationDowngradeScheme + a.AccrueCharge = temp.AccrueCharge + a.UpgradeCharge = temp.UpgradeCharge + a.DowngradeCredit = temp.DowngradeCredit + a.PricePointId = temp.PricePointId + a.Interval = temp.Interval + a.IntervalUnit = temp.IntervalUnit + a.PreviousPricePointId = temp.PreviousPricePointId + a.PricePointHandle = temp.PricePointHandle + a.PricePointName = temp.PricePointName + a.ComponentHandle = temp.ComponentHandle + return nil +} + +// TODO +type allocationPreviewItem struct { + ComponentId *int `json:"component_id,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + Quantity *AllocationPreviewItemQuantity `json:"quantity,omitempty"` + PreviousQuantity *AllocationPreviewItemPreviousQuantity `json:"previous_quantity,omitempty"` + Memo Optional[string] `json:"memo"` + Timestamp Optional[string] `json:"timestamp"` + ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` + ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` + AccrueCharge *bool `json:"accrue_charge,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePointId *int `json:"price_point_id,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + PreviousPricePointId *int `json:"previous_price_point_id,omitempty"` + PricePointHandle *string `json:"price_point_handle,omitempty"` + PricePointName *string `json:"price_point_name,omitempty"` + ComponentHandle Optional[string] `json:"component_handle"` } diff --git a/models/allocation_preview_item_previous_quantity.go b/models/allocation_preview_item_previous_quantity.go new file mode 100644 index 00000000..119acb21 --- /dev/null +++ b/models/allocation_preview_item_previous_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// AllocationPreviewItemPreviousQuantity represents a AllocationPreviewItemPreviousQuantity struct. +// This is a container for one-of cases. +type AllocationPreviewItemPreviousQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the AllocationPreviewItemPreviousQuantity object to a string representation. +func (a AllocationPreviewItemPreviousQuantity) String() string { + if bytes, err := json.Marshal(a.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for AllocationPreviewItemPreviousQuantity. +// It customizes the JSON marshaling process for AllocationPreviewItemPreviousQuantity objects. +func (a *AllocationPreviewItemPreviousQuantity) MarshalJSON() ( + []byte, + error) { + if a.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.AllocationPreviewItemPreviousQuantityContainer.From*` functions to initialize the AllocationPreviewItemPreviousQuantity object.") + } + return json.Marshal(a.toMap()) +} + +// toMap converts the AllocationPreviewItemPreviousQuantity object to a map representation for JSON marshaling. +func (a *AllocationPreviewItemPreviousQuantity) toMap() any { + switch obj := a.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPreviewItemPreviousQuantity. +// It customizes the JSON unmarshaling process for AllocationPreviewItemPreviousQuantity objects. +func (a *AllocationPreviewItemPreviousQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &a.isNumber), + NewTypeHolder(new(string), false, &a.isString), + ) + + a.value = result + return err +} + +func (a *AllocationPreviewItemPreviousQuantity) AsNumber() ( + *int, + bool) { + if !a.isNumber { + return nil, false + } + return a.value.(*int), true +} + +func (a *AllocationPreviewItemPreviousQuantity) AsString() ( + *string, + bool) { + if !a.isString { + return nil, false + } + return a.value.(*string), true +} + +// internalAllocationPreviewItemPreviousQuantity represents a allocationPreviewItemPreviousQuantity struct. +// This is a container for one-of cases. +type internalAllocationPreviewItemPreviousQuantity struct{} + +var AllocationPreviewItemPreviousQuantityContainer internalAllocationPreviewItemPreviousQuantity + +func (a *internalAllocationPreviewItemPreviousQuantity) FromNumber(val int) AllocationPreviewItemPreviousQuantity { + return AllocationPreviewItemPreviousQuantity{value: &val} +} + +func (a *internalAllocationPreviewItemPreviousQuantity) FromString(val string) AllocationPreviewItemPreviousQuantity { + return AllocationPreviewItemPreviousQuantity{value: &val} +} diff --git a/models/allocation_preview_item_quantity.go b/models/allocation_preview_item_quantity.go new file mode 100644 index 00000000..f394f63b --- /dev/null +++ b/models/allocation_preview_item_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// AllocationPreviewItemQuantity represents a AllocationPreviewItemQuantity struct. +// This is a container for one-of cases. +type AllocationPreviewItemQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the AllocationPreviewItemQuantity object to a string representation. +func (a AllocationPreviewItemQuantity) String() string { + if bytes, err := json.Marshal(a.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for AllocationPreviewItemQuantity. +// It customizes the JSON marshaling process for AllocationPreviewItemQuantity objects. +func (a *AllocationPreviewItemQuantity) MarshalJSON() ( + []byte, + error) { + if a.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.AllocationPreviewItemQuantityContainer.From*` functions to initialize the AllocationPreviewItemQuantity object.") + } + return json.Marshal(a.toMap()) +} + +// toMap converts the AllocationPreviewItemQuantity object to a map representation for JSON marshaling. +func (a *AllocationPreviewItemQuantity) toMap() any { + switch obj := a.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPreviewItemQuantity. +// It customizes the JSON unmarshaling process for AllocationPreviewItemQuantity objects. +func (a *AllocationPreviewItemQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &a.isNumber), + NewTypeHolder(new(string), false, &a.isString), + ) + + a.value = result + return err +} + +func (a *AllocationPreviewItemQuantity) AsNumber() ( + *int, + bool) { + if !a.isNumber { + return nil, false + } + return a.value.(*int), true +} + +func (a *AllocationPreviewItemQuantity) AsString() ( + *string, + bool) { + if !a.isString { + return nil, false + } + return a.value.(*string), true +} + +// internalAllocationPreviewItemQuantity represents a allocationPreviewItemQuantity struct. +// This is a container for one-of cases. +type internalAllocationPreviewItemQuantity struct{} + +var AllocationPreviewItemQuantityContainer internalAllocationPreviewItemQuantity + +func (a *internalAllocationPreviewItemQuantity) FromNumber(val int) AllocationPreviewItemQuantity { + return AllocationPreviewItemQuantity{value: &val} +} + +func (a *internalAllocationPreviewItemQuantity) FromString(val string) AllocationPreviewItemQuantity { + return AllocationPreviewItemQuantity{value: &val} +} diff --git a/models/allocation_preview_line_item.go b/models/allocation_preview_line_item.go index cdd698b6..fedf1184 100644 --- a/models/allocation_preview_line_item.go +++ b/models/allocation_preview_line_item.go @@ -1,93 +1,95 @@ package models import ( - "encoding/json" + "encoding/json" ) // AllocationPreviewLineItem represents a AllocationPreviewLineItem struct. type AllocationPreviewLineItem struct { - // A handle for the line item transaction type - TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` - // A handle for the line item kind for allocation preview - Kind *AllocationPreviewLineItemKind `json:"kind,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - Memo *string `json:"memo,omitempty"` - DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` - TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - ComponentHandle *string `json:"component_handle,omitempty"` - // Visible when using Fine-grained Component Control - Direction *AllocationPreviewDirection `json:"direction,omitempty"` + // A handle for the line item transaction type + TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` + // A handle for the line item kind for allocation preview + Kind *AllocationPreviewLineItemKind `json:"kind,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + Memo *string `json:"memo,omitempty"` + DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` + TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + ComponentHandle *string `json:"component_handle,omitempty"` + // Visible when using Fine-grained Component Control + Direction *AllocationPreviewDirection `json:"direction,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for AllocationPreviewLineItem. +// MarshalJSON implements the json.Marshaler interface for AllocationPreviewLineItem. // It customizes the JSON marshaling process for AllocationPreviewLineItem objects. func (a *AllocationPreviewLineItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AllocationPreviewLineItem object to a map representation for JSON marshaling. func (a *AllocationPreviewLineItem) toMap() map[string]any { - structMap := make(map[string]any) - if a.TransactionType != nil { - structMap["transaction_type"] = a.TransactionType - } - if a.Kind != nil { - structMap["kind"] = a.Kind - } - if a.AmountInCents != nil { - structMap["amount_in_cents"] = a.AmountInCents - } - if a.Memo != nil { - structMap["memo"] = a.Memo - } - if a.DiscountAmountInCents != nil { - structMap["discount_amount_in_cents"] = a.DiscountAmountInCents - } - if a.TaxableAmountInCents != nil { - structMap["taxable_amount_in_cents"] = a.TaxableAmountInCents - } - if a.ComponentId != nil { - structMap["component_id"] = a.ComponentId - } - if a.ComponentHandle != nil { - structMap["component_handle"] = a.ComponentHandle - } - if a.Direction != nil { - structMap["direction"] = a.Direction - } - return structMap + structMap := make(map[string]any) + if a.TransactionType != nil { + structMap["transaction_type"] = a.TransactionType + } + if a.Kind != nil { + structMap["kind"] = a.Kind + } + if a.AmountInCents != nil { + structMap["amount_in_cents"] = a.AmountInCents + } + if a.Memo != nil { + structMap["memo"] = a.Memo + } + if a.DiscountAmountInCents != nil { + structMap["discount_amount_in_cents"] = a.DiscountAmountInCents + } + if a.TaxableAmountInCents != nil { + structMap["taxable_amount_in_cents"] = a.TaxableAmountInCents + } + if a.ComponentId != nil { + structMap["component_id"] = a.ComponentId + } + if a.ComponentHandle != nil { + structMap["component_handle"] = a.ComponentHandle + } + if a.Direction != nil { + structMap["direction"] = a.Direction + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPreviewLineItem. +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPreviewLineItem. // It customizes the JSON unmarshaling process for AllocationPreviewLineItem objects. func (a *AllocationPreviewLineItem) UnmarshalJSON(input []byte) error { - temp := &struct { - TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` - Kind *AllocationPreviewLineItemKind `json:"kind,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - Memo *string `json:"memo,omitempty"` - DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` - TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - ComponentHandle *string `json:"component_handle,omitempty"` - Direction *AllocationPreviewDirection `json:"direction,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.TransactionType = temp.TransactionType - a.Kind = temp.Kind - a.AmountInCents = temp.AmountInCents - a.Memo = temp.Memo - a.DiscountAmountInCents = temp.DiscountAmountInCents - a.TaxableAmountInCents = temp.TaxableAmountInCents - a.ComponentId = temp.ComponentId - a.ComponentHandle = temp.ComponentHandle - a.Direction = temp.Direction - return nil + var temp allocationPreviewLineItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.TransactionType = temp.TransactionType + a.Kind = temp.Kind + a.AmountInCents = temp.AmountInCents + a.Memo = temp.Memo + a.DiscountAmountInCents = temp.DiscountAmountInCents + a.TaxableAmountInCents = temp.TaxableAmountInCents + a.ComponentId = temp.ComponentId + a.ComponentHandle = temp.ComponentHandle + a.Direction = temp.Direction + return nil +} + +// TODO +type allocationPreviewLineItem struct { + TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` + Kind *AllocationPreviewLineItemKind `json:"kind,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + Memo *string `json:"memo,omitempty"` + DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` + TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + ComponentHandle *string `json:"component_handle,omitempty"` + Direction *AllocationPreviewDirection `json:"direction,omitempty"` } diff --git a/models/allocation_preview_response.go b/models/allocation_preview_response.go index 8b0edfc0..4c0bee82 100644 --- a/models/allocation_preview_response.go +++ b/models/allocation_preview_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // AllocationPreviewResponse represents a AllocationPreviewResponse struct. type AllocationPreviewResponse struct { - AllocationPreview AllocationPreview `json:"allocation_preview"` + AllocationPreview AllocationPreview `json:"allocation_preview"` } -// MarshalJSON implements the json.Marshaler interface for AllocationPreviewResponse. +// MarshalJSON implements the json.Marshaler interface for AllocationPreviewResponse. // It customizes the JSON marshaling process for AllocationPreviewResponse objects. func (a *AllocationPreviewResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AllocationPreviewResponse object to a map representation for JSON marshaling. func (a *AllocationPreviewResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["allocation_preview"] = a.AllocationPreview.toMap() - return structMap + structMap := make(map[string]any) + structMap["allocation_preview"] = a.AllocationPreview.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPreviewResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPreviewResponse. // It customizes the JSON unmarshaling process for AllocationPreviewResponse objects. func (a *AllocationPreviewResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - AllocationPreview AllocationPreview `json:"allocation_preview"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.AllocationPreview = temp.AllocationPreview - return nil + var temp allocationPreviewResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + a.AllocationPreview = *temp.AllocationPreview + return nil +} + +// TODO +type allocationPreviewResponse struct { + AllocationPreview *AllocationPreview `json:"allocation_preview"` +} + +func (a *allocationPreviewResponse) validate() error { + var errs []string + if a.AllocationPreview == nil { + errs = append(errs, "required field `allocation_preview` is missing for type `Allocation Preview Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/allocation_previous_quantity.go b/models/allocation_previous_quantity.go new file mode 100644 index 00000000..8aa7af3b --- /dev/null +++ b/models/allocation_previous_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// AllocationPreviousQuantity represents a AllocationPreviousQuantity struct. +// This is a container for one-of cases. +type AllocationPreviousQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the AllocationPreviousQuantity object to a string representation. +func (a AllocationPreviousQuantity) String() string { + if bytes, err := json.Marshal(a.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for AllocationPreviousQuantity. +// It customizes the JSON marshaling process for AllocationPreviousQuantity objects. +func (a *AllocationPreviousQuantity) MarshalJSON() ( + []byte, + error) { + if a.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.AllocationPreviousQuantityContainer.From*` functions to initialize the AllocationPreviousQuantity object.") + } + return json.Marshal(a.toMap()) +} + +// toMap converts the AllocationPreviousQuantity object to a map representation for JSON marshaling. +func (a *AllocationPreviousQuantity) toMap() any { + switch obj := a.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationPreviousQuantity. +// It customizes the JSON unmarshaling process for AllocationPreviousQuantity objects. +func (a *AllocationPreviousQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &a.isNumber), + NewTypeHolder(new(string), false, &a.isString), + ) + + a.value = result + return err +} + +func (a *AllocationPreviousQuantity) AsNumber() ( + *int, + bool) { + if !a.isNumber { + return nil, false + } + return a.value.(*int), true +} + +func (a *AllocationPreviousQuantity) AsString() ( + *string, + bool) { + if !a.isString { + return nil, false + } + return a.value.(*string), true +} + +// internalAllocationPreviousQuantity represents a allocationPreviousQuantity struct. +// This is a container for one-of cases. +type internalAllocationPreviousQuantity struct{} + +var AllocationPreviousQuantityContainer internalAllocationPreviousQuantity + +func (a *internalAllocationPreviousQuantity) FromNumber(val int) AllocationPreviousQuantity { + return AllocationPreviousQuantity{value: &val} +} + +func (a *internalAllocationPreviousQuantity) FromString(val string) AllocationPreviousQuantity { + return AllocationPreviousQuantity{value: &val} +} diff --git a/models/allocation_quantity.go b/models/allocation_quantity.go new file mode 100644 index 00000000..fd55fd18 --- /dev/null +++ b/models/allocation_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// AllocationQuantity represents a AllocationQuantity struct. +// This is a container for one-of cases. +type AllocationQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the AllocationQuantity object to a string representation. +func (a AllocationQuantity) String() string { + if bytes, err := json.Marshal(a.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for AllocationQuantity. +// It customizes the JSON marshaling process for AllocationQuantity objects. +func (a *AllocationQuantity) MarshalJSON() ( + []byte, + error) { + if a.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.AllocationQuantityContainer.From*` functions to initialize the AllocationQuantity object.") + } + return json.Marshal(a.toMap()) +} + +// toMap converts the AllocationQuantity object to a map representation for JSON marshaling. +func (a *AllocationQuantity) toMap() any { + switch obj := a.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationQuantity. +// It customizes the JSON unmarshaling process for AllocationQuantity objects. +func (a *AllocationQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &a.isNumber), + NewTypeHolder(new(string), false, &a.isString), + ) + + a.value = result + return err +} + +func (a *AllocationQuantity) AsNumber() ( + *int, + bool) { + if !a.isNumber { + return nil, false + } + return a.value.(*int), true +} + +func (a *AllocationQuantity) AsString() ( + *string, + bool) { + if !a.isString { + return nil, false + } + return a.value.(*string), true +} + +// internalAllocationQuantity represents a allocationQuantity struct. +// This is a container for one-of cases. +type internalAllocationQuantity struct{} + +var AllocationQuantityContainer internalAllocationQuantity + +func (a *internalAllocationQuantity) FromNumber(val int) AllocationQuantity { + return AllocationQuantity{value: &val} +} + +func (a *internalAllocationQuantity) FromString(val string) AllocationQuantity { + return AllocationQuantity{value: &val} +} diff --git a/models/allocation_response.go b/models/allocation_response.go index ff1b311c..ba740c4d 100644 --- a/models/allocation_response.go +++ b/models/allocation_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // AllocationResponse represents a AllocationResponse struct. type AllocationResponse struct { - Allocation *Allocation `json:"allocation,omitempty"` + Allocation *Allocation `json:"allocation,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for AllocationResponse. +// MarshalJSON implements the json.Marshaler interface for AllocationResponse. // It customizes the JSON marshaling process for AllocationResponse objects. func (a *AllocationResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AllocationResponse object to a map representation for JSON marshaling. func (a *AllocationResponse) toMap() map[string]any { - structMap := make(map[string]any) - if a.Allocation != nil { - structMap["allocation"] = a.Allocation.toMap() - } - return structMap + structMap := make(map[string]any) + if a.Allocation != nil { + structMap["allocation"] = a.Allocation.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AllocationResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationResponse. // It customizes the JSON unmarshaling process for AllocationResponse objects. func (a *AllocationResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Allocation *Allocation `json:"allocation,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.Allocation = temp.Allocation - return nil + var temp allocationResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.Allocation = temp.Allocation + return nil +} + +// TODO +type allocationResponse struct { + Allocation *Allocation `json:"allocation,omitempty"` } diff --git a/models/allocation_settings.go b/models/allocation_settings.go index 8c542fee..3ef5d286 100644 --- a/models/allocation_settings.go +++ b/models/allocation_settings.go @@ -1,59 +1,69 @@ package models import ( - "encoding/json" + "encoding/json" ) // AllocationSettings represents a AllocationSettings struct. type AllocationSettings struct { - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - // Either "true" or "false". - AccrueCharge *string `json:"accrue_charge,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + // Either "true" or "false". + AccrueCharge *string `json:"accrue_charge,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for AllocationSettings. +// MarshalJSON implements the json.Marshaler interface for AllocationSettings. // It customizes the JSON marshaling process for AllocationSettings objects. func (a *AllocationSettings) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AllocationSettings object to a map representation for JSON marshaling. func (a *AllocationSettings) toMap() map[string]any { - structMap := make(map[string]any) - if a.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = a.UpgradeCharge.Value() - } - if a.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = a.DowngradeCredit.Value() - } - if a.AccrueCharge != nil { - structMap["accrue_charge"] = a.AccrueCharge - } - return structMap + structMap := make(map[string]any) + if a.UpgradeCharge.IsValueSet() { + if a.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = a.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if a.DowngradeCredit.IsValueSet() { + if a.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = a.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if a.AccrueCharge != nil { + structMap["accrue_charge"] = a.AccrueCharge + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AllocationSettings. +// UnmarshalJSON implements the json.Unmarshaler interface for AllocationSettings. // It customizes the JSON unmarshaling process for AllocationSettings objects. func (a *AllocationSettings) UnmarshalJSON(input []byte) error { - temp := &struct { - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - AccrueCharge *string `json:"accrue_charge,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.UpgradeCharge = temp.UpgradeCharge - a.DowngradeCredit = temp.DowngradeCredit - a.AccrueCharge = temp.AccrueCharge - return nil + var temp allocationSettings + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.UpgradeCharge = temp.UpgradeCharge + a.DowngradeCredit = temp.DowngradeCredit + a.AccrueCharge = temp.AccrueCharge + return nil +} + +// TODO +type allocationSettings struct { + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + AccrueCharge *string `json:"accrue_charge,omitempty"` } diff --git a/models/applied_credit_note_data.go b/models/applied_credit_note_data.go index 06db8970..48fe387a 100644 --- a/models/applied_credit_note_data.go +++ b/models/applied_credit_note_data.go @@ -1,50 +1,52 @@ package models import ( - "encoding/json" + "encoding/json" ) // AppliedCreditNoteData represents a AppliedCreditNoteData struct. type AppliedCreditNoteData struct { - // The UID of the credit note - Uid *string `json:"uid,omitempty"` - // The number of the credit note - Number *string `json:"number,omitempty"` + // The UID of the credit note + Uid *string `json:"uid,omitempty"` + // The number of the credit note + Number *string `json:"number,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for AppliedCreditNoteData. +// MarshalJSON implements the json.Marshaler interface for AppliedCreditNoteData. // It customizes the JSON marshaling process for AppliedCreditNoteData objects. func (a *AppliedCreditNoteData) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AppliedCreditNoteData object to a map representation for JSON marshaling. func (a *AppliedCreditNoteData) toMap() map[string]any { - structMap := make(map[string]any) - if a.Uid != nil { - structMap["uid"] = a.Uid - } - if a.Number != nil { - structMap["number"] = a.Number - } - return structMap + structMap := make(map[string]any) + if a.Uid != nil { + structMap["uid"] = a.Uid + } + if a.Number != nil { + structMap["number"] = a.Number + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AppliedCreditNoteData. +// UnmarshalJSON implements the json.Unmarshaler interface for AppliedCreditNoteData. // It customizes the JSON unmarshaling process for AppliedCreditNoteData objects. func (a *AppliedCreditNoteData) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Number *string `json:"number,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.Uid = temp.Uid - a.Number = temp.Number - return nil + var temp appliedCreditNoteData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.Uid = temp.Uid + a.Number = temp.Number + return nil +} + +// TODO +type appliedCreditNoteData struct { + Uid *string `json:"uid,omitempty"` + Number *string `json:"number,omitempty"` } diff --git a/models/apply_credit_note_event_data.go b/models/apply_credit_note_event_data.go new file mode 100644 index 00000000..3d47aa6a --- /dev/null +++ b/models/apply_credit_note_event_data.go @@ -0,0 +1,137 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// ApplyCreditNoteEventData represents a ApplyCreditNoteEventData struct. +// Example schema for an `apply_credit_note` event +type ApplyCreditNoteEventData struct { + // Unique identifier for the credit note application. It is generated automatically by Chargify and has the prefix "cdt_" followed by alphanumeric characters. + Uid string `json:"uid"` + // A unique, identifying string that appears on the credit note and in places it is referenced. + CreditNoteNumber string `json:"credit_note_number"` + // Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. + CreditNoteUid string `json:"credit_note_uid"` + // The full, original amount of the credit note. + OriginalAmount string `json:"original_amount"` + // The amount of the credit note applied to invoice. + AppliedAmount string `json:"applied_amount"` + // The time the credit note was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" + TransactionTime *time.Time `json:"transaction_time,omitempty"` + // The credit note memo. + Memo *string `json:"memo,omitempty"` + // The role of the credit note (e.g. 'general') + Role *string `json:"role,omitempty"` + // Shows whether it was applied to consolidated invoice or not + ConsolidatedInvoice *bool `json:"consolidated_invoice,omitempty"` + // List of credit notes applied to children invoices (if consolidated invoice) + AppliedCreditNotes []AppliedCreditNoteData `json:"applied_credit_notes,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for ApplyCreditNoteEventData. +// It customizes the JSON marshaling process for ApplyCreditNoteEventData objects. +func (a *ApplyCreditNoteEventData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(a.toMap()) +} + +// toMap converts the ApplyCreditNoteEventData object to a map representation for JSON marshaling. +func (a *ApplyCreditNoteEventData) toMap() map[string]any { + structMap := make(map[string]any) + structMap["uid"] = a.Uid + structMap["credit_note_number"] = a.CreditNoteNumber + structMap["credit_note_uid"] = a.CreditNoteUid + structMap["original_amount"] = a.OriginalAmount + structMap["applied_amount"] = a.AppliedAmount + if a.TransactionTime != nil { + structMap["transaction_time"] = a.TransactionTime.Format(time.RFC3339) + } + if a.Memo != nil { + structMap["memo"] = a.Memo + } + if a.Role != nil { + structMap["role"] = a.Role + } + if a.ConsolidatedInvoice != nil { + structMap["consolidated_invoice"] = a.ConsolidatedInvoice + } + if a.AppliedCreditNotes != nil { + structMap["applied_credit_notes"] = a.AppliedCreditNotes + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ApplyCreditNoteEventData. +// It customizes the JSON unmarshaling process for ApplyCreditNoteEventData objects. +func (a *ApplyCreditNoteEventData) UnmarshalJSON(input []byte) error { + var temp applyCreditNoteEventData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + a.Uid = *temp.Uid + a.CreditNoteNumber = *temp.CreditNoteNumber + a.CreditNoteUid = *temp.CreditNoteUid + a.OriginalAmount = *temp.OriginalAmount + a.AppliedAmount = *temp.AppliedAmount + if temp.TransactionTime != nil { + TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) + if err != nil { + log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) + } + a.TransactionTime = &TransactionTimeVal + } + a.Memo = temp.Memo + a.Role = temp.Role + a.ConsolidatedInvoice = temp.ConsolidatedInvoice + a.AppliedCreditNotes = temp.AppliedCreditNotes + return nil +} + +// TODO +type applyCreditNoteEventData struct { + Uid *string `json:"uid"` + CreditNoteNumber *string `json:"credit_note_number"` + CreditNoteUid *string `json:"credit_note_uid"` + OriginalAmount *string `json:"original_amount"` + AppliedAmount *string `json:"applied_amount"` + TransactionTime *string `json:"transaction_time,omitempty"` + Memo *string `json:"memo,omitempty"` + Role *string `json:"role,omitempty"` + ConsolidatedInvoice *bool `json:"consolidated_invoice,omitempty"` + AppliedCreditNotes []AppliedCreditNoteData `json:"applied_credit_notes,omitempty"` +} + +func (a *applyCreditNoteEventData) validate() error { + var errs []string + if a.Uid == nil { + errs = append(errs, "required field `uid` is missing for type `Apply Credit Note Event Data`") + } + if a.CreditNoteNumber == nil { + errs = append(errs, "required field `credit_note_number` is missing for type `Apply Credit Note Event Data`") + } + if a.CreditNoteUid == nil { + errs = append(errs, "required field `credit_note_uid` is missing for type `Apply Credit Note Event Data`") + } + if a.OriginalAmount == nil { + errs = append(errs, "required field `original_amount` is missing for type `Apply Credit Note Event Data`") + } + if a.AppliedAmount == nil { + errs = append(errs, "required field `applied_amount` is missing for type `Apply Credit Note Event Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/apply_debit_note_event_data.go b/models/apply_debit_note_event_data.go new file mode 100644 index 00000000..f01ac76d --- /dev/null +++ b/models/apply_debit_note_event_data.go @@ -0,0 +1,86 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ApplyDebitNoteEventData represents a ApplyDebitNoteEventData struct. +// Example schema for an `apply_debit_note` event +type ApplyDebitNoteEventData struct { + // A unique, identifying string that appears on the debit note and in places it is referenced. + DebitNoteNumber string `json:"debit_note_number"` + // Unique identifier for the debit note. It is generated automatically by Chargify and has the prefix "db_" followed by alphanumeric characters. + DebitNoteUid string `json:"debit_note_uid"` + // The full, original amount of the debit note. + OriginalAmount string `json:"original_amount"` + // The amount of the debit note applied to invoice. + AppliedAmount string `json:"applied_amount"` +} + +// MarshalJSON implements the json.Marshaler interface for ApplyDebitNoteEventData. +// It customizes the JSON marshaling process for ApplyDebitNoteEventData objects. +func (a *ApplyDebitNoteEventData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(a.toMap()) +} + +// toMap converts the ApplyDebitNoteEventData object to a map representation for JSON marshaling. +func (a *ApplyDebitNoteEventData) toMap() map[string]any { + structMap := make(map[string]any) + structMap["debit_note_number"] = a.DebitNoteNumber + structMap["debit_note_uid"] = a.DebitNoteUid + structMap["original_amount"] = a.OriginalAmount + structMap["applied_amount"] = a.AppliedAmount + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ApplyDebitNoteEventData. +// It customizes the JSON unmarshaling process for ApplyDebitNoteEventData objects. +func (a *ApplyDebitNoteEventData) UnmarshalJSON(input []byte) error { + var temp applyDebitNoteEventData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + a.DebitNoteNumber = *temp.DebitNoteNumber + a.DebitNoteUid = *temp.DebitNoteUid + a.OriginalAmount = *temp.OriginalAmount + a.AppliedAmount = *temp.AppliedAmount + return nil +} + +// TODO +type applyDebitNoteEventData struct { + DebitNoteNumber *string `json:"debit_note_number"` + DebitNoteUid *string `json:"debit_note_uid"` + OriginalAmount *string `json:"original_amount"` + AppliedAmount *string `json:"applied_amount"` +} + +func (a *applyDebitNoteEventData) validate() error { + var errs []string + if a.DebitNoteNumber == nil { + errs = append(errs, "required field `debit_note_number` is missing for type `Apply Debit Note Event Data`") + } + if a.DebitNoteUid == nil { + errs = append(errs, "required field `debit_note_uid` is missing for type `Apply Debit Note Event Data`") + } + if a.OriginalAmount == nil { + errs = append(errs, "required field `original_amount` is missing for type `Apply Debit Note Event Data`") + } + if a.AppliedAmount == nil { + errs = append(errs, "required field `applied_amount` is missing for type `Apply Debit Note Event Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/apply_payment_event_data.go b/models/apply_payment_event_data.go new file mode 100644 index 00000000..2d7f195c --- /dev/null +++ b/models/apply_payment_event_data.go @@ -0,0 +1,139 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// ApplyPaymentEventData represents a ApplyPaymentEventData struct. +// Example schema for an `apply_payment` event +type ApplyPaymentEventData struct { + // The payment memo + Memo string `json:"memo"` + // The full, original amount of the payment transaction as a string in full units. Incoming payments can be split amongst several invoices, which will result in a `applied_amount` less than the `original_amount`. Example: A $100.99 payment, of which $40.11 is applied to this invoice, will have an `original_amount` of `"100.99"`. + OriginalAmount string `json:"original_amount"` + // The amount of the payment applied to this invoice. Incoming payments can be split amongst several invoices, which will result in a `applied_amount` less than the `original_amount`. Example: A $100.99 payment, of which $40.11 is applied to this invoice, will have an `applied_amount` of `"40.11"`. + AppliedAmount string `json:"applied_amount"` + // The time the payment was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" + TransactionTime time.Time `json:"transaction_time"` + // A nested data structure detailing the method of payment + PaymentMethod InvoiceEventPayment2 `json:"payment_method"` + // The Chargify id of the original payment + TransactionId *int `json:"transaction_id,omitempty"` + ParentInvoiceNumber Optional[int] `json:"parent_invoice_number"` + RemainingPrepaymentAmount Optional[string] `json:"remaining_prepayment_amount"` + Prepayment *bool `json:"prepayment,omitempty"` + External *bool `json:"external,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for ApplyPaymentEventData. +// It customizes the JSON marshaling process for ApplyPaymentEventData objects. +func (a *ApplyPaymentEventData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(a.toMap()) +} + +// toMap converts the ApplyPaymentEventData object to a map representation for JSON marshaling. +func (a *ApplyPaymentEventData) toMap() map[string]any { + structMap := make(map[string]any) + structMap["memo"] = a.Memo + structMap["original_amount"] = a.OriginalAmount + structMap["applied_amount"] = a.AppliedAmount + structMap["transaction_time"] = a.TransactionTime.Format(time.RFC3339) + structMap["payment_method"] = a.PaymentMethod.toMap() + if a.TransactionId != nil { + structMap["transaction_id"] = a.TransactionId + } + if a.ParentInvoiceNumber.IsValueSet() { + if a.ParentInvoiceNumber.Value() != nil { + structMap["parent_invoice_number"] = a.ParentInvoiceNumber.Value() + } else { + structMap["parent_invoice_number"] = nil + } + } + if a.RemainingPrepaymentAmount.IsValueSet() { + if a.RemainingPrepaymentAmount.Value() != nil { + structMap["remaining_prepayment_amount"] = a.RemainingPrepaymentAmount.Value() + } else { + structMap["remaining_prepayment_amount"] = nil + } + } + if a.Prepayment != nil { + structMap["prepayment"] = a.Prepayment + } + if a.External != nil { + structMap["external"] = a.External + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ApplyPaymentEventData. +// It customizes the JSON unmarshaling process for ApplyPaymentEventData objects. +func (a *ApplyPaymentEventData) UnmarshalJSON(input []byte) error { + var temp applyPaymentEventData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + a.Memo = *temp.Memo + a.OriginalAmount = *temp.OriginalAmount + a.AppliedAmount = *temp.AppliedAmount + TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) + if err != nil { + log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) + } + a.TransactionTime = TransactionTimeVal + a.PaymentMethod = *temp.PaymentMethod + a.TransactionId = temp.TransactionId + a.ParentInvoiceNumber = temp.ParentInvoiceNumber + a.RemainingPrepaymentAmount = temp.RemainingPrepaymentAmount + a.Prepayment = temp.Prepayment + a.External = temp.External + return nil +} + +// TODO +type applyPaymentEventData struct { + Memo *string `json:"memo"` + OriginalAmount *string `json:"original_amount"` + AppliedAmount *string `json:"applied_amount"` + TransactionTime *string `json:"transaction_time"` + PaymentMethod *InvoiceEventPayment2 `json:"payment_method"` + TransactionId *int `json:"transaction_id,omitempty"` + ParentInvoiceNumber Optional[int] `json:"parent_invoice_number"` + RemainingPrepaymentAmount Optional[string] `json:"remaining_prepayment_amount"` + Prepayment *bool `json:"prepayment,omitempty"` + External *bool `json:"external,omitempty"` +} + +func (a *applyPaymentEventData) validate() error { + var errs []string + if a.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Apply Payment Event Data`") + } + if a.OriginalAmount == nil { + errs = append(errs, "required field `original_amount` is missing for type `Apply Payment Event Data`") + } + if a.AppliedAmount == nil { + errs = append(errs, "required field `applied_amount` is missing for type `Apply Payment Event Data`") + } + if a.TransactionTime == nil { + errs = append(errs, "required field `transaction_time` is missing for type `Apply Payment Event Data`") + } + if a.PaymentMethod == nil { + errs = append(errs, "required field `payment_method` is missing for type `Apply Payment Event Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/archive_product_price_point_price_point_id.go b/models/archive_product_price_point_price_point_id.go new file mode 100644 index 00000000..da2c5562 --- /dev/null +++ b/models/archive_product_price_point_price_point_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ArchiveProductPricePointPricePointId represents a ArchiveProductPricePointPricePointId struct. +// This is a container for one-of cases. +type ArchiveProductPricePointPricePointId struct { + value any + isNumber bool + isString bool +} + +// String converts the ArchiveProductPricePointPricePointId object to a string representation. +func (a ArchiveProductPricePointPricePointId) String() string { + if bytes, err := json.Marshal(a.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ArchiveProductPricePointPricePointId. +// It customizes the JSON marshaling process for ArchiveProductPricePointPricePointId objects. +func (a *ArchiveProductPricePointPricePointId) MarshalJSON() ( + []byte, + error) { + if a.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ArchiveProductPricePointPricePointIdContainer.From*` functions to initialize the ArchiveProductPricePointPricePointId object.") + } + return json.Marshal(a.toMap()) +} + +// toMap converts the ArchiveProductPricePointPricePointId object to a map representation for JSON marshaling. +func (a *ArchiveProductPricePointPricePointId) toMap() any { + switch obj := a.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ArchiveProductPricePointPricePointId. +// It customizes the JSON unmarshaling process for ArchiveProductPricePointPricePointId objects. +func (a *ArchiveProductPricePointPricePointId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &a.isNumber), + NewTypeHolder(new(string), false, &a.isString), + ) + + a.value = result + return err +} + +func (a *ArchiveProductPricePointPricePointId) AsNumber() ( + *int, + bool) { + if !a.isNumber { + return nil, false + } + return a.value.(*int), true +} + +func (a *ArchiveProductPricePointPricePointId) AsString() ( + *string, + bool) { + if !a.isString { + return nil, false + } + return a.value.(*string), true +} + +// internalArchiveProductPricePointPricePointId represents a archiveProductPricePointPricePointId struct. +// This is a container for one-of cases. +type internalArchiveProductPricePointPricePointId struct{} + +var ArchiveProductPricePointPricePointIdContainer internalArchiveProductPricePointPricePointId + +func (a *internalArchiveProductPricePointPricePointId) FromNumber(val int) ArchiveProductPricePointPricePointId { + return ArchiveProductPricePointPricePointId{value: &val} +} + +func (a *internalArchiveProductPricePointPricePointId) FromString(val string) ArchiveProductPricePointPricePointId { + return ArchiveProductPricePointPricePointId{value: &val} +} diff --git a/models/archive_product_price_point_product_id.go b/models/archive_product_price_point_product_id.go new file mode 100644 index 00000000..2b19fe00 --- /dev/null +++ b/models/archive_product_price_point_product_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ArchiveProductPricePointProductId represents a ArchiveProductPricePointProductId struct. +// This is a container for one-of cases. +type ArchiveProductPricePointProductId struct { + value any + isNumber bool + isString bool +} + +// String converts the ArchiveProductPricePointProductId object to a string representation. +func (a ArchiveProductPricePointProductId) String() string { + if bytes, err := json.Marshal(a.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ArchiveProductPricePointProductId. +// It customizes the JSON marshaling process for ArchiveProductPricePointProductId objects. +func (a *ArchiveProductPricePointProductId) MarshalJSON() ( + []byte, + error) { + if a.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ArchiveProductPricePointProductIdContainer.From*` functions to initialize the ArchiveProductPricePointProductId object.") + } + return json.Marshal(a.toMap()) +} + +// toMap converts the ArchiveProductPricePointProductId object to a map representation for JSON marshaling. +func (a *ArchiveProductPricePointProductId) toMap() any { + switch obj := a.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ArchiveProductPricePointProductId. +// It customizes the JSON unmarshaling process for ArchiveProductPricePointProductId objects. +func (a *ArchiveProductPricePointProductId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &a.isNumber), + NewTypeHolder(new(string), false, &a.isString), + ) + + a.value = result + return err +} + +func (a *ArchiveProductPricePointProductId) AsNumber() ( + *int, + bool) { + if !a.isNumber { + return nil, false + } + return a.value.(*int), true +} + +func (a *ArchiveProductPricePointProductId) AsString() ( + *string, + bool) { + if !a.isString { + return nil, false + } + return a.value.(*string), true +} + +// internalArchiveProductPricePointProductId represents a archiveProductPricePointProductId struct. +// This is a container for one-of cases. +type internalArchiveProductPricePointProductId struct{} + +var ArchiveProductPricePointProductIdContainer internalArchiveProductPricePointProductId + +func (a *internalArchiveProductPricePointProductId) FromNumber(val int) ArchiveProductPricePointProductId { + return ArchiveProductPricePointProductId{value: &val} +} + +func (a *internalArchiveProductPricePointProductId) FromString(val string) ArchiveProductPricePointProductId { + return ArchiveProductPricePointProductId{value: &val} +} diff --git a/models/attribute_error.go b/models/attribute_error.go index 7fb3dedc..cc34ae94 100644 --- a/models/attribute_error.go +++ b/models/attribute_error.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // AttributeError represents a AttributeError struct. type AttributeError struct { - Attribute []string `json:"attribute"` + Attribute []string `json:"attribute"` } -// MarshalJSON implements the json.Marshaler interface for AttributeError. +// MarshalJSON implements the json.Marshaler interface for AttributeError. // It customizes the JSON marshaling process for AttributeError objects. func (a *AttributeError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AttributeError object to a map representation for JSON marshaling. func (a *AttributeError) toMap() map[string]any { - structMap := make(map[string]any) - structMap["attribute"] = a.Attribute - return structMap + structMap := make(map[string]any) + structMap["attribute"] = a.Attribute + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AttributeError. +// UnmarshalJSON implements the json.Unmarshaler interface for AttributeError. // It customizes the JSON unmarshaling process for AttributeError objects. func (a *AttributeError) UnmarshalJSON(input []byte) error { - temp := &struct { - Attribute []string `json:"attribute"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.Attribute = temp.Attribute - return nil + var temp attributeError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + a.Attribute = *temp.Attribute + return nil +} + +// TODO +type attributeError struct { + Attribute *[]string `json:"attribute"` +} + +func (a *attributeError) validate() error { + var errs []string + if a.Attribute == nil { + errs = append(errs, "required field `attribute` is missing for type `Attribute Error`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/auto_resume.go b/models/auto_resume.go index 657c66da..632bd796 100644 --- a/models/auto_resume.go +++ b/models/auto_resume.go @@ -1,56 +1,62 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // AutoResume represents a AutoResume struct. type AutoResume struct { - AutomaticallyResumeAt Optional[time.Time] `json:"automatically_resume_at"` + AutomaticallyResumeAt Optional[time.Time] `json:"automatically_resume_at"` } -// MarshalJSON implements the json.Marshaler interface for AutoResume. +// MarshalJSON implements the json.Marshaler interface for AutoResume. // It customizes the JSON marshaling process for AutoResume objects. func (a *AutoResume) MarshalJSON() ( - []byte, - error) { - return json.Marshal(a.toMap()) + []byte, + error) { + return json.Marshal(a.toMap()) } // toMap converts the AutoResume object to a map representation for JSON marshaling. func (a *AutoResume) toMap() map[string]any { - structMap := make(map[string]any) - if a.AutomaticallyResumeAt.IsValueSet() { - var AutomaticallyResumeAtVal *string = nil - if a.AutomaticallyResumeAt.Value() != nil { - val := a.AutomaticallyResumeAt.Value().Format(time.RFC3339) - AutomaticallyResumeAtVal = &val - } - structMap["automatically_resume_at"] = AutomaticallyResumeAtVal - } - return structMap + structMap := make(map[string]any) + if a.AutomaticallyResumeAt.IsValueSet() { + var AutomaticallyResumeAtVal *string = nil + if a.AutomaticallyResumeAt.Value() != nil { + val := a.AutomaticallyResumeAt.Value().Format(time.RFC3339) + AutomaticallyResumeAtVal = &val + } + if a.AutomaticallyResumeAt.Value() != nil { + structMap["automatically_resume_at"] = AutomaticallyResumeAtVal + } else { + structMap["automatically_resume_at"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for AutoResume. +// UnmarshalJSON implements the json.Unmarshaler interface for AutoResume. // It customizes the JSON unmarshaling process for AutoResume objects. func (a *AutoResume) UnmarshalJSON(input []byte) error { - temp := &struct { - AutomaticallyResumeAt Optional[string] `json:"automatically_resume_at"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - a.AutomaticallyResumeAt.ShouldSetValue(temp.AutomaticallyResumeAt.IsValueSet()) - if temp.AutomaticallyResumeAt.Value() != nil { - AutomaticallyResumeAtVal, err := time.Parse(time.RFC3339, (*temp.AutomaticallyResumeAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse automatically_resume_at as % s format.", time.RFC3339) - } - a.AutomaticallyResumeAt.SetValue(&AutomaticallyResumeAtVal) - } - return nil + var temp autoResume + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + a.AutomaticallyResumeAt.ShouldSetValue(temp.AutomaticallyResumeAt.IsValueSet()) + if temp.AutomaticallyResumeAt.Value() != nil { + AutomaticallyResumeAtVal, err := time.Parse(time.RFC3339, (*temp.AutomaticallyResumeAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse automatically_resume_at as % s format.", time.RFC3339) + } + a.AutomaticallyResumeAt.SetValue(&AutomaticallyResumeAtVal) + } + return nil +} + +// TODO +type autoResume struct { + AutomaticallyResumeAt Optional[string] `json:"automatically_resume_at"` } diff --git a/models/bank_account_attributes.go b/models/bank_account_attributes.go index 1d2ef949..f7a0c300 100644 --- a/models/bank_account_attributes.go +++ b/models/bank_account_attributes.go @@ -1,117 +1,119 @@ package models import ( - "encoding/json" + "encoding/json" ) // BankAccountAttributes represents a BankAccountAttributes struct. type BankAccountAttributes struct { - ChargifyToken *string `json:"chargify_token,omitempty"` - // (Required when creating a subscription with ACH or GoCardless) The name of the bank where the customer’s account resides - BankName *string `json:"bank_name,omitempty"` - // (Required when creating a subscription with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API - BankRoutingNumber *string `json:"bank_routing_number,omitempty"` - // (Required when creating a subscription with ACH. Required when creating a subscription with GoCardless and bank_iban is blank) The customerʼs bank account number - BankAccountNumber *string `json:"bank_account_number,omitempty"` - // Defaults to checking - BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` - // (Optional when creating a subscription with GoCardless) Branch code. Alternatively, an IBAN can be provided - BankBranchCode *string `json:"bank_branch_code,omitempty"` - // (Optional when creating a subscription with GoCardless). International Bank Account Number. Alternatively, local bank details can be provided - BankIban *string `json:"bank_iban,omitempty"` - // Defaults to personal - BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` - PaymentType *PaymentType `json:"payment_type,omitempty"` - // The vault that stores the payment profile with the provided vault_token. - CurrentVault *BankAccountVault `json:"current_vault,omitempty"` - VaultToken *string `json:"vault_token,omitempty"` - // (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token - CustomerVaultToken *string `json:"customer_vault_token,omitempty"` + ChargifyToken *string `json:"chargify_token,omitempty"` + // (Required when creating a subscription with ACH or GoCardless) The name of the bank where the customer’s account resides + BankName *string `json:"bank_name,omitempty"` + // (Required when creating a subscription with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API + BankRoutingNumber *string `json:"bank_routing_number,omitempty"` + // (Required when creating a subscription with ACH. Required when creating a subscription with GoCardless and bank_iban is blank) The customerʼs bank account number + BankAccountNumber *string `json:"bank_account_number,omitempty"` + // Defaults to checking + BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` + // (Optional when creating a subscription with GoCardless) Branch code. Alternatively, an IBAN can be provided + BankBranchCode *string `json:"bank_branch_code,omitempty"` + // (Optional when creating a subscription with GoCardless). International Bank Account Number. Alternatively, local bank details can be provided + BankIban *string `json:"bank_iban,omitempty"` + // Defaults to personal + BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` + PaymentType *PaymentType `json:"payment_type,omitempty"` + // The vault that stores the payment profile with the provided vault_token. + CurrentVault *BankAccountVault `json:"current_vault,omitempty"` + VaultToken *string `json:"vault_token,omitempty"` + // (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token + CustomerVaultToken *string `json:"customer_vault_token,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BankAccountAttributes. +// MarshalJSON implements the json.Marshaler interface for BankAccountAttributes. // It customizes the JSON marshaling process for BankAccountAttributes objects. func (b *BankAccountAttributes) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BankAccountAttributes object to a map representation for JSON marshaling. func (b *BankAccountAttributes) toMap() map[string]any { - structMap := make(map[string]any) - if b.ChargifyToken != nil { - structMap["chargify_token"] = b.ChargifyToken - } - if b.BankName != nil { - structMap["bank_name"] = b.BankName - } - if b.BankRoutingNumber != nil { - structMap["bank_routing_number"] = b.BankRoutingNumber - } - if b.BankAccountNumber != nil { - structMap["bank_account_number"] = b.BankAccountNumber - } - if b.BankAccountType != nil { - structMap["bank_account_type"] = b.BankAccountType - } - if b.BankBranchCode != nil { - structMap["bank_branch_code"] = b.BankBranchCode - } - if b.BankIban != nil { - structMap["bank_iban"] = b.BankIban - } - if b.BankAccountHolderType != nil { - structMap["bank_account_holder_type"] = b.BankAccountHolderType - } - if b.PaymentType != nil { - structMap["payment_type"] = b.PaymentType - } - if b.CurrentVault != nil { - structMap["current_vault"] = b.CurrentVault - } - if b.VaultToken != nil { - structMap["vault_token"] = b.VaultToken - } - if b.CustomerVaultToken != nil { - structMap["customer_vault_token"] = b.CustomerVaultToken - } - return structMap + structMap := make(map[string]any) + if b.ChargifyToken != nil { + structMap["chargify_token"] = b.ChargifyToken + } + if b.BankName != nil { + structMap["bank_name"] = b.BankName + } + if b.BankRoutingNumber != nil { + structMap["bank_routing_number"] = b.BankRoutingNumber + } + if b.BankAccountNumber != nil { + structMap["bank_account_number"] = b.BankAccountNumber + } + if b.BankAccountType != nil { + structMap["bank_account_type"] = b.BankAccountType + } + if b.BankBranchCode != nil { + structMap["bank_branch_code"] = b.BankBranchCode + } + if b.BankIban != nil { + structMap["bank_iban"] = b.BankIban + } + if b.BankAccountHolderType != nil { + structMap["bank_account_holder_type"] = b.BankAccountHolderType + } + if b.PaymentType != nil { + structMap["payment_type"] = b.PaymentType + } + if b.CurrentVault != nil { + structMap["current_vault"] = b.CurrentVault + } + if b.VaultToken != nil { + structMap["vault_token"] = b.VaultToken + } + if b.CustomerVaultToken != nil { + structMap["customer_vault_token"] = b.CustomerVaultToken + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BankAccountAttributes. +// UnmarshalJSON implements the json.Unmarshaler interface for BankAccountAttributes. // It customizes the JSON unmarshaling process for BankAccountAttributes objects. func (b *BankAccountAttributes) UnmarshalJSON(input []byte) error { - temp := &struct { - ChargifyToken *string `json:"chargify_token,omitempty"` - BankName *string `json:"bank_name,omitempty"` - BankRoutingNumber *string `json:"bank_routing_number,omitempty"` - BankAccountNumber *string `json:"bank_account_number,omitempty"` - BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` - BankBranchCode *string `json:"bank_branch_code,omitempty"` - BankIban *string `json:"bank_iban,omitempty"` - BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` - PaymentType *PaymentType `json:"payment_type,omitempty"` - CurrentVault *BankAccountVault `json:"current_vault,omitempty"` - VaultToken *string `json:"vault_token,omitempty"` - CustomerVaultToken *string `json:"customer_vault_token,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.ChargifyToken = temp.ChargifyToken - b.BankName = temp.BankName - b.BankRoutingNumber = temp.BankRoutingNumber - b.BankAccountNumber = temp.BankAccountNumber - b.BankAccountType = temp.BankAccountType - b.BankBranchCode = temp.BankBranchCode - b.BankIban = temp.BankIban - b.BankAccountHolderType = temp.BankAccountHolderType - b.PaymentType = temp.PaymentType - b.CurrentVault = temp.CurrentVault - b.VaultToken = temp.VaultToken - b.CustomerVaultToken = temp.CustomerVaultToken - return nil + var temp bankAccountAttributes + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.ChargifyToken = temp.ChargifyToken + b.BankName = temp.BankName + b.BankRoutingNumber = temp.BankRoutingNumber + b.BankAccountNumber = temp.BankAccountNumber + b.BankAccountType = temp.BankAccountType + b.BankBranchCode = temp.BankBranchCode + b.BankIban = temp.BankIban + b.BankAccountHolderType = temp.BankAccountHolderType + b.PaymentType = temp.PaymentType + b.CurrentVault = temp.CurrentVault + b.VaultToken = temp.VaultToken + b.CustomerVaultToken = temp.CustomerVaultToken + return nil +} + +// TODO +type bankAccountAttributes struct { + ChargifyToken *string `json:"chargify_token,omitempty"` + BankName *string `json:"bank_name,omitempty"` + BankRoutingNumber *string `json:"bank_routing_number,omitempty"` + BankAccountNumber *string `json:"bank_account_number,omitempty"` + BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` + BankBranchCode *string `json:"bank_branch_code,omitempty"` + BankIban *string `json:"bank_iban,omitempty"` + BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` + PaymentType *PaymentType `json:"payment_type,omitempty"` + CurrentVault *BankAccountVault `json:"current_vault,omitempty"` + VaultToken *string `json:"vault_token,omitempty"` + CustomerVaultToken *string `json:"customer_vault_token,omitempty"` } diff --git a/models/bank_account_payment_profile.go b/models/bank_account_payment_profile.go index 16b5ad81..2dd3a1c3 100644 --- a/models/bank_account_payment_profile.go +++ b/models/bank_account_payment_profile.go @@ -1,183 +1,242 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // BankAccountPaymentProfile represents a BankAccountPaymentProfile struct. type BankAccountPaymentProfile struct { - // The Chargify-assigned ID of the stored bank account. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer - Id *int `json:"id,omitempty"` - // The first name of the bank account holder - FirstName *string `json:"first_name,omitempty"` - // The last name of the bank account holder - LastName *string `json:"last_name,omitempty"` - // The Chargify-assigned id for the customer record to which the bank account belongs - CustomerId *int `json:"customer_id,omitempty"` - // The vault that stores the payment profile with the provided vault_token. - CurrentVault *BankAccountVault `json:"current_vault,omitempty"` - // The “token” provided by your vault storage for an already stored payment profile - VaultToken *string `json:"vault_token,omitempty"` - // The current billing street address for the bank account - BillingAddress Optional[string] `json:"billing_address"` - // The current billing address city for the bank account - BillingCity Optional[string] `json:"billing_city"` - // The current billing address state for the bank account - BillingState Optional[string] `json:"billing_state"` - // The current billing address zip code for the bank account - BillingZip Optional[string] `json:"billing_zip"` - // The current billing address country for the bank account - BillingCountry Optional[string] `json:"billing_country"` - // (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. - CustomerVaultToken Optional[string] `json:"customer_vault_token"` - // The current billing street address, second line, for the bank account - BillingAddress2 Optional[string] `json:"billing_address_2"` - // The bank where the account resides - BankName *string `json:"bank_name,omitempty"` - // A string representation of the stored bank routing number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’). payment_type will be bank_account - MaskedBankRoutingNumber string `json:"masked_bank_routing_number"` - // A string representation of the stored bank account number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’) - MaskedBankAccountNumber string `json:"masked_bank_account_number"` - // Defaults to checking - BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` - // Defaults to personal - BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` - PaymentType *PaymentType `json:"payment_type,omitempty"` - // denotes whether a bank account has been verified by providing the amounts of two small deposits made into the account - Verified *bool `json:"verified,omitempty"` - SiteGatewaySettingId Optional[int] `json:"site_gateway_setting_id"` - GatewayHandle Optional[string] `json:"gateway_handle"` + // The Chargify-assigned ID of the stored bank account. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer + Id *int `json:"id,omitempty"` + // The first name of the bank account holder + FirstName *string `json:"first_name,omitempty"` + // The last name of the bank account holder + LastName *string `json:"last_name,omitempty"` + // The Chargify-assigned id for the customer record to which the bank account belongs + CustomerId *int `json:"customer_id,omitempty"` + // The vault that stores the payment profile with the provided vault_token. + CurrentVault *BankAccountVault `json:"current_vault,omitempty"` + // The “token” provided by your vault storage for an already stored payment profile + VaultToken *string `json:"vault_token,omitempty"` + // The current billing street address for the bank account + BillingAddress Optional[string] `json:"billing_address"` + // The current billing address city for the bank account + BillingCity Optional[string] `json:"billing_city"` + // The current billing address state for the bank account + BillingState Optional[string] `json:"billing_state"` + // The current billing address zip code for the bank account + BillingZip Optional[string] `json:"billing_zip"` + // The current billing address country for the bank account + BillingCountry Optional[string] `json:"billing_country"` + // (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. + CustomerVaultToken Optional[string] `json:"customer_vault_token"` + // The current billing street address, second line, for the bank account + BillingAddress2 Optional[string] `json:"billing_address_2"` + // The bank where the account resides + BankName *string `json:"bank_name,omitempty"` + // A string representation of the stored bank routing number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’). payment_type will be bank_account + MaskedBankRoutingNumber string `json:"masked_bank_routing_number"` + // A string representation of the stored bank account number with all but the last 4 digits marked with X’s (i.e. ‘XXXXXXX1111’) + MaskedBankAccountNumber string `json:"masked_bank_account_number"` + // Defaults to checking + BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` + // Defaults to personal + BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` + PaymentType *PaymentType `json:"payment_type,omitempty"` + // denotes whether a bank account has been verified by providing the amounts of two small deposits made into the account + Verified *bool `json:"verified,omitempty"` + SiteGatewaySettingId Optional[int] `json:"site_gateway_setting_id"` + GatewayHandle Optional[string] `json:"gateway_handle"` } -// MarshalJSON implements the json.Marshaler interface for BankAccountPaymentProfile. +// MarshalJSON implements the json.Marshaler interface for BankAccountPaymentProfile. // It customizes the JSON marshaling process for BankAccountPaymentProfile objects. func (b *BankAccountPaymentProfile) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BankAccountPaymentProfile object to a map representation for JSON marshaling. func (b *BankAccountPaymentProfile) toMap() map[string]any { - structMap := make(map[string]any) - if b.Id != nil { - structMap["id"] = b.Id - } - if b.FirstName != nil { - structMap["first_name"] = b.FirstName - } - if b.LastName != nil { - structMap["last_name"] = b.LastName - } - if b.CustomerId != nil { - structMap["customer_id"] = b.CustomerId - } - if b.CurrentVault != nil { - structMap["current_vault"] = b.CurrentVault - } - if b.VaultToken != nil { - structMap["vault_token"] = b.VaultToken - } - if b.BillingAddress.IsValueSet() { - structMap["billing_address"] = b.BillingAddress.Value() - } - if b.BillingCity.IsValueSet() { - structMap["billing_city"] = b.BillingCity.Value() - } - if b.BillingState.IsValueSet() { - structMap["billing_state"] = b.BillingState.Value() - } - if b.BillingZip.IsValueSet() { - structMap["billing_zip"] = b.BillingZip.Value() - } - if b.BillingCountry.IsValueSet() { - structMap["billing_country"] = b.BillingCountry.Value() - } - if b.CustomerVaultToken.IsValueSet() { - structMap["customer_vault_token"] = b.CustomerVaultToken.Value() - } - if b.BillingAddress2.IsValueSet() { - structMap["billing_address_2"] = b.BillingAddress2.Value() - } - if b.BankName != nil { - structMap["bank_name"] = b.BankName - } - structMap["masked_bank_routing_number"] = b.MaskedBankRoutingNumber - structMap["masked_bank_account_number"] = b.MaskedBankAccountNumber - if b.BankAccountType != nil { - structMap["bank_account_type"] = b.BankAccountType - } - if b.BankAccountHolderType != nil { - structMap["bank_account_holder_type"] = b.BankAccountHolderType - } - if b.PaymentType != nil { - structMap["payment_type"] = b.PaymentType - } - if b.Verified != nil { - structMap["verified"] = b.Verified - } - if b.SiteGatewaySettingId.IsValueSet() { - structMap["site_gateway_setting_id"] = b.SiteGatewaySettingId.Value() - } - if b.GatewayHandle.IsValueSet() { - structMap["gateway_handle"] = b.GatewayHandle.Value() - } - return structMap + structMap := make(map[string]any) + if b.Id != nil { + structMap["id"] = b.Id + } + if b.FirstName != nil { + structMap["first_name"] = b.FirstName + } + if b.LastName != nil { + structMap["last_name"] = b.LastName + } + if b.CustomerId != nil { + structMap["customer_id"] = b.CustomerId + } + if b.CurrentVault != nil { + structMap["current_vault"] = b.CurrentVault + } + if b.VaultToken != nil { + structMap["vault_token"] = b.VaultToken + } + if b.BillingAddress.IsValueSet() { + if b.BillingAddress.Value() != nil { + structMap["billing_address"] = b.BillingAddress.Value() + } else { + structMap["billing_address"] = nil + } + } + if b.BillingCity.IsValueSet() { + if b.BillingCity.Value() != nil { + structMap["billing_city"] = b.BillingCity.Value() + } else { + structMap["billing_city"] = nil + } + } + if b.BillingState.IsValueSet() { + if b.BillingState.Value() != nil { + structMap["billing_state"] = b.BillingState.Value() + } else { + structMap["billing_state"] = nil + } + } + if b.BillingZip.IsValueSet() { + if b.BillingZip.Value() != nil { + structMap["billing_zip"] = b.BillingZip.Value() + } else { + structMap["billing_zip"] = nil + } + } + if b.BillingCountry.IsValueSet() { + if b.BillingCountry.Value() != nil { + structMap["billing_country"] = b.BillingCountry.Value() + } else { + structMap["billing_country"] = nil + } + } + if b.CustomerVaultToken.IsValueSet() { + if b.CustomerVaultToken.Value() != nil { + structMap["customer_vault_token"] = b.CustomerVaultToken.Value() + } else { + structMap["customer_vault_token"] = nil + } + } + if b.BillingAddress2.IsValueSet() { + if b.BillingAddress2.Value() != nil { + structMap["billing_address_2"] = b.BillingAddress2.Value() + } else { + structMap["billing_address_2"] = nil + } + } + if b.BankName != nil { + structMap["bank_name"] = b.BankName + } + structMap["masked_bank_routing_number"] = b.MaskedBankRoutingNumber + structMap["masked_bank_account_number"] = b.MaskedBankAccountNumber + if b.BankAccountType != nil { + structMap["bank_account_type"] = b.BankAccountType + } + if b.BankAccountHolderType != nil { + structMap["bank_account_holder_type"] = b.BankAccountHolderType + } + if b.PaymentType != nil { + structMap["payment_type"] = b.PaymentType + } + if b.Verified != nil { + structMap["verified"] = b.Verified + } + if b.SiteGatewaySettingId.IsValueSet() { + if b.SiteGatewaySettingId.Value() != nil { + structMap["site_gateway_setting_id"] = b.SiteGatewaySettingId.Value() + } else { + structMap["site_gateway_setting_id"] = nil + } + } + if b.GatewayHandle.IsValueSet() { + if b.GatewayHandle.Value() != nil { + structMap["gateway_handle"] = b.GatewayHandle.Value() + } else { + structMap["gateway_handle"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BankAccountPaymentProfile. +// UnmarshalJSON implements the json.Unmarshaler interface for BankAccountPaymentProfile. // It customizes the JSON unmarshaling process for BankAccountPaymentProfile objects. func (b *BankAccountPaymentProfile) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - CurrentVault *BankAccountVault `json:"current_vault,omitempty"` - VaultToken *string `json:"vault_token,omitempty"` - BillingAddress Optional[string] `json:"billing_address"` - BillingCity Optional[string] `json:"billing_city"` - BillingState Optional[string] `json:"billing_state"` - BillingZip Optional[string] `json:"billing_zip"` - BillingCountry Optional[string] `json:"billing_country"` - CustomerVaultToken Optional[string] `json:"customer_vault_token"` - BillingAddress2 Optional[string] `json:"billing_address_2"` - BankName *string `json:"bank_name,omitempty"` - MaskedBankRoutingNumber string `json:"masked_bank_routing_number"` - MaskedBankAccountNumber string `json:"masked_bank_account_number"` - BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` - BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` - PaymentType *PaymentType `json:"payment_type,omitempty"` - Verified *bool `json:"verified,omitempty"` - SiteGatewaySettingId Optional[int] `json:"site_gateway_setting_id"` - GatewayHandle Optional[string] `json:"gateway_handle"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.Id = temp.Id - b.FirstName = temp.FirstName - b.LastName = temp.LastName - b.CustomerId = temp.CustomerId - b.CurrentVault = temp.CurrentVault - b.VaultToken = temp.VaultToken - b.BillingAddress = temp.BillingAddress - b.BillingCity = temp.BillingCity - b.BillingState = temp.BillingState - b.BillingZip = temp.BillingZip - b.BillingCountry = temp.BillingCountry - b.CustomerVaultToken = temp.CustomerVaultToken - b.BillingAddress2 = temp.BillingAddress2 - b.BankName = temp.BankName - b.MaskedBankRoutingNumber = temp.MaskedBankRoutingNumber - b.MaskedBankAccountNumber = temp.MaskedBankAccountNumber - b.BankAccountType = temp.BankAccountType - b.BankAccountHolderType = temp.BankAccountHolderType - b.PaymentType = temp.PaymentType - b.Verified = temp.Verified - b.SiteGatewaySettingId = temp.SiteGatewaySettingId - b.GatewayHandle = temp.GatewayHandle - return nil + var temp bankAccountPaymentProfile + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + b.Id = temp.Id + b.FirstName = temp.FirstName + b.LastName = temp.LastName + b.CustomerId = temp.CustomerId + b.CurrentVault = temp.CurrentVault + b.VaultToken = temp.VaultToken + b.BillingAddress = temp.BillingAddress + b.BillingCity = temp.BillingCity + b.BillingState = temp.BillingState + b.BillingZip = temp.BillingZip + b.BillingCountry = temp.BillingCountry + b.CustomerVaultToken = temp.CustomerVaultToken + b.BillingAddress2 = temp.BillingAddress2 + b.BankName = temp.BankName + b.MaskedBankRoutingNumber = *temp.MaskedBankRoutingNumber + b.MaskedBankAccountNumber = *temp.MaskedBankAccountNumber + b.BankAccountType = temp.BankAccountType + b.BankAccountHolderType = temp.BankAccountHolderType + b.PaymentType = temp.PaymentType + b.Verified = temp.Verified + b.SiteGatewaySettingId = temp.SiteGatewaySettingId + b.GatewayHandle = temp.GatewayHandle + return nil +} + +// TODO +type bankAccountPaymentProfile struct { + Id *int `json:"id,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + CurrentVault *BankAccountVault `json:"current_vault,omitempty"` + VaultToken *string `json:"vault_token,omitempty"` + BillingAddress Optional[string] `json:"billing_address"` + BillingCity Optional[string] `json:"billing_city"` + BillingState Optional[string] `json:"billing_state"` + BillingZip Optional[string] `json:"billing_zip"` + BillingCountry Optional[string] `json:"billing_country"` + CustomerVaultToken Optional[string] `json:"customer_vault_token"` + BillingAddress2 Optional[string] `json:"billing_address_2"` + BankName *string `json:"bank_name,omitempty"` + MaskedBankRoutingNumber *string `json:"masked_bank_routing_number"` + MaskedBankAccountNumber *string `json:"masked_bank_account_number"` + BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` + BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` + PaymentType *PaymentType `json:"payment_type,omitempty"` + Verified *bool `json:"verified,omitempty"` + SiteGatewaySettingId Optional[int] `json:"site_gateway_setting_id"` + GatewayHandle Optional[string] `json:"gateway_handle"` +} + +func (b *bankAccountPaymentProfile) validate() error { + var errs []string + if b.MaskedBankRoutingNumber == nil { + errs = append(errs, "required field `masked_bank_routing_number` is missing for type `Bank Account Payment Profile`") + } + if b.MaskedBankAccountNumber == nil { + errs = append(errs, "required field `masked_bank_account_number` is missing for type `Bank Account Payment Profile`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/bank_account_response.go b/models/bank_account_response.go index 2b433442..4ac742e5 100644 --- a/models/bank_account_response.go +++ b/models/bank_account_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // BankAccountResponse represents a BankAccountResponse struct. type BankAccountResponse struct { - PaymentProfile BankAccountPaymentProfile `json:"payment_profile"` + PaymentProfile BankAccountPaymentProfile `json:"payment_profile"` } -// MarshalJSON implements the json.Marshaler interface for BankAccountResponse. +// MarshalJSON implements the json.Marshaler interface for BankAccountResponse. // It customizes the JSON marshaling process for BankAccountResponse objects. func (b *BankAccountResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BankAccountResponse object to a map representation for JSON marshaling. func (b *BankAccountResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["payment_profile"] = b.PaymentProfile.toMap() - return structMap + structMap := make(map[string]any) + structMap["payment_profile"] = b.PaymentProfile.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BankAccountResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for BankAccountResponse. // It customizes the JSON unmarshaling process for BankAccountResponse objects. func (b *BankAccountResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - PaymentProfile BankAccountPaymentProfile `json:"payment_profile"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.PaymentProfile = temp.PaymentProfile - return nil + var temp bankAccountResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + b.PaymentProfile = *temp.PaymentProfile + return nil +} + +// TODO +type bankAccountResponse struct { + PaymentProfile *BankAccountPaymentProfile `json:"payment_profile"` +} + +func (b *bankAccountResponse) validate() error { + var errs []string + if b.PaymentProfile == nil { + errs = append(errs, "required field `payment_profile` is missing for type `Bank Account Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/bank_account_verification.go b/models/bank_account_verification.go index d3516ecb..ff93296c 100644 --- a/models/bank_account_verification.go +++ b/models/bank_account_verification.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // BankAccountVerification represents a BankAccountVerification struct. type BankAccountVerification struct { - Deposit1InCents *int64 `json:"deposit_1_in_cents,omitempty"` - Deposit2InCents *int64 `json:"deposit_2_in_cents,omitempty"` + Deposit1InCents *int64 `json:"deposit_1_in_cents,omitempty"` + Deposit2InCents *int64 `json:"deposit_2_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BankAccountVerification. +// MarshalJSON implements the json.Marshaler interface for BankAccountVerification. // It customizes the JSON marshaling process for BankAccountVerification objects. func (b *BankAccountVerification) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BankAccountVerification object to a map representation for JSON marshaling. func (b *BankAccountVerification) toMap() map[string]any { - structMap := make(map[string]any) - if b.Deposit1InCents != nil { - structMap["deposit_1_in_cents"] = b.Deposit1InCents - } - if b.Deposit2InCents != nil { - structMap["deposit_2_in_cents"] = b.Deposit2InCents - } - return structMap + structMap := make(map[string]any) + if b.Deposit1InCents != nil { + structMap["deposit_1_in_cents"] = b.Deposit1InCents + } + if b.Deposit2InCents != nil { + structMap["deposit_2_in_cents"] = b.Deposit2InCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BankAccountVerification. +// UnmarshalJSON implements the json.Unmarshaler interface for BankAccountVerification. // It customizes the JSON unmarshaling process for BankAccountVerification objects. func (b *BankAccountVerification) UnmarshalJSON(input []byte) error { - temp := &struct { - Deposit1InCents *int64 `json:"deposit_1_in_cents,omitempty"` - Deposit2InCents *int64 `json:"deposit_2_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.Deposit1InCents = temp.Deposit1InCents - b.Deposit2InCents = temp.Deposit2InCents - return nil + var temp bankAccountVerification + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.Deposit1InCents = temp.Deposit1InCents + b.Deposit2InCents = temp.Deposit2InCents + return nil +} + +// TODO +type bankAccountVerification struct { + Deposit1InCents *int64 `json:"deposit_1_in_cents,omitempty"` + Deposit2InCents *int64 `json:"deposit_2_in_cents,omitempty"` } diff --git a/models/bank_account_verification_request.go b/models/bank_account_verification_request.go index c0aef48b..391dba43 100644 --- a/models/bank_account_verification_request.go +++ b/models/bank_account_verification_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // BankAccountVerificationRequest represents a BankAccountVerificationRequest struct. type BankAccountVerificationRequest struct { - BankAccountVerification BankAccountVerification `json:"bank_account_verification"` + BankAccountVerification BankAccountVerification `json:"bank_account_verification"` } -// MarshalJSON implements the json.Marshaler interface for BankAccountVerificationRequest. +// MarshalJSON implements the json.Marshaler interface for BankAccountVerificationRequest. // It customizes the JSON marshaling process for BankAccountVerificationRequest objects. func (b *BankAccountVerificationRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BankAccountVerificationRequest object to a map representation for JSON marshaling. func (b *BankAccountVerificationRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["bank_account_verification"] = b.BankAccountVerification.toMap() - return structMap + structMap := make(map[string]any) + structMap["bank_account_verification"] = b.BankAccountVerification.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BankAccountVerificationRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for BankAccountVerificationRequest. // It customizes the JSON unmarshaling process for BankAccountVerificationRequest objects. func (b *BankAccountVerificationRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - BankAccountVerification BankAccountVerification `json:"bank_account_verification"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.BankAccountVerification = temp.BankAccountVerification - return nil + var temp bankAccountVerificationRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + b.BankAccountVerification = *temp.BankAccountVerification + return nil +} + +// TODO +type bankAccountVerificationRequest struct { + BankAccountVerification *BankAccountVerification `json:"bank_account_verification"` +} + +func (b *bankAccountVerificationRequest) validate() error { + var errs []string + if b.BankAccountVerification == nil { + errs = append(errs, "required field `bank_account_verification` is missing for type `Bank Account Verification Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/base_refund_error.go b/models/base_refund_error.go index bdafff7b..200d7214 100644 --- a/models/base_refund_error.go +++ b/models/base_refund_error.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // BaseRefundError represents a BaseRefundError struct. type BaseRefundError struct { - Base []interface{} `json:"base,omitempty"` + Base []interface{} `json:"base,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BaseRefundError. +// MarshalJSON implements the json.Marshaler interface for BaseRefundError. // It customizes the JSON marshaling process for BaseRefundError objects. func (b *BaseRefundError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BaseRefundError object to a map representation for JSON marshaling. func (b *BaseRefundError) toMap() map[string]any { - structMap := make(map[string]any) - if b.Base != nil { - structMap["base"] = b.Base - } - return structMap + structMap := make(map[string]any) + if b.Base != nil { + structMap["base"] = b.Base + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BaseRefundError. +// UnmarshalJSON implements the json.Unmarshaler interface for BaseRefundError. // It customizes the JSON unmarshaling process for BaseRefundError objects. func (b *BaseRefundError) UnmarshalJSON(input []byte) error { - temp := &struct { - Base []interface{} `json:"base,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.Base = temp.Base - return nil + var temp baseRefundError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.Base = temp.Base + return nil +} + +// TODO +type baseRefundError struct { + Base []interface{} `json:"base,omitempty"` } diff --git a/models/base_string_error.go b/models/base_string_error.go index f7c49ad3..504a52d0 100644 --- a/models/base_string_error.go +++ b/models/base_string_error.go @@ -1,43 +1,45 @@ package models import ( - "encoding/json" + "encoding/json" ) -// BaseStringError represents a BaseStringError struct. +// BaseStringError represents a BaseStringError struct. // The error is base if it is not directly associated with a single attribute. type BaseStringError struct { - Base []string `json:"base,omitempty"` + Base []string `json:"base,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BaseStringError. +// MarshalJSON implements the json.Marshaler interface for BaseStringError. // It customizes the JSON marshaling process for BaseStringError objects. func (b *BaseStringError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BaseStringError object to a map representation for JSON marshaling. func (b *BaseStringError) toMap() map[string]any { - structMap := make(map[string]any) - if b.Base != nil { - structMap["base"] = b.Base - } - return structMap + structMap := make(map[string]any) + if b.Base != nil { + structMap["base"] = b.Base + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BaseStringError. +// UnmarshalJSON implements the json.Unmarshaler interface for BaseStringError. // It customizes the JSON unmarshaling process for BaseStringError objects. func (b *BaseStringError) UnmarshalJSON(input []byte) error { - temp := &struct { - Base []string `json:"base,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.Base = temp.Base - return nil + var temp baseStringError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.Base = temp.Base + return nil +} + +// TODO +type baseStringError struct { + Base []string `json:"base,omitempty"` } diff --git a/models/batch_job.go b/models/batch_job.go index 122e80c0..cc90530e 100644 --- a/models/batch_job.go +++ b/models/batch_job.go @@ -1,92 +1,106 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // BatchJob represents a BatchJob struct. type BatchJob struct { - Id *int `json:"id,omitempty"` - FinishedAt Optional[time.Time] `json:"finished_at"` - RowCount Optional[int] `json:"row_count"` - CreatedAt Optional[time.Time] `json:"created_at"` - Completed *string `json:"completed,omitempty"` + Id *int `json:"id,omitempty"` + FinishedAt Optional[time.Time] `json:"finished_at"` + RowCount Optional[int] `json:"row_count"` + CreatedAt Optional[time.Time] `json:"created_at"` + Completed *string `json:"completed,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BatchJob. +// MarshalJSON implements the json.Marshaler interface for BatchJob. // It customizes the JSON marshaling process for BatchJob objects. func (b *BatchJob) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BatchJob object to a map representation for JSON marshaling. func (b *BatchJob) toMap() map[string]any { - structMap := make(map[string]any) - if b.Id != nil { - structMap["id"] = b.Id - } - if b.FinishedAt.IsValueSet() { - var FinishedAtVal *string = nil - if b.FinishedAt.Value() != nil { - val := b.FinishedAt.Value().Format(time.RFC3339) - FinishedAtVal = &val - } - structMap["finished_at"] = FinishedAtVal - } - if b.RowCount.IsValueSet() { - structMap["row_count"] = b.RowCount.Value() - } - if b.CreatedAt.IsValueSet() { - var CreatedAtVal *string = nil - if b.CreatedAt.Value() != nil { - val := b.CreatedAt.Value().Format(time.RFC3339) - CreatedAtVal = &val - } - structMap["created_at"] = CreatedAtVal - } - if b.Completed != nil { - structMap["completed"] = b.Completed - } - return structMap + structMap := make(map[string]any) + if b.Id != nil { + structMap["id"] = b.Id + } + if b.FinishedAt.IsValueSet() { + var FinishedAtVal *string = nil + if b.FinishedAt.Value() != nil { + val := b.FinishedAt.Value().Format(time.RFC3339) + FinishedAtVal = &val + } + if b.FinishedAt.Value() != nil { + structMap["finished_at"] = FinishedAtVal + } else { + structMap["finished_at"] = nil + } + } + if b.RowCount.IsValueSet() { + if b.RowCount.Value() != nil { + structMap["row_count"] = b.RowCount.Value() + } else { + structMap["row_count"] = nil + } + } + if b.CreatedAt.IsValueSet() { + var CreatedAtVal *string = nil + if b.CreatedAt.Value() != nil { + val := b.CreatedAt.Value().Format(time.RFC3339) + CreatedAtVal = &val + } + if b.CreatedAt.Value() != nil { + structMap["created_at"] = CreatedAtVal + } else { + structMap["created_at"] = nil + } + } + if b.Completed != nil { + structMap["completed"] = b.Completed + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BatchJob. +// UnmarshalJSON implements the json.Unmarshaler interface for BatchJob. // It customizes the JSON unmarshaling process for BatchJob objects. func (b *BatchJob) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - FinishedAt Optional[string] `json:"finished_at"` - RowCount Optional[int] `json:"row_count"` - CreatedAt Optional[string] `json:"created_at"` - Completed *string `json:"completed,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.Id = temp.Id - b.FinishedAt.ShouldSetValue(temp.FinishedAt.IsValueSet()) - if temp.FinishedAt.Value() != nil { - FinishedAtVal, err := time.Parse(time.RFC3339, (*temp.FinishedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse finished_at as % s format.", time.RFC3339) - } - b.FinishedAt.SetValue(&FinishedAtVal) - } - b.RowCount = temp.RowCount - b.CreatedAt.ShouldSetValue(temp.CreatedAt.IsValueSet()) - if temp.CreatedAt.Value() != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, (*temp.CreatedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - b.CreatedAt.SetValue(&CreatedAtVal) - } - b.Completed = temp.Completed - return nil + var temp batchJob + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.Id = temp.Id + b.FinishedAt.ShouldSetValue(temp.FinishedAt.IsValueSet()) + if temp.FinishedAt.Value() != nil { + FinishedAtVal, err := time.Parse(time.RFC3339, (*temp.FinishedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse finished_at as % s format.", time.RFC3339) + } + b.FinishedAt.SetValue(&FinishedAtVal) + } + b.RowCount = temp.RowCount + b.CreatedAt.ShouldSetValue(temp.CreatedAt.IsValueSet()) + if temp.CreatedAt.Value() != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, (*temp.CreatedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + b.CreatedAt.SetValue(&CreatedAtVal) + } + b.Completed = temp.Completed + return nil +} + +// TODO +type batchJob struct { + Id *int `json:"id,omitempty"` + FinishedAt Optional[string] `json:"finished_at"` + RowCount Optional[int] `json:"row_count"` + CreatedAt Optional[string] `json:"created_at"` + Completed *string `json:"completed,omitempty"` } diff --git a/models/batch_job_response.go b/models/batch_job_response.go index 5ef8a14c..6410e095 100644 --- a/models/batch_job_response.go +++ b/models/batch_job_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // BatchJobResponse represents a BatchJobResponse struct. type BatchJobResponse struct { - Batchjob BatchJob `json:"batchjob"` + Batchjob BatchJob `json:"batchjob"` } -// MarshalJSON implements the json.Marshaler interface for BatchJobResponse. +// MarshalJSON implements the json.Marshaler interface for BatchJobResponse. // It customizes the JSON marshaling process for BatchJobResponse objects. func (b *BatchJobResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BatchJobResponse object to a map representation for JSON marshaling. func (b *BatchJobResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["batchjob"] = b.Batchjob.toMap() - return structMap + structMap := make(map[string]any) + structMap["batchjob"] = b.Batchjob.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BatchJobResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for BatchJobResponse. // It customizes the JSON unmarshaling process for BatchJobResponse objects. func (b *BatchJobResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Batchjob BatchJob `json:"batchjob"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.Batchjob = temp.Batchjob - return nil + var temp batchJobResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + b.Batchjob = *temp.Batchjob + return nil +} + +// TODO +type batchJobResponse struct { + Batchjob *BatchJob `json:"batchjob"` +} + +func (b *batchJobResponse) validate() error { + var errs []string + if b.Batchjob == nil { + errs = append(errs, "required field `batchjob` is missing for type `Batch Job Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/billing_address.go b/models/billing_address.go index 1a7b7f8b..e57cf57d 100644 --- a/models/billing_address.go +++ b/models/billing_address.go @@ -1,72 +1,98 @@ package models import ( - "encoding/json" + "encoding/json" ) // BillingAddress represents a BillingAddress struct. type BillingAddress struct { - Street Optional[string] `json:"street"` - Line2 Optional[string] `json:"line2"` - City Optional[string] `json:"city"` - State Optional[string] `json:"state"` - Zip Optional[string] `json:"zip"` - Country Optional[string] `json:"country"` + Street Optional[string] `json:"street"` + Line2 Optional[string] `json:"line2"` + City Optional[string] `json:"city"` + State Optional[string] `json:"state"` + Zip Optional[string] `json:"zip"` + Country Optional[string] `json:"country"` } -// MarshalJSON implements the json.Marshaler interface for BillingAddress. +// MarshalJSON implements the json.Marshaler interface for BillingAddress. // It customizes the JSON marshaling process for BillingAddress objects. func (b *BillingAddress) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BillingAddress object to a map representation for JSON marshaling. func (b *BillingAddress) toMap() map[string]any { - structMap := make(map[string]any) - if b.Street.IsValueSet() { - structMap["street"] = b.Street.Value() - } - if b.Line2.IsValueSet() { - structMap["line2"] = b.Line2.Value() - } - if b.City.IsValueSet() { - structMap["city"] = b.City.Value() - } - if b.State.IsValueSet() { - structMap["state"] = b.State.Value() - } - if b.Zip.IsValueSet() { - structMap["zip"] = b.Zip.Value() - } - if b.Country.IsValueSet() { - structMap["country"] = b.Country.Value() - } - return structMap + structMap := make(map[string]any) + if b.Street.IsValueSet() { + if b.Street.Value() != nil { + structMap["street"] = b.Street.Value() + } else { + structMap["street"] = nil + } + } + if b.Line2.IsValueSet() { + if b.Line2.Value() != nil { + structMap["line2"] = b.Line2.Value() + } else { + structMap["line2"] = nil + } + } + if b.City.IsValueSet() { + if b.City.Value() != nil { + structMap["city"] = b.City.Value() + } else { + structMap["city"] = nil + } + } + if b.State.IsValueSet() { + if b.State.Value() != nil { + structMap["state"] = b.State.Value() + } else { + structMap["state"] = nil + } + } + if b.Zip.IsValueSet() { + if b.Zip.Value() != nil { + structMap["zip"] = b.Zip.Value() + } else { + structMap["zip"] = nil + } + } + if b.Country.IsValueSet() { + if b.Country.Value() != nil { + structMap["country"] = b.Country.Value() + } else { + structMap["country"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BillingAddress. +// UnmarshalJSON implements the json.Unmarshaler interface for BillingAddress. // It customizes the JSON unmarshaling process for BillingAddress objects. func (b *BillingAddress) UnmarshalJSON(input []byte) error { - temp := &struct { - Street Optional[string] `json:"street"` - Line2 Optional[string] `json:"line2"` - City Optional[string] `json:"city"` - State Optional[string] `json:"state"` - Zip Optional[string] `json:"zip"` - Country Optional[string] `json:"country"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.Street = temp.Street - b.Line2 = temp.Line2 - b.City = temp.City - b.State = temp.State - b.Zip = temp.Zip - b.Country = temp.Country - return nil + var temp billingAddress + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.Street = temp.Street + b.Line2 = temp.Line2 + b.City = temp.City + b.State = temp.State + b.Zip = temp.Zip + b.Country = temp.Country + return nil +} + +// TODO +type billingAddress struct { + Street Optional[string] `json:"street"` + Line2 Optional[string] `json:"line2"` + City Optional[string] `json:"city"` + State Optional[string] `json:"state"` + Zip Optional[string] `json:"zip"` + Country Optional[string] `json:"country"` } diff --git a/models/billing_manifest.go b/models/billing_manifest.go index 975adac6..52bca0ce 100644 --- a/models/billing_manifest.go +++ b/models/billing_manifest.go @@ -1,104 +1,106 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // BillingManifest represents a BillingManifest struct. type BillingManifest struct { - LineItems []BillingManifestItem `json:"line_items,omitempty"` - TotalInCents *int64 `json:"total_in_cents,omitempty"` - TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` - TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` - SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` - StartDate *time.Time `json:"start_date,omitempty"` - EndDate *time.Time `json:"end_date,omitempty"` - PeriodType *string `json:"period_type,omitempty"` - ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` + LineItems []BillingManifestItem `json:"line_items,omitempty"` + TotalInCents *int64 `json:"total_in_cents,omitempty"` + TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` + TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` + SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` + StartDate *time.Time `json:"start_date,omitempty"` + EndDate *time.Time `json:"end_date,omitempty"` + PeriodType *string `json:"period_type,omitempty"` + ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BillingManifest. +// MarshalJSON implements the json.Marshaler interface for BillingManifest. // It customizes the JSON marshaling process for BillingManifest objects. func (b *BillingManifest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BillingManifest object to a map representation for JSON marshaling. func (b *BillingManifest) toMap() map[string]any { - structMap := make(map[string]any) - if b.LineItems != nil { - structMap["line_items"] = b.LineItems - } - if b.TotalInCents != nil { - structMap["total_in_cents"] = b.TotalInCents - } - if b.TotalDiscountInCents != nil { - structMap["total_discount_in_cents"] = b.TotalDiscountInCents - } - if b.TotalTaxInCents != nil { - structMap["total_tax_in_cents"] = b.TotalTaxInCents - } - if b.SubtotalInCents != nil { - structMap["subtotal_in_cents"] = b.SubtotalInCents - } - if b.StartDate != nil { - structMap["start_date"] = b.StartDate.Format(time.RFC3339) - } - if b.EndDate != nil { - structMap["end_date"] = b.EndDate.Format(time.RFC3339) - } - if b.PeriodType != nil { - structMap["period_type"] = b.PeriodType - } - if b.ExistingBalanceInCents != nil { - structMap["existing_balance_in_cents"] = b.ExistingBalanceInCents - } - return structMap + structMap := make(map[string]any) + if b.LineItems != nil { + structMap["line_items"] = b.LineItems + } + if b.TotalInCents != nil { + structMap["total_in_cents"] = b.TotalInCents + } + if b.TotalDiscountInCents != nil { + structMap["total_discount_in_cents"] = b.TotalDiscountInCents + } + if b.TotalTaxInCents != nil { + structMap["total_tax_in_cents"] = b.TotalTaxInCents + } + if b.SubtotalInCents != nil { + structMap["subtotal_in_cents"] = b.SubtotalInCents + } + if b.StartDate != nil { + structMap["start_date"] = b.StartDate.Format(time.RFC3339) + } + if b.EndDate != nil { + structMap["end_date"] = b.EndDate.Format(time.RFC3339) + } + if b.PeriodType != nil { + structMap["period_type"] = b.PeriodType + } + if b.ExistingBalanceInCents != nil { + structMap["existing_balance_in_cents"] = b.ExistingBalanceInCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BillingManifest. +// UnmarshalJSON implements the json.Unmarshaler interface for BillingManifest. // It customizes the JSON unmarshaling process for BillingManifest objects. func (b *BillingManifest) UnmarshalJSON(input []byte) error { - temp := &struct { - LineItems []BillingManifestItem `json:"line_items,omitempty"` - TotalInCents *int64 `json:"total_in_cents,omitempty"` - TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` - TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` - SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` - StartDate *string `json:"start_date,omitempty"` - EndDate *string `json:"end_date,omitempty"` - PeriodType *string `json:"period_type,omitempty"` - ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.LineItems = temp.LineItems - b.TotalInCents = temp.TotalInCents - b.TotalDiscountInCents = temp.TotalDiscountInCents - b.TotalTaxInCents = temp.TotalTaxInCents - b.SubtotalInCents = temp.SubtotalInCents - if temp.StartDate != nil { - StartDateVal, err := time.Parse(time.RFC3339, *temp.StartDate) - if err != nil { - log.Fatalf("Cannot Parse start_date as % s format.", time.RFC3339) - } - b.StartDate = &StartDateVal - } - if temp.EndDate != nil { - EndDateVal, err := time.Parse(time.RFC3339, *temp.EndDate) - if err != nil { - log.Fatalf("Cannot Parse end_date as % s format.", time.RFC3339) - } - b.EndDate = &EndDateVal - } - b.PeriodType = temp.PeriodType - b.ExistingBalanceInCents = temp.ExistingBalanceInCents - return nil + var temp billingManifest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.LineItems = temp.LineItems + b.TotalInCents = temp.TotalInCents + b.TotalDiscountInCents = temp.TotalDiscountInCents + b.TotalTaxInCents = temp.TotalTaxInCents + b.SubtotalInCents = temp.SubtotalInCents + if temp.StartDate != nil { + StartDateVal, err := time.Parse(time.RFC3339, *temp.StartDate) + if err != nil { + log.Fatalf("Cannot Parse start_date as % s format.", time.RFC3339) + } + b.StartDate = &StartDateVal + } + if temp.EndDate != nil { + EndDateVal, err := time.Parse(time.RFC3339, *temp.EndDate) + if err != nil { + log.Fatalf("Cannot Parse end_date as % s format.", time.RFC3339) + } + b.EndDate = &EndDateVal + } + b.PeriodType = temp.PeriodType + b.ExistingBalanceInCents = temp.ExistingBalanceInCents + return nil +} + +// TODO +type billingManifest struct { + LineItems []BillingManifestItem `json:"line_items,omitempty"` + TotalInCents *int64 `json:"total_in_cents,omitempty"` + TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` + TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` + SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` + StartDate *string `json:"start_date,omitempty"` + EndDate *string `json:"end_date,omitempty"` + PeriodType *string `json:"period_type,omitempty"` + ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` } diff --git a/models/billing_manifest_item.go b/models/billing_manifest_item.go index db3068ea..9baa13aa 100644 --- a/models/billing_manifest_item.go +++ b/models/billing_manifest_item.go @@ -1,122 +1,124 @@ package models import ( - "encoding/json" + "encoding/json" ) // BillingManifestItem represents a BillingManifestItem struct. type BillingManifestItem struct { - // A handle for the line item transaction type - TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` - // A handle for the billing manifest line item kind - Kind *BillingManifestLineItemKind `json:"kind,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - Memo *string `json:"memo,omitempty"` - DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` - TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - ComponentHandle *string `json:"component_handle,omitempty"` - ComponentName *string `json:"component_name,omitempty"` - ProductId *int `json:"product_id,omitempty"` - ProductHandle *string `json:"product_handle,omitempty"` - ProductName *string `json:"product_name,omitempty"` - PeriodRangeStart *string `json:"period_range_start,omitempty"` - PeriodRangeEnd *string `json:"period_range_end,omitempty"` + // A handle for the line item transaction type + TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` + // A handle for the billing manifest line item kind + Kind *BillingManifestLineItemKind `json:"kind,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + Memo *string `json:"memo,omitempty"` + DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` + TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + ComponentHandle *string `json:"component_handle,omitempty"` + ComponentName *string `json:"component_name,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductHandle *string `json:"product_handle,omitempty"` + ProductName *string `json:"product_name,omitempty"` + PeriodRangeStart *string `json:"period_range_start,omitempty"` + PeriodRangeEnd *string `json:"period_range_end,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BillingManifestItem. +// MarshalJSON implements the json.Marshaler interface for BillingManifestItem. // It customizes the JSON marshaling process for BillingManifestItem objects. func (b *BillingManifestItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BillingManifestItem object to a map representation for JSON marshaling. func (b *BillingManifestItem) toMap() map[string]any { - structMap := make(map[string]any) - if b.TransactionType != nil { - structMap["transaction_type"] = b.TransactionType - } - if b.Kind != nil { - structMap["kind"] = b.Kind - } - if b.AmountInCents != nil { - structMap["amount_in_cents"] = b.AmountInCents - } - if b.Memo != nil { - structMap["memo"] = b.Memo - } - if b.DiscountAmountInCents != nil { - structMap["discount_amount_in_cents"] = b.DiscountAmountInCents - } - if b.TaxableAmountInCents != nil { - structMap["taxable_amount_in_cents"] = b.TaxableAmountInCents - } - if b.ComponentId != nil { - structMap["component_id"] = b.ComponentId - } - if b.ComponentHandle != nil { - structMap["component_handle"] = b.ComponentHandle - } - if b.ComponentName != nil { - structMap["component_name"] = b.ComponentName - } - if b.ProductId != nil { - structMap["product_id"] = b.ProductId - } - if b.ProductHandle != nil { - structMap["product_handle"] = b.ProductHandle - } - if b.ProductName != nil { - structMap["product_name"] = b.ProductName - } - if b.PeriodRangeStart != nil { - structMap["period_range_start"] = b.PeriodRangeStart - } - if b.PeriodRangeEnd != nil { - structMap["period_range_end"] = b.PeriodRangeEnd - } - return structMap + structMap := make(map[string]any) + if b.TransactionType != nil { + structMap["transaction_type"] = b.TransactionType + } + if b.Kind != nil { + structMap["kind"] = b.Kind + } + if b.AmountInCents != nil { + structMap["amount_in_cents"] = b.AmountInCents + } + if b.Memo != nil { + structMap["memo"] = b.Memo + } + if b.DiscountAmountInCents != nil { + structMap["discount_amount_in_cents"] = b.DiscountAmountInCents + } + if b.TaxableAmountInCents != nil { + structMap["taxable_amount_in_cents"] = b.TaxableAmountInCents + } + if b.ComponentId != nil { + structMap["component_id"] = b.ComponentId + } + if b.ComponentHandle != nil { + structMap["component_handle"] = b.ComponentHandle + } + if b.ComponentName != nil { + structMap["component_name"] = b.ComponentName + } + if b.ProductId != nil { + structMap["product_id"] = b.ProductId + } + if b.ProductHandle != nil { + structMap["product_handle"] = b.ProductHandle + } + if b.ProductName != nil { + structMap["product_name"] = b.ProductName + } + if b.PeriodRangeStart != nil { + structMap["period_range_start"] = b.PeriodRangeStart + } + if b.PeriodRangeEnd != nil { + structMap["period_range_end"] = b.PeriodRangeEnd + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BillingManifestItem. +// UnmarshalJSON implements the json.Unmarshaler interface for BillingManifestItem. // It customizes the JSON unmarshaling process for BillingManifestItem objects. func (b *BillingManifestItem) UnmarshalJSON(input []byte) error { - temp := &struct { - TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` - Kind *BillingManifestLineItemKind `json:"kind,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - Memo *string `json:"memo,omitempty"` - DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` - TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - ComponentHandle *string `json:"component_handle,omitempty"` - ComponentName *string `json:"component_name,omitempty"` - ProductId *int `json:"product_id,omitempty"` - ProductHandle *string `json:"product_handle,omitempty"` - ProductName *string `json:"product_name,omitempty"` - PeriodRangeStart *string `json:"period_range_start,omitempty"` - PeriodRangeEnd *string `json:"period_range_end,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.TransactionType = temp.TransactionType - b.Kind = temp.Kind - b.AmountInCents = temp.AmountInCents - b.Memo = temp.Memo - b.DiscountAmountInCents = temp.DiscountAmountInCents - b.TaxableAmountInCents = temp.TaxableAmountInCents - b.ComponentId = temp.ComponentId - b.ComponentHandle = temp.ComponentHandle - b.ComponentName = temp.ComponentName - b.ProductId = temp.ProductId - b.ProductHandle = temp.ProductHandle - b.ProductName = temp.ProductName - b.PeriodRangeStart = temp.PeriodRangeStart - b.PeriodRangeEnd = temp.PeriodRangeEnd - return nil + var temp billingManifestItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.TransactionType = temp.TransactionType + b.Kind = temp.Kind + b.AmountInCents = temp.AmountInCents + b.Memo = temp.Memo + b.DiscountAmountInCents = temp.DiscountAmountInCents + b.TaxableAmountInCents = temp.TaxableAmountInCents + b.ComponentId = temp.ComponentId + b.ComponentHandle = temp.ComponentHandle + b.ComponentName = temp.ComponentName + b.ProductId = temp.ProductId + b.ProductHandle = temp.ProductHandle + b.ProductName = temp.ProductName + b.PeriodRangeStart = temp.PeriodRangeStart + b.PeriodRangeEnd = temp.PeriodRangeEnd + return nil +} + +// TODO +type billingManifestItem struct { + TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` + Kind *BillingManifestLineItemKind `json:"kind,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + Memo *string `json:"memo,omitempty"` + DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` + TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + ComponentHandle *string `json:"component_handle,omitempty"` + ComponentName *string `json:"component_name,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductHandle *string `json:"product_handle,omitempty"` + ProductName *string `json:"product_name,omitempty"` + PeriodRangeStart *string `json:"period_range_start,omitempty"` + PeriodRangeEnd *string `json:"period_range_end,omitempty"` } diff --git a/models/billing_schedule.go b/models/billing_schedule.go index 5842bec0..f87438c9 100644 --- a/models/billing_schedule.go +++ b/models/billing_schedule.go @@ -1,52 +1,54 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) -// BillingSchedule represents a BillingSchedule struct. +// BillingSchedule represents a BillingSchedule struct. // This attribute is particularly useful when you need to align billing events for different components on distinct schedules within a subscription. Please note this only works for site with Multifrequency enabled type BillingSchedule struct { - // The initial_billing_at attribute in Maxio allows you to specify a custom starting date for billing cycles associated with components that have their own billing frequency set. Only ISO8601 format is supported. - InitialBillingAt *time.Time `json:"initial_billing_at,omitempty"` + // The initial_billing_at attribute in Maxio allows you to specify a custom starting date for billing cycles associated with components that have their own billing frequency set. Only ISO8601 format is supported. + InitialBillingAt *time.Time `json:"initial_billing_at,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BillingSchedule. +// MarshalJSON implements the json.Marshaler interface for BillingSchedule. // It customizes the JSON marshaling process for BillingSchedule objects. func (b *BillingSchedule) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BillingSchedule object to a map representation for JSON marshaling. func (b *BillingSchedule) toMap() map[string]any { - structMap := make(map[string]any) - if b.InitialBillingAt != nil { - structMap["initial_billing_at"] = b.InitialBillingAt.Format(DEFAULT_DATE) - } - return structMap + structMap := make(map[string]any) + if b.InitialBillingAt != nil { + structMap["initial_billing_at"] = b.InitialBillingAt.Format(DEFAULT_DATE) + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BillingSchedule. +// UnmarshalJSON implements the json.Unmarshaler interface for BillingSchedule. // It customizes the JSON unmarshaling process for BillingSchedule objects. func (b *BillingSchedule) UnmarshalJSON(input []byte) error { - temp := &struct { - InitialBillingAt *string `json:"initial_billing_at,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - if temp.InitialBillingAt != nil { - InitialBillingAtVal, err := time.Parse(DEFAULT_DATE, *temp.InitialBillingAt) - if err != nil { - log.Fatalf("Cannot Parse initial_billing_at as % s format.", DEFAULT_DATE) - } - b.InitialBillingAt = &InitialBillingAtVal - } - return nil + var temp billingSchedule + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + if temp.InitialBillingAt != nil { + InitialBillingAtVal, err := time.Parse(DEFAULT_DATE, *temp.InitialBillingAt) + if err != nil { + log.Fatalf("Cannot Parse initial_billing_at as % s format.", DEFAULT_DATE) + } + b.InitialBillingAt = &InitialBillingAtVal + } + return nil +} + +// TODO +type billingSchedule struct { + InitialBillingAt *string `json:"initial_billing_at,omitempty"` } diff --git a/models/breakouts.go b/models/breakouts.go index 54962939..bc67e6be 100644 --- a/models/breakouts.go +++ b/models/breakouts.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // Breakouts represents a Breakouts struct. type Breakouts struct { - PlanAmountInCents *int64 `json:"plan_amount_in_cents,omitempty"` - PlanAmountFormatted *string `json:"plan_amount_formatted,omitempty"` - UsageAmountInCents *int64 `json:"usage_amount_in_cents,omitempty"` - UsageAmountFormatted *string `json:"usage_amount_formatted,omitempty"` + PlanAmountInCents *int64 `json:"plan_amount_in_cents,omitempty"` + PlanAmountFormatted *string `json:"plan_amount_formatted,omitempty"` + UsageAmountInCents *int64 `json:"usage_amount_in_cents,omitempty"` + UsageAmountFormatted *string `json:"usage_amount_formatted,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Breakouts. +// MarshalJSON implements the json.Marshaler interface for Breakouts. // It customizes the JSON marshaling process for Breakouts objects. func (b *Breakouts) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the Breakouts object to a map representation for JSON marshaling. func (b *Breakouts) toMap() map[string]any { - structMap := make(map[string]any) - if b.PlanAmountInCents != nil { - structMap["plan_amount_in_cents"] = b.PlanAmountInCents - } - if b.PlanAmountFormatted != nil { - structMap["plan_amount_formatted"] = b.PlanAmountFormatted - } - if b.UsageAmountInCents != nil { - structMap["usage_amount_in_cents"] = b.UsageAmountInCents - } - if b.UsageAmountFormatted != nil { - structMap["usage_amount_formatted"] = b.UsageAmountFormatted - } - return structMap + structMap := make(map[string]any) + if b.PlanAmountInCents != nil { + structMap["plan_amount_in_cents"] = b.PlanAmountInCents + } + if b.PlanAmountFormatted != nil { + structMap["plan_amount_formatted"] = b.PlanAmountFormatted + } + if b.UsageAmountInCents != nil { + structMap["usage_amount_in_cents"] = b.UsageAmountInCents + } + if b.UsageAmountFormatted != nil { + structMap["usage_amount_formatted"] = b.UsageAmountFormatted + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Breakouts. +// UnmarshalJSON implements the json.Unmarshaler interface for Breakouts. // It customizes the JSON unmarshaling process for Breakouts objects. func (b *Breakouts) UnmarshalJSON(input []byte) error { - temp := &struct { - PlanAmountInCents *int64 `json:"plan_amount_in_cents,omitempty"` - PlanAmountFormatted *string `json:"plan_amount_formatted,omitempty"` - UsageAmountInCents *int64 `json:"usage_amount_in_cents,omitempty"` - UsageAmountFormatted *string `json:"usage_amount_formatted,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.PlanAmountInCents = temp.PlanAmountInCents - b.PlanAmountFormatted = temp.PlanAmountFormatted - b.UsageAmountInCents = temp.UsageAmountInCents - b.UsageAmountFormatted = temp.UsageAmountFormatted - return nil + var temp breakouts + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.PlanAmountInCents = temp.PlanAmountInCents + b.PlanAmountFormatted = temp.PlanAmountFormatted + b.UsageAmountInCents = temp.UsageAmountInCents + b.UsageAmountFormatted = temp.UsageAmountFormatted + return nil +} + +// TODO +type breakouts struct { + PlanAmountInCents *int64 `json:"plan_amount_in_cents,omitempty"` + PlanAmountFormatted *string `json:"plan_amount_formatted,omitempty"` + UsageAmountInCents *int64 `json:"usage_amount_in_cents,omitempty"` + UsageAmountFormatted *string `json:"usage_amount_formatted,omitempty"` } diff --git a/models/bulk_components_price_point_assignment.go b/models/bulk_components_price_point_assignment.go index 5351f3e3..523e332c 100644 --- a/models/bulk_components_price_point_assignment.go +++ b/models/bulk_components_price_point_assignment.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // BulkComponentsPricePointAssignment represents a BulkComponentsPricePointAssignment struct. type BulkComponentsPricePointAssignment struct { - Components []ComponentPricePointAssignment `json:"components,omitempty"` + Components []ComponentPricePointAssignment `json:"components,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BulkComponentsPricePointAssignment. +// MarshalJSON implements the json.Marshaler interface for BulkComponentsPricePointAssignment. // It customizes the JSON marshaling process for BulkComponentsPricePointAssignment objects. func (b *BulkComponentsPricePointAssignment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BulkComponentsPricePointAssignment object to a map representation for JSON marshaling. func (b *BulkComponentsPricePointAssignment) toMap() map[string]any { - structMap := make(map[string]any) - if b.Components != nil { - structMap["components"] = b.Components - } - return structMap + structMap := make(map[string]any) + if b.Components != nil { + structMap["components"] = b.Components + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BulkComponentsPricePointAssignment. +// UnmarshalJSON implements the json.Unmarshaler interface for BulkComponentsPricePointAssignment. // It customizes the JSON unmarshaling process for BulkComponentsPricePointAssignment objects. func (b *BulkComponentsPricePointAssignment) UnmarshalJSON(input []byte) error { - temp := &struct { - Components []ComponentPricePointAssignment `json:"components,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.Components = temp.Components - return nil + var temp bulkComponentsPricePointAssignment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.Components = temp.Components + return nil +} + +// TODO +type bulkComponentsPricePointAssignment struct { + Components []ComponentPricePointAssignment `json:"components,omitempty"` } diff --git a/models/bulk_create_product_price_points_request.go b/models/bulk_create_product_price_points_request.go index 9fc42afc..bf2e2cb1 100644 --- a/models/bulk_create_product_price_points_request.go +++ b/models/bulk_create_product_price_points_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // BulkCreateProductPricePointsRequest represents a BulkCreateProductPricePointsRequest struct. type BulkCreateProductPricePointsRequest struct { - PricePoints []CreateProductPricePoint `json:"price_points"` + PricePoints []CreateProductPricePoint `json:"price_points"` } -// MarshalJSON implements the json.Marshaler interface for BulkCreateProductPricePointsRequest. +// MarshalJSON implements the json.Marshaler interface for BulkCreateProductPricePointsRequest. // It customizes the JSON marshaling process for BulkCreateProductPricePointsRequest objects. func (b *BulkCreateProductPricePointsRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BulkCreateProductPricePointsRequest object to a map representation for JSON marshaling. func (b *BulkCreateProductPricePointsRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["price_points"] = b.PricePoints - return structMap + structMap := make(map[string]any) + structMap["price_points"] = b.PricePoints + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BulkCreateProductPricePointsRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for BulkCreateProductPricePointsRequest. // It customizes the JSON unmarshaling process for BulkCreateProductPricePointsRequest objects. func (b *BulkCreateProductPricePointsRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoints []CreateProductPricePoint `json:"price_points"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.PricePoints = temp.PricePoints - return nil + var temp bulkCreateProductPricePointsRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + b.PricePoints = *temp.PricePoints + return nil +} + +// TODO +type bulkCreateProductPricePointsRequest struct { + PricePoints *[]CreateProductPricePoint `json:"price_points"` +} + +func (b *bulkCreateProductPricePointsRequest) validate() error { + var errs []string + if b.PricePoints == nil { + errs = append(errs, "required field `price_points` is missing for type `Bulk Create Product Price Points Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/bulk_create_product_price_points_response.go b/models/bulk_create_product_price_points_response.go index 176e1ec5..1d61a503 100644 --- a/models/bulk_create_product_price_points_response.go +++ b/models/bulk_create_product_price_points_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // BulkCreateProductPricePointsResponse represents a BulkCreateProductPricePointsResponse struct. type BulkCreateProductPricePointsResponse struct { - PricePoints []ProductPricePoint `json:"price_points,omitempty"` + PricePoints []ProductPricePoint `json:"price_points,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BulkCreateProductPricePointsResponse. +// MarshalJSON implements the json.Marshaler interface for BulkCreateProductPricePointsResponse. // It customizes the JSON marshaling process for BulkCreateProductPricePointsResponse objects. func (b *BulkCreateProductPricePointsResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BulkCreateProductPricePointsResponse object to a map representation for JSON marshaling. func (b *BulkCreateProductPricePointsResponse) toMap() map[string]any { - structMap := make(map[string]any) - if b.PricePoints != nil { - structMap["price_points"] = b.PricePoints - } - return structMap + structMap := make(map[string]any) + if b.PricePoints != nil { + structMap["price_points"] = b.PricePoints + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BulkCreateProductPricePointsResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for BulkCreateProductPricePointsResponse. // It customizes the JSON unmarshaling process for BulkCreateProductPricePointsResponse objects. func (b *BulkCreateProductPricePointsResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoints []ProductPricePoint `json:"price_points,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.PricePoints = temp.PricePoints - return nil + var temp bulkCreateProductPricePointsResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.PricePoints = temp.PricePoints + return nil +} + +// TODO +type bulkCreateProductPricePointsResponse struct { + PricePoints []ProductPricePoint `json:"price_points,omitempty"` } diff --git a/models/bulk_create_segments.go b/models/bulk_create_segments.go index 6d0b2838..139f9bca 100644 --- a/models/bulk_create_segments.go +++ b/models/bulk_create_segments.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // BulkCreateSegments represents a BulkCreateSegments struct. type BulkCreateSegments struct { - Segments []CreateSegment `json:"segments,omitempty"` + Segments []CreateSegment `json:"segments,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BulkCreateSegments. +// MarshalJSON implements the json.Marshaler interface for BulkCreateSegments. // It customizes the JSON marshaling process for BulkCreateSegments objects. func (b *BulkCreateSegments) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BulkCreateSegments object to a map representation for JSON marshaling. func (b *BulkCreateSegments) toMap() map[string]any { - structMap := make(map[string]any) - if b.Segments != nil { - structMap["segments"] = b.Segments - } - return structMap + structMap := make(map[string]any) + if b.Segments != nil { + structMap["segments"] = b.Segments + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BulkCreateSegments. +// UnmarshalJSON implements the json.Unmarshaler interface for BulkCreateSegments. // It customizes the JSON unmarshaling process for BulkCreateSegments objects. func (b *BulkCreateSegments) UnmarshalJSON(input []byte) error { - temp := &struct { - Segments []CreateSegment `json:"segments,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.Segments = temp.Segments - return nil + var temp bulkCreateSegments + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.Segments = temp.Segments + return nil +} + +// TODO +type bulkCreateSegments struct { + Segments []CreateSegment `json:"segments,omitempty"` } diff --git a/models/bulk_update_segments.go b/models/bulk_update_segments.go index a1d79731..578dc7d0 100644 --- a/models/bulk_update_segments.go +++ b/models/bulk_update_segments.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // BulkUpdateSegments represents a BulkUpdateSegments struct. type BulkUpdateSegments struct { - Segments []BulkUpdateSegmentsItem `json:"segments,omitempty"` + Segments []BulkUpdateSegmentsItem `json:"segments,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for BulkUpdateSegments. +// MarshalJSON implements the json.Marshaler interface for BulkUpdateSegments. // It customizes the JSON marshaling process for BulkUpdateSegments objects. func (b *BulkUpdateSegments) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BulkUpdateSegments object to a map representation for JSON marshaling. func (b *BulkUpdateSegments) toMap() map[string]any { - structMap := make(map[string]any) - if b.Segments != nil { - structMap["segments"] = b.Segments - } - return structMap + structMap := make(map[string]any) + if b.Segments != nil { + structMap["segments"] = b.Segments + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BulkUpdateSegments. +// UnmarshalJSON implements the json.Unmarshaler interface for BulkUpdateSegments. // It customizes the JSON unmarshaling process for BulkUpdateSegments objects. func (b *BulkUpdateSegments) UnmarshalJSON(input []byte) error { - temp := &struct { - Segments []BulkUpdateSegmentsItem `json:"segments,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.Segments = temp.Segments - return nil + var temp bulkUpdateSegments + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + b.Segments = temp.Segments + return nil +} + +// TODO +type bulkUpdateSegments struct { + Segments []BulkUpdateSegmentsItem `json:"segments,omitempty"` } diff --git a/models/bulk_update_segments_item.go b/models/bulk_update_segments_item.go index 643c8225..98626e45 100644 --- a/models/bulk_update_segments_item.go +++ b/models/bulk_update_segments_item.go @@ -1,50 +1,76 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // BulkUpdateSegmentsItem represents a BulkUpdateSegmentsItem struct. type BulkUpdateSegmentsItem struct { - // The ID of the segment you want to update. - Id int `json:"id"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme PricingScheme `json:"pricing_scheme"` - Prices []CreateOrUpdateSegmentPrice `json:"prices"` + // The ID of the segment you want to update. + Id int `json:"id"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme PricingScheme `json:"pricing_scheme"` + Prices []CreateOrUpdateSegmentPrice `json:"prices"` } -// MarshalJSON implements the json.Marshaler interface for BulkUpdateSegmentsItem. +// MarshalJSON implements the json.Marshaler interface for BulkUpdateSegmentsItem. // It customizes the JSON marshaling process for BulkUpdateSegmentsItem objects. func (b *BulkUpdateSegmentsItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(b.toMap()) + []byte, + error) { + return json.Marshal(b.toMap()) } // toMap converts the BulkUpdateSegmentsItem object to a map representation for JSON marshaling. func (b *BulkUpdateSegmentsItem) toMap() map[string]any { - structMap := make(map[string]any) - structMap["id"] = b.Id - structMap["pricing_scheme"] = b.PricingScheme - structMap["prices"] = b.Prices - return structMap + structMap := make(map[string]any) + structMap["id"] = b.Id + structMap["pricing_scheme"] = b.PricingScheme + structMap["prices"] = b.Prices + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for BulkUpdateSegmentsItem. +// UnmarshalJSON implements the json.Unmarshaler interface for BulkUpdateSegmentsItem. // It customizes the JSON unmarshaling process for BulkUpdateSegmentsItem objects. func (b *BulkUpdateSegmentsItem) UnmarshalJSON(input []byte) error { - temp := &struct { - Id int `json:"id"` - PricingScheme PricingScheme `json:"pricing_scheme"` - Prices []CreateOrUpdateSegmentPrice `json:"prices"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - b.Id = temp.Id - b.PricingScheme = temp.PricingScheme - b.Prices = temp.Prices - return nil + var temp bulkUpdateSegmentsItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + b.Id = *temp.Id + b.PricingScheme = *temp.PricingScheme + b.Prices = *temp.Prices + return nil +} + +// TODO +type bulkUpdateSegmentsItem struct { + Id *int `json:"id"` + PricingScheme *PricingScheme `json:"pricing_scheme"` + Prices *[]CreateOrUpdateSegmentPrice `json:"prices"` +} + +func (b *bulkUpdateSegmentsItem) validate() error { + var errs []string + if b.Id == nil { + errs = append(errs, "required field `id` is missing for type `Bulk Update Segments Item`") + } + if b.PricingScheme == nil { + errs = append(errs, "required field `pricing_scheme` is missing for type `Bulk Update Segments Item`") + } + if b.Prices == nil { + errs = append(errs, "required field `prices` is missing for type `Bulk Update Segments Item`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/calendar_billing.go b/models/calendar_billing.go index 90c24803..6975ba95 100644 --- a/models/calendar_billing.go +++ b/models/calendar_billing.go @@ -1,50 +1,52 @@ package models import ( - "encoding/json" + "encoding/json" ) -// CalendarBilling represents a CalendarBilling struct. +// CalendarBilling represents a CalendarBilling struct. // (Optional). Cannot be used when also specifying next_billing_at type CalendarBilling struct { - // A day of month that subscription will be processed on. Can be 1 up to 28 or 'end'. - SnapDay *interface{} `json:"snap_day,omitempty"` - CalendarBillingFirstCharge *FirstChargeType `json:"calendar_billing_first_charge,omitempty"` + // A day of month that subscription will be processed on. Can be 1 up to 28 or 'end'. + SnapDay *CalendarBillingSnapDay `json:"snap_day,omitempty"` + CalendarBillingFirstCharge *FirstChargeType `json:"calendar_billing_first_charge,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CalendarBilling. +// MarshalJSON implements the json.Marshaler interface for CalendarBilling. // It customizes the JSON marshaling process for CalendarBilling objects. func (c *CalendarBilling) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CalendarBilling object to a map representation for JSON marshaling. func (c *CalendarBilling) toMap() map[string]any { - structMap := make(map[string]any) - if c.SnapDay != nil { - structMap["snap_day"] = c.SnapDay - } - if c.CalendarBillingFirstCharge != nil { - structMap["calendar_billing_first_charge"] = c.CalendarBillingFirstCharge - } - return structMap + structMap := make(map[string]any) + if c.SnapDay != nil { + structMap["snap_day"] = c.SnapDay.toMap() + } + if c.CalendarBillingFirstCharge != nil { + structMap["calendar_billing_first_charge"] = c.CalendarBillingFirstCharge + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CalendarBilling. +// UnmarshalJSON implements the json.Unmarshaler interface for CalendarBilling. // It customizes the JSON unmarshaling process for CalendarBilling objects. func (c *CalendarBilling) UnmarshalJSON(input []byte) error { - temp := &struct { - SnapDay *interface{} `json:"snap_day,omitempty"` - CalendarBillingFirstCharge *FirstChargeType `json:"calendar_billing_first_charge,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.SnapDay = temp.SnapDay - c.CalendarBillingFirstCharge = temp.CalendarBillingFirstCharge - return nil + var temp calendarBilling + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.SnapDay = temp.SnapDay + c.CalendarBillingFirstCharge = temp.CalendarBillingFirstCharge + return nil +} + +// TODO +type calendarBilling struct { + SnapDay *CalendarBillingSnapDay `json:"snap_day,omitempty"` + CalendarBillingFirstCharge *FirstChargeType `json:"calendar_billing_first_charge,omitempty"` } diff --git a/models/calendar_billing_snap_day.go b/models/calendar_billing_snap_day.go new file mode 100644 index 00000000..024da616 --- /dev/null +++ b/models/calendar_billing_snap_day.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CalendarBillingSnapDay represents a CalendarBillingSnapDay struct. +// This is a container for one-of cases. +type CalendarBillingSnapDay struct { + value any + isNumber bool + isString bool +} + +// String converts the CalendarBillingSnapDay object to a string representation. +func (c CalendarBillingSnapDay) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CalendarBillingSnapDay. +// It customizes the JSON marshaling process for CalendarBillingSnapDay objects. +func (c *CalendarBillingSnapDay) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CalendarBillingSnapDayContainer.From*` functions to initialize the CalendarBillingSnapDay object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CalendarBillingSnapDay object to a map representation for JSON marshaling. +func (c *CalendarBillingSnapDay) toMap() any { + switch obj := c.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CalendarBillingSnapDay. +// It customizes the JSON unmarshaling process for CalendarBillingSnapDay objects. +func (c *CalendarBillingSnapDay) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(string), false, &c.isString), + ) + + c.value = result + return err +} + +func (c *CalendarBillingSnapDay) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CalendarBillingSnapDay) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +// internalCalendarBillingSnapDay represents a calendarBillingSnapDay struct. +// This is a container for one-of cases. +type internalCalendarBillingSnapDay struct{} + +var CalendarBillingSnapDayContainer internalCalendarBillingSnapDay + +func (c *internalCalendarBillingSnapDay) FromNumber(val int) CalendarBillingSnapDay { + return CalendarBillingSnapDay{value: &val} +} + +func (c *internalCalendarBillingSnapDay) FromString(val string) CalendarBillingSnapDay { + return CalendarBillingSnapDay{value: &val} +} diff --git a/models/cancel_grouped_subscriptions_request.go b/models/cancel_grouped_subscriptions_request.go index a3853ae4..78477240 100644 --- a/models/cancel_grouped_subscriptions_request.go +++ b/models/cancel_grouped_subscriptions_request.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // CancelGroupedSubscriptionsRequest represents a CancelGroupedSubscriptionsRequest struct. type CancelGroupedSubscriptionsRequest struct { - ChargeUnbilledUsage *bool `json:"charge_unbilled_usage,omitempty"` + ChargeUnbilledUsage *bool `json:"charge_unbilled_usage,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CancelGroupedSubscriptionsRequest. +// MarshalJSON implements the json.Marshaler interface for CancelGroupedSubscriptionsRequest. // It customizes the JSON marshaling process for CancelGroupedSubscriptionsRequest objects. func (c *CancelGroupedSubscriptionsRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CancelGroupedSubscriptionsRequest object to a map representation for JSON marshaling. func (c *CancelGroupedSubscriptionsRequest) toMap() map[string]any { - structMap := make(map[string]any) - if c.ChargeUnbilledUsage != nil { - structMap["charge_unbilled_usage"] = c.ChargeUnbilledUsage - } - return structMap + structMap := make(map[string]any) + if c.ChargeUnbilledUsage != nil { + structMap["charge_unbilled_usage"] = c.ChargeUnbilledUsage + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CancelGroupedSubscriptionsRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CancelGroupedSubscriptionsRequest. // It customizes the JSON unmarshaling process for CancelGroupedSubscriptionsRequest objects. func (c *CancelGroupedSubscriptionsRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - ChargeUnbilledUsage *bool `json:"charge_unbilled_usage,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ChargeUnbilledUsage = temp.ChargeUnbilledUsage - return nil + var temp cancelGroupedSubscriptionsRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.ChargeUnbilledUsage = temp.ChargeUnbilledUsage + return nil +} + +// TODO +type cancelGroupedSubscriptionsRequest struct { + ChargeUnbilledUsage *bool `json:"charge_unbilled_usage,omitempty"` } diff --git a/models/cancellation_options.go b/models/cancellation_options.go index 82e4f847..26a94f81 100644 --- a/models/cancellation_options.go +++ b/models/cancellation_options.go @@ -1,50 +1,52 @@ package models import ( - "encoding/json" + "encoding/json" ) // CancellationOptions represents a CancellationOptions struct. type CancellationOptions struct { - // For your internal use. An indication as to why the subscription is being canceled. - CancellationMessage *string `json:"cancellation_message,omitempty"` - // The reason code associated with the cancellation. See the list of reason codes associated with your site. - ReasonCode *string `json:"reason_code,omitempty"` + // For your internal use. An indication as to why the subscription is being canceled. + CancellationMessage *string `json:"cancellation_message,omitempty"` + // The reason code associated with the cancellation. See the list of reason codes associated with your site. + ReasonCode *string `json:"reason_code,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CancellationOptions. +// MarshalJSON implements the json.Marshaler interface for CancellationOptions. // It customizes the JSON marshaling process for CancellationOptions objects. func (c *CancellationOptions) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CancellationOptions object to a map representation for JSON marshaling. func (c *CancellationOptions) toMap() map[string]any { - structMap := make(map[string]any) - if c.CancellationMessage != nil { - structMap["cancellation_message"] = c.CancellationMessage - } - if c.ReasonCode != nil { - structMap["reason_code"] = c.ReasonCode - } - return structMap + structMap := make(map[string]any) + if c.CancellationMessage != nil { + structMap["cancellation_message"] = c.CancellationMessage + } + if c.ReasonCode != nil { + structMap["reason_code"] = c.ReasonCode + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CancellationOptions. +// UnmarshalJSON implements the json.Unmarshaler interface for CancellationOptions. // It customizes the JSON unmarshaling process for CancellationOptions objects. func (c *CancellationOptions) UnmarshalJSON(input []byte) error { - temp := &struct { - CancellationMessage *string `json:"cancellation_message,omitempty"` - ReasonCode *string `json:"reason_code,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.CancellationMessage = temp.CancellationMessage - c.ReasonCode = temp.ReasonCode - return nil + var temp cancellationOptions + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.CancellationMessage = temp.CancellationMessage + c.ReasonCode = temp.ReasonCode + return nil +} + +// TODO +type cancellationOptions struct { + CancellationMessage *string `json:"cancellation_message,omitempty"` + ReasonCode *string `json:"reason_code,omitempty"` } diff --git a/models/cancellation_request.go b/models/cancellation_request.go index bfaca7c7..a5971342 100644 --- a/models/cancellation_request.go +++ b/models/cancellation_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CancellationRequest represents a CancellationRequest struct. type CancellationRequest struct { - Subscription CancellationOptions `json:"subscription"` + Subscription CancellationOptions `json:"subscription"` } -// MarshalJSON implements the json.Marshaler interface for CancellationRequest. +// MarshalJSON implements the json.Marshaler interface for CancellationRequest. // It customizes the JSON marshaling process for CancellationRequest objects. func (c *CancellationRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CancellationRequest object to a map representation for JSON marshaling. func (c *CancellationRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscription"] = c.Subscription.toMap() - return structMap + structMap := make(map[string]any) + structMap["subscription"] = c.Subscription.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CancellationRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CancellationRequest. // It customizes the JSON unmarshaling process for CancellationRequest objects. func (c *CancellationRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Subscription CancellationOptions `json:"subscription"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Subscription = temp.Subscription - return nil + var temp cancellationRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Subscription = *temp.Subscription + return nil +} + +// TODO +type cancellationRequest struct { + Subscription *CancellationOptions `json:"subscription"` +} + +func (c *cancellationRequest) validate() error { + var errs []string + if c.Subscription == nil { + errs = append(errs, "required field `subscription` is missing for type `Cancellation Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/change_invoice_collection_method_event_data.go b/models/change_invoice_collection_method_event_data.go new file mode 100644 index 00000000..935fbf43 --- /dev/null +++ b/models/change_invoice_collection_method_event_data.go @@ -0,0 +1,70 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ChangeInvoiceCollectionMethodEventData represents a ChangeInvoiceCollectionMethodEventData struct. +// Example schema for an `change_invoice_collection_method` event +type ChangeInvoiceCollectionMethodEventData struct { + // The previous collection method of the invoice. + FromCollectionMethod string `json:"from_collection_method"` + // The new collection method of the invoice. + ToCollectionMethod string `json:"to_collection_method"` +} + +// MarshalJSON implements the json.Marshaler interface for ChangeInvoiceCollectionMethodEventData. +// It customizes the JSON marshaling process for ChangeInvoiceCollectionMethodEventData objects. +func (c *ChangeInvoiceCollectionMethodEventData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(c.toMap()) +} + +// toMap converts the ChangeInvoiceCollectionMethodEventData object to a map representation for JSON marshaling. +func (c *ChangeInvoiceCollectionMethodEventData) toMap() map[string]any { + structMap := make(map[string]any) + structMap["from_collection_method"] = c.FromCollectionMethod + structMap["to_collection_method"] = c.ToCollectionMethod + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ChangeInvoiceCollectionMethodEventData. +// It customizes the JSON unmarshaling process for ChangeInvoiceCollectionMethodEventData objects. +func (c *ChangeInvoiceCollectionMethodEventData) UnmarshalJSON(input []byte) error { + var temp changeInvoiceCollectionMethodEventData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.FromCollectionMethod = *temp.FromCollectionMethod + c.ToCollectionMethod = *temp.ToCollectionMethod + return nil +} + +// TODO +type changeInvoiceCollectionMethodEventData struct { + FromCollectionMethod *string `json:"from_collection_method"` + ToCollectionMethod *string `json:"to_collection_method"` +} + +func (c *changeInvoiceCollectionMethodEventData) validate() error { + var errs []string + if c.FromCollectionMethod == nil { + errs = append(errs, "required field `from_collection_method` is missing for type `Change Invoice Collection Method Event Data`") + } + if c.ToCollectionMethod == nil { + errs = append(errs, "required field `to_collection_method` is missing for type `Change Invoice Collection Method Event Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/chargify_ebb.go b/models/chargify_ebb.go index 5d21fe93..a503d668 100644 --- a/models/chargify_ebb.go +++ b/models/chargify_ebb.go @@ -1,94 +1,96 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // ChargifyEBB represents a ChargifyEBB struct. type ChargifyEBB struct { - // This timestamp determines what billing period the event will be billed in. If your request payload does not include it, Chargify will add `chargify.timestamp` to the event payload and set the value to `now`. - Timestamp *time.Time `json:"timestamp,omitempty"` - // A unique ID set by Chargify. Please note that this field is reserved. If `chargify.id` is present in the request payload, it will be overwritten. - Id *string `json:"id,omitempty"` - // An ISO-8601 timestamp, set by Chargify at the time each event is recorded. Please note that this field is reserved. If `chargify.created_at` is present in the request payload, it will be overwritten. - CreatedAt *time.Time `json:"created_at,omitempty"` - // User-defined string scoped per-stream. Duplicate events within a stream will be silently ignored. Tokens expire after 31 days. - UniquenessToken *string `json:"uniqueness_token,omitempty"` - // Id of Maxio Advanced Billing Subscription which is connected to this event. - // Provide `subscription_id` if you configured `chargify.subscription_id` as Subscription Identifier in your Event Stream. - SubscriptionId *int `json:"subscription_id,omitempty"` - // Reference of Maxio Advanced Billing Subscription which is connected to this event. - // Provide `subscription_reference` if you configured `chargify.subscription_reference` as Subscription Identifier in your Event Stream. - SubscriptionReference *string `json:"subscription_reference,omitempty"` + // This timestamp determines what billing period the event will be billed in. If your request payload does not include it, Chargify will add `chargify.timestamp` to the event payload and set the value to `now`. + Timestamp *time.Time `json:"timestamp,omitempty"` + // A unique ID set by Chargify. Please note that this field is reserved. If `chargify.id` is present in the request payload, it will be overwritten. + Id *string `json:"id,omitempty"` + // An ISO-8601 timestamp, set by Chargify at the time each event is recorded. Please note that this field is reserved. If `chargify.created_at` is present in the request payload, it will be overwritten. + CreatedAt *time.Time `json:"created_at,omitempty"` + // User-defined string scoped per-stream. Duplicate events within a stream will be silently ignored. Tokens expire after 31 days. + UniquenessToken *string `json:"uniqueness_token,omitempty"` + // Id of Maxio Advanced Billing Subscription which is connected to this event. + // Provide `subscription_id` if you configured `chargify.subscription_id` as Subscription Identifier in your Event Stream. + SubscriptionId *int `json:"subscription_id,omitempty"` + // Reference of Maxio Advanced Billing Subscription which is connected to this event. + // Provide `subscription_reference` if you configured `chargify.subscription_reference` as Subscription Identifier in your Event Stream. + SubscriptionReference *string `json:"subscription_reference,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ChargifyEBB. +// MarshalJSON implements the json.Marshaler interface for ChargifyEBB. // It customizes the JSON marshaling process for ChargifyEBB objects. func (c *ChargifyEBB) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ChargifyEBB object to a map representation for JSON marshaling. func (c *ChargifyEBB) toMap() map[string]any { - structMap := make(map[string]any) - if c.Timestamp != nil { - structMap["timestamp"] = c.Timestamp.Format(time.RFC3339) - } - if c.Id != nil { - structMap["id"] = c.Id - } - if c.CreatedAt != nil { - structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) - } - if c.UniquenessToken != nil { - structMap["uniqueness_token"] = c.UniquenessToken - } - if c.SubscriptionId != nil { - structMap["subscription_id"] = c.SubscriptionId - } - if c.SubscriptionReference != nil { - structMap["subscription_reference"] = c.SubscriptionReference - } - return structMap + structMap := make(map[string]any) + if c.Timestamp != nil { + structMap["timestamp"] = c.Timestamp.Format(time.RFC3339) + } + if c.Id != nil { + structMap["id"] = c.Id + } + if c.CreatedAt != nil { + structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) + } + if c.UniquenessToken != nil { + structMap["uniqueness_token"] = c.UniquenessToken + } + if c.SubscriptionId != nil { + structMap["subscription_id"] = c.SubscriptionId + } + if c.SubscriptionReference != nil { + structMap["subscription_reference"] = c.SubscriptionReference + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ChargifyEBB. +// UnmarshalJSON implements the json.Unmarshaler interface for ChargifyEBB. // It customizes the JSON unmarshaling process for ChargifyEBB objects. func (c *ChargifyEBB) UnmarshalJSON(input []byte) error { - temp := &struct { - Timestamp *string `json:"timestamp,omitempty"` - Id *string `json:"id,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UniquenessToken *string `json:"uniqueness_token,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - SubscriptionReference *string `json:"subscription_reference,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - if temp.Timestamp != nil { - TimestampVal, err := time.Parse(time.RFC3339, *temp.Timestamp) - if err != nil { - log.Fatalf("Cannot Parse timestamp as % s format.", time.RFC3339) - } - c.Timestamp = &TimestampVal - } - c.Id = temp.Id - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - c.CreatedAt = &CreatedAtVal - } - c.UniquenessToken = temp.UniquenessToken - c.SubscriptionId = temp.SubscriptionId - c.SubscriptionReference = temp.SubscriptionReference - return nil + var temp chargifyEBB + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + if temp.Timestamp != nil { + TimestampVal, err := time.Parse(time.RFC3339, *temp.Timestamp) + if err != nil { + log.Fatalf("Cannot Parse timestamp as % s format.", time.RFC3339) + } + c.Timestamp = &TimestampVal + } + c.Id = temp.Id + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + c.CreatedAt = &CreatedAtVal + } + c.UniquenessToken = temp.UniquenessToken + c.SubscriptionId = temp.SubscriptionId + c.SubscriptionReference = temp.SubscriptionReference + return nil +} + +// TODO +type chargifyEBB struct { + Timestamp *string `json:"timestamp,omitempty"` + Id *string `json:"id,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + UniquenessToken *string `json:"uniqueness_token,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + SubscriptionReference *string `json:"subscription_reference,omitempty"` } diff --git a/models/component.go b/models/component.go index 239bfad3..bd65d81f 100644 --- a/models/component.go +++ b/models/component.go @@ -1,296 +1,358 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Component represents a Component struct. type Component struct { - // The unique ID assigned to the component by Chargify. This ID can be used to fetch the component from the API. - Id *int `json:"id,omitempty"` - // The name of the Component, suitable for display on statements. i.e. Text Messages. - Name *string `json:"name,omitempty"` - // The component API handle - Handle Optional[string] `json:"handle"` - PricingScheme Optional[PricingScheme] `json:"pricing_scheme"` - // The name of the unit that the component’s usage is measured in. i.e. message - UnitName *string `json:"unit_name,omitempty"` - // The amount the customer will be charged per unit. This field is only populated for ‘per_unit’ pricing schemes, otherwise it may be null. - UnitPrice Optional[string] `json:"unit_price"` - // The id of the Product Family to which the Component belongs - ProductFamilyId *int `json:"product_family_id,omitempty"` - // The name of the Product Family to which the Component belongs - ProductFamilyName *string `json:"product_family_name,omitempty"` - // deprecated - use unit_price instead - PricePerUnitInCents Optional[int64] `json:"price_per_unit_in_cents"` - // A handle for the component type - Kind *ComponentKind `json:"kind,omitempty"` - // Boolean flag describing whether a component is archived or not. - Archived *bool `json:"archived,omitempty"` - // Boolean flag describing whether a component is taxable or not. - Taxable *bool `json:"taxable,omitempty"` - // The description of the component. - Description Optional[string] `json:"description"` - DefaultPricePointId Optional[int] `json:"default_price_point_id"` - // An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. - OveragePrices Optional[[]ComponentPrice] `json:"overage_prices"` - // An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. - Prices Optional[[]ComponentPrice] `json:"prices"` - // Count for the number of price points associated with the component - PricePointCount *int `json:"price_point_count,omitempty"` - // URL that points to the location to read the existing price points via GET request - PricePointsUrl *string `json:"price_points_url,omitempty"` - DefaultPricePointName *string `json:"default_price_point_name,omitempty"` - // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. - TaxCode Optional[string] `json:"tax_code"` - Recurring *bool `json:"recurring,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - // Timestamp indicating when this component was created - CreatedAt *time.Time `json:"created_at,omitempty"` - // Timestamp indicating when this component was updated - UpdatedAt *time.Time `json:"updated_at,omitempty"` - // Timestamp indicating when this component was archived - ArchivedAt Optional[time.Time] `json:"archived_at"` - // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - // One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other - ItemCategory Optional[ItemCategory] `json:"item_category"` - UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` - // E.g. Internal ID or SKU Number - AccountingCode Optional[string] `json:"accounting_code"` - // (Only for Event Based Components) This is an ID of a metric attached to the component. This metric is used to bill upon collected events. - EventBasedBillingMetricId *int `json:"event_based_billing_metric_id,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + // The unique ID assigned to the component by Chargify. This ID can be used to fetch the component from the API. + Id *int `json:"id,omitempty"` + // The name of the Component, suitable for display on statements. i.e. Text Messages. + Name *string `json:"name,omitempty"` + // The component API handle + Handle Optional[string] `json:"handle"` + PricingScheme Optional[ComponentPricingScheme] `json:"pricing_scheme"` + // The name of the unit that the component’s usage is measured in. i.e. message + UnitName *string `json:"unit_name,omitempty"` + // The amount the customer will be charged per unit. This field is only populated for ‘per_unit’ pricing schemes, otherwise it may be null. + UnitPrice Optional[string] `json:"unit_price"` + // The id of the Product Family to which the Component belongs + ProductFamilyId *int `json:"product_family_id,omitempty"` + // The name of the Product Family to which the Component belongs + ProductFamilyName *string `json:"product_family_name,omitempty"` + // deprecated - use unit_price instead + PricePerUnitInCents Optional[int64] `json:"price_per_unit_in_cents"` + // A handle for the component type + Kind *ComponentKind `json:"kind,omitempty"` + // Boolean flag describing whether a component is archived or not. + Archived *bool `json:"archived,omitempty"` + // Boolean flag describing whether a component is taxable or not. + Taxable *bool `json:"taxable,omitempty"` + // The description of the component. + Description Optional[string] `json:"description"` + DefaultPricePointId Optional[int] `json:"default_price_point_id"` + // An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. + OveragePrices Optional[[]ComponentPrice] `json:"overage_prices"` + // An array of price brackets. If the component uses the ‘per_unit’ pricing scheme, this array will be empty. + Prices Optional[[]ComponentPrice] `json:"prices"` + // Count for the number of price points associated with the component + PricePointCount *int `json:"price_point_count,omitempty"` + // URL that points to the location to read the existing price points via GET request + PricePointsUrl *string `json:"price_points_url,omitempty"` + DefaultPricePointName *string `json:"default_price_point_name,omitempty"` + // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. + TaxCode Optional[string] `json:"tax_code"` + Recurring *bool `json:"recurring,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + // Timestamp indicating when this component was created + CreatedAt *time.Time `json:"created_at,omitempty"` + // Timestamp indicating when this component was updated + UpdatedAt *time.Time `json:"updated_at,omitempty"` + // Timestamp indicating when this component was archived + ArchivedAt Optional[time.Time] `json:"archived_at"` + // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + // One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other + ItemCategory Optional[ItemCategory] `json:"item_category"` + UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` + // E.g. Internal ID or SKU Number + AccountingCode Optional[string] `json:"accounting_code"` + // (Only for Event Based Components) This is an ID of a metric attached to the component. This metric is used to bill upon collected events. + EventBasedBillingMetricId *int `json:"event_based_billing_metric_id,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Component. +// MarshalJSON implements the json.Marshaler interface for Component. // It customizes the JSON marshaling process for Component objects. func (c *Component) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the Component object to a map representation for JSON marshaling. func (c *Component) toMap() map[string]any { - structMap := make(map[string]any) - if c.Id != nil { - structMap["id"] = c.Id - } - if c.Name != nil { - structMap["name"] = c.Name - } - if c.Handle.IsValueSet() { - structMap["handle"] = c.Handle.Value() - } - if c.PricingScheme.IsValueSet() { - structMap["pricing_scheme"] = c.PricingScheme.Value() - } - if c.UnitName != nil { - structMap["unit_name"] = c.UnitName - } - if c.UnitPrice.IsValueSet() { - structMap["unit_price"] = c.UnitPrice.Value() - } - if c.ProductFamilyId != nil { - structMap["product_family_id"] = c.ProductFamilyId - } - if c.ProductFamilyName != nil { - structMap["product_family_name"] = c.ProductFamilyName - } - if c.PricePerUnitInCents.IsValueSet() { - structMap["price_per_unit_in_cents"] = c.PricePerUnitInCents.Value() - } - if c.Kind != nil { - structMap["kind"] = c.Kind - } - if c.Archived != nil { - structMap["archived"] = c.Archived - } - if c.Taxable != nil { - structMap["taxable"] = c.Taxable - } - if c.Description.IsValueSet() { - structMap["description"] = c.Description.Value() - } - if c.DefaultPricePointId.IsValueSet() { - structMap["default_price_point_id"] = c.DefaultPricePointId.Value() - } - if c.OveragePrices.IsValueSet() { - structMap["overage_prices"] = c.OveragePrices.Value() - } - if c.Prices.IsValueSet() { - structMap["prices"] = c.Prices.Value() - } - if c.PricePointCount != nil { - structMap["price_point_count"] = c.PricePointCount - } - if c.PricePointsUrl != nil { - structMap["price_points_url"] = c.PricePointsUrl - } - if c.DefaultPricePointName != nil { - structMap["default_price_point_name"] = c.DefaultPricePointName - } - if c.TaxCode.IsValueSet() { - structMap["tax_code"] = c.TaxCode.Value() - } - if c.Recurring != nil { - structMap["recurring"] = c.Recurring - } - if c.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = c.UpgradeCharge.Value() - } - if c.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = c.DowngradeCredit.Value() - } - if c.CreatedAt != nil { - structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) - } - if c.UpdatedAt != nil { - structMap["updated_at"] = c.UpdatedAt.Format(time.RFC3339) - } - if c.ArchivedAt.IsValueSet() { - var ArchivedAtVal *string = nil - if c.ArchivedAt.Value() != nil { - val := c.ArchivedAt.Value().Format(time.RFC3339) - ArchivedAtVal = &val - } - structMap["archived_at"] = ArchivedAtVal - } - if c.HideDateRangeOnInvoice != nil { - structMap["hide_date_range_on_invoice"] = c.HideDateRangeOnInvoice - } - if c.AllowFractionalQuantities != nil { - structMap["allow_fractional_quantities"] = c.AllowFractionalQuantities - } - if c.ItemCategory.IsValueSet() { - structMap["item_category"] = c.ItemCategory.Value() - } - if c.UseSiteExchangeRate.IsValueSet() { - structMap["use_site_exchange_rate"] = c.UseSiteExchangeRate.Value() - } - if c.AccountingCode.IsValueSet() { - structMap["accounting_code"] = c.AccountingCode.Value() - } - if c.EventBasedBillingMetricId != nil { - structMap["event_based_billing_metric_id"] = c.EventBasedBillingMetricId - } - if c.Interval != nil { - structMap["interval"] = c.Interval - } - if c.IntervalUnit != nil { - structMap["interval_unit"] = c.IntervalUnit - } - return structMap + structMap := make(map[string]any) + if c.Id != nil { + structMap["id"] = c.Id + } + if c.Name != nil { + structMap["name"] = c.Name + } + if c.Handle.IsValueSet() { + if c.Handle.Value() != nil { + structMap["handle"] = c.Handle.Value() + } else { + structMap["handle"] = nil + } + } + if c.PricingScheme.IsValueSet() { + if c.PricingScheme.Value() != nil { + structMap["pricing_scheme"] = c.PricingScheme.Value().toMap() + } else { + structMap["pricing_scheme"] = nil + } + } + if c.UnitName != nil { + structMap["unit_name"] = c.UnitName + } + if c.UnitPrice.IsValueSet() { + if c.UnitPrice.Value() != nil { + structMap["unit_price"] = c.UnitPrice.Value() + } else { + structMap["unit_price"] = nil + } + } + if c.ProductFamilyId != nil { + structMap["product_family_id"] = c.ProductFamilyId + } + if c.ProductFamilyName != nil { + structMap["product_family_name"] = c.ProductFamilyName + } + if c.PricePerUnitInCents.IsValueSet() { + if c.PricePerUnitInCents.Value() != nil { + structMap["price_per_unit_in_cents"] = c.PricePerUnitInCents.Value() + } else { + structMap["price_per_unit_in_cents"] = nil + } + } + if c.Kind != nil { + structMap["kind"] = c.Kind + } + if c.Archived != nil { + structMap["archived"] = c.Archived + } + if c.Taxable != nil { + structMap["taxable"] = c.Taxable + } + if c.Description.IsValueSet() { + if c.Description.Value() != nil { + structMap["description"] = c.Description.Value() + } else { + structMap["description"] = nil + } + } + if c.DefaultPricePointId.IsValueSet() { + if c.DefaultPricePointId.Value() != nil { + structMap["default_price_point_id"] = c.DefaultPricePointId.Value() + } else { + structMap["default_price_point_id"] = nil + } + } + if c.OveragePrices.IsValueSet() { + if c.OveragePrices.Value() != nil { + structMap["overage_prices"] = c.OveragePrices.Value() + } else { + structMap["overage_prices"] = nil + } + } + if c.Prices.IsValueSet() { + if c.Prices.Value() != nil { + structMap["prices"] = c.Prices.Value() + } else { + structMap["prices"] = nil + } + } + if c.PricePointCount != nil { + structMap["price_point_count"] = c.PricePointCount + } + if c.PricePointsUrl != nil { + structMap["price_points_url"] = c.PricePointsUrl + } + if c.DefaultPricePointName != nil { + structMap["default_price_point_name"] = c.DefaultPricePointName + } + if c.TaxCode.IsValueSet() { + if c.TaxCode.Value() != nil { + structMap["tax_code"] = c.TaxCode.Value() + } else { + structMap["tax_code"] = nil + } + } + if c.Recurring != nil { + structMap["recurring"] = c.Recurring + } + if c.UpgradeCharge.IsValueSet() { + if c.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = c.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if c.DowngradeCredit.IsValueSet() { + if c.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = c.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if c.CreatedAt != nil { + structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) + } + if c.UpdatedAt != nil { + structMap["updated_at"] = c.UpdatedAt.Format(time.RFC3339) + } + if c.ArchivedAt.IsValueSet() { + var ArchivedAtVal *string = nil + if c.ArchivedAt.Value() != nil { + val := c.ArchivedAt.Value().Format(time.RFC3339) + ArchivedAtVal = &val + } + if c.ArchivedAt.Value() != nil { + structMap["archived_at"] = ArchivedAtVal + } else { + structMap["archived_at"] = nil + } + } + if c.HideDateRangeOnInvoice != nil { + structMap["hide_date_range_on_invoice"] = c.HideDateRangeOnInvoice + } + if c.AllowFractionalQuantities != nil { + structMap["allow_fractional_quantities"] = c.AllowFractionalQuantities + } + if c.ItemCategory.IsValueSet() { + if c.ItemCategory.Value() != nil { + structMap["item_category"] = c.ItemCategory.Value() + } else { + structMap["item_category"] = nil + } + } + if c.UseSiteExchangeRate.IsValueSet() { + if c.UseSiteExchangeRate.Value() != nil { + structMap["use_site_exchange_rate"] = c.UseSiteExchangeRate.Value() + } else { + structMap["use_site_exchange_rate"] = nil + } + } + if c.AccountingCode.IsValueSet() { + if c.AccountingCode.Value() != nil { + structMap["accounting_code"] = c.AccountingCode.Value() + } else { + structMap["accounting_code"] = nil + } + } + if c.EventBasedBillingMetricId != nil { + structMap["event_based_billing_metric_id"] = c.EventBasedBillingMetricId + } + if c.Interval != nil { + structMap["interval"] = c.Interval + } + if c.IntervalUnit != nil { + structMap["interval_unit"] = c.IntervalUnit + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Component. +// UnmarshalJSON implements the json.Unmarshaler interface for Component. // It customizes the JSON unmarshaling process for Component objects. func (c *Component) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Handle Optional[string] `json:"handle"` - PricingScheme Optional[PricingScheme] `json:"pricing_scheme"` - UnitName *string `json:"unit_name,omitempty"` - UnitPrice Optional[string] `json:"unit_price"` - ProductFamilyId *int `json:"product_family_id,omitempty"` - ProductFamilyName *string `json:"product_family_name,omitempty"` - PricePerUnitInCents Optional[int64] `json:"price_per_unit_in_cents"` - Kind *ComponentKind `json:"kind,omitempty"` - Archived *bool `json:"archived,omitempty"` - Taxable *bool `json:"taxable,omitempty"` - Description Optional[string] `json:"description"` - DefaultPricePointId Optional[int] `json:"default_price_point_id"` - OveragePrices Optional[[]ComponentPrice] `json:"overage_prices"` - Prices Optional[[]ComponentPrice] `json:"prices"` - PricePointCount *int `json:"price_point_count,omitempty"` - PricePointsUrl *string `json:"price_points_url,omitempty"` - DefaultPricePointName *string `json:"default_price_point_name,omitempty"` - TaxCode Optional[string] `json:"tax_code"` - Recurring *bool `json:"recurring,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - ArchivedAt Optional[string] `json:"archived_at"` - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - ItemCategory Optional[ItemCategory] `json:"item_category"` - UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` - AccountingCode Optional[string] `json:"accounting_code"` - EventBasedBillingMetricId *int `json:"event_based_billing_metric_id,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Id = temp.Id - c.Name = temp.Name - c.Handle = temp.Handle - c.PricingScheme = temp.PricingScheme - c.UnitName = temp.UnitName - c.UnitPrice = temp.UnitPrice - c.ProductFamilyId = temp.ProductFamilyId - c.ProductFamilyName = temp.ProductFamilyName - c.PricePerUnitInCents = temp.PricePerUnitInCents - c.Kind = temp.Kind - c.Archived = temp.Archived - c.Taxable = temp.Taxable - c.Description = temp.Description - c.DefaultPricePointId = temp.DefaultPricePointId - c.OveragePrices = temp.OveragePrices - c.Prices = temp.Prices - c.PricePointCount = temp.PricePointCount - c.PricePointsUrl = temp.PricePointsUrl - c.DefaultPricePointName = temp.DefaultPricePointName - c.TaxCode = temp.TaxCode - c.Recurring = temp.Recurring - c.UpgradeCharge = temp.UpgradeCharge - c.DowngradeCredit = temp.DowngradeCredit - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - c.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - c.UpdatedAt = &UpdatedAtVal - } - c.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) - if temp.ArchivedAt.Value() != nil { - ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) - } - c.ArchivedAt.SetValue(&ArchivedAtVal) - } - c.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice - c.AllowFractionalQuantities = temp.AllowFractionalQuantities - c.ItemCategory = temp.ItemCategory - c.UseSiteExchangeRate = temp.UseSiteExchangeRate - c.AccountingCode = temp.AccountingCode - c.EventBasedBillingMetricId = temp.EventBasedBillingMetricId - c.Interval = temp.Interval - c.IntervalUnit = temp.IntervalUnit - return nil + var temp component + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Id = temp.Id + c.Name = temp.Name + c.Handle = temp.Handle + c.PricingScheme = temp.PricingScheme + c.UnitName = temp.UnitName + c.UnitPrice = temp.UnitPrice + c.ProductFamilyId = temp.ProductFamilyId + c.ProductFamilyName = temp.ProductFamilyName + c.PricePerUnitInCents = temp.PricePerUnitInCents + c.Kind = temp.Kind + c.Archived = temp.Archived + c.Taxable = temp.Taxable + c.Description = temp.Description + c.DefaultPricePointId = temp.DefaultPricePointId + c.OveragePrices = temp.OveragePrices + c.Prices = temp.Prices + c.PricePointCount = temp.PricePointCount + c.PricePointsUrl = temp.PricePointsUrl + c.DefaultPricePointName = temp.DefaultPricePointName + c.TaxCode = temp.TaxCode + c.Recurring = temp.Recurring + c.UpgradeCharge = temp.UpgradeCharge + c.DowngradeCredit = temp.DowngradeCredit + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + c.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + c.UpdatedAt = &UpdatedAtVal + } + c.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) + if temp.ArchivedAt.Value() != nil { + ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) + } + c.ArchivedAt.SetValue(&ArchivedAtVal) + } + c.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice + c.AllowFractionalQuantities = temp.AllowFractionalQuantities + c.ItemCategory = temp.ItemCategory + c.UseSiteExchangeRate = temp.UseSiteExchangeRate + c.AccountingCode = temp.AccountingCode + c.EventBasedBillingMetricId = temp.EventBasedBillingMetricId + c.Interval = temp.Interval + c.IntervalUnit = temp.IntervalUnit + return nil +} + +// TODO +type component struct { + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Handle Optional[string] `json:"handle"` + PricingScheme Optional[ComponentPricingScheme] `json:"pricing_scheme"` + UnitName *string `json:"unit_name,omitempty"` + UnitPrice Optional[string] `json:"unit_price"` + ProductFamilyId *int `json:"product_family_id,omitempty"` + ProductFamilyName *string `json:"product_family_name,omitempty"` + PricePerUnitInCents Optional[int64] `json:"price_per_unit_in_cents"` + Kind *ComponentKind `json:"kind,omitempty"` + Archived *bool `json:"archived,omitempty"` + Taxable *bool `json:"taxable,omitempty"` + Description Optional[string] `json:"description"` + DefaultPricePointId Optional[int] `json:"default_price_point_id"` + OveragePrices Optional[[]ComponentPrice] `json:"overage_prices"` + Prices Optional[[]ComponentPrice] `json:"prices"` + PricePointCount *int `json:"price_point_count,omitempty"` + PricePointsUrl *string `json:"price_points_url,omitempty"` + DefaultPricePointName *string `json:"default_price_point_name,omitempty"` + TaxCode Optional[string] `json:"tax_code"` + Recurring *bool `json:"recurring,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + ArchivedAt Optional[string] `json:"archived_at"` + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + ItemCategory Optional[ItemCategory] `json:"item_category"` + UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` + AccountingCode Optional[string] `json:"accounting_code"` + EventBasedBillingMetricId *int `json:"event_based_billing_metric_id,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` } diff --git a/models/component_allocation_change.go b/models/component_allocation_change.go new file mode 100644 index 00000000..626741f7 --- /dev/null +++ b/models/component_allocation_change.go @@ -0,0 +1,101 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ComponentAllocationChange represents a ComponentAllocationChange struct. +type ComponentAllocationChange struct { + PreviousAllocation int `json:"previous_allocation"` + NewAllocation int `json:"new_allocation"` + ComponentId int `json:"component_id"` + ComponentHandle string `json:"component_handle"` + Memo string `json:"memo"` + AllocationId int `json:"allocation_id"` + AllocatedQuantity *ComponentAllocationChangeAllocatedQuantity `json:"allocated_quantity,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for ComponentAllocationChange. +// It customizes the JSON marshaling process for ComponentAllocationChange objects. +func (c *ComponentAllocationChange) MarshalJSON() ( + []byte, + error) { + return json.Marshal(c.toMap()) +} + +// toMap converts the ComponentAllocationChange object to a map representation for JSON marshaling. +func (c *ComponentAllocationChange) toMap() map[string]any { + structMap := make(map[string]any) + structMap["previous_allocation"] = c.PreviousAllocation + structMap["new_allocation"] = c.NewAllocation + structMap["component_id"] = c.ComponentId + structMap["component_handle"] = c.ComponentHandle + structMap["memo"] = c.Memo + structMap["allocation_id"] = c.AllocationId + if c.AllocatedQuantity != nil { + structMap["allocated_quantity"] = c.AllocatedQuantity.toMap() + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentAllocationChange. +// It customizes the JSON unmarshaling process for ComponentAllocationChange objects. +func (c *ComponentAllocationChange) UnmarshalJSON(input []byte) error { + var temp componentAllocationChange + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.PreviousAllocation = *temp.PreviousAllocation + c.NewAllocation = *temp.NewAllocation + c.ComponentId = *temp.ComponentId + c.ComponentHandle = *temp.ComponentHandle + c.Memo = *temp.Memo + c.AllocationId = *temp.AllocationId + c.AllocatedQuantity = temp.AllocatedQuantity + return nil +} + +// TODO +type componentAllocationChange struct { + PreviousAllocation *int `json:"previous_allocation"` + NewAllocation *int `json:"new_allocation"` + ComponentId *int `json:"component_id"` + ComponentHandle *string `json:"component_handle"` + Memo *string `json:"memo"` + AllocationId *int `json:"allocation_id"` + AllocatedQuantity *ComponentAllocationChangeAllocatedQuantity `json:"allocated_quantity,omitempty"` +} + +func (c *componentAllocationChange) validate() error { + var errs []string + if c.PreviousAllocation == nil { + errs = append(errs, "required field `previous_allocation` is missing for type `Component Allocation Change`") + } + if c.NewAllocation == nil { + errs = append(errs, "required field `new_allocation` is missing for type `Component Allocation Change`") + } + if c.ComponentId == nil { + errs = append(errs, "required field `component_id` is missing for type `Component Allocation Change`") + } + if c.ComponentHandle == nil { + errs = append(errs, "required field `component_handle` is missing for type `Component Allocation Change`") + } + if c.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Component Allocation Change`") + } + if c.AllocationId == nil { + errs = append(errs, "required field `allocation_id` is missing for type `Component Allocation Change`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/component_allocation_change_allocated_quantity.go b/models/component_allocation_change_allocated_quantity.go new file mode 100644 index 00000000..86748544 --- /dev/null +++ b/models/component_allocation_change_allocated_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ComponentAllocationChangeAllocatedQuantity represents a ComponentAllocationChangeAllocatedQuantity struct. +// This is a container for one-of cases. +type ComponentAllocationChangeAllocatedQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the ComponentAllocationChangeAllocatedQuantity object to a string representation. +func (c ComponentAllocationChangeAllocatedQuantity) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ComponentAllocationChangeAllocatedQuantity. +// It customizes the JSON marshaling process for ComponentAllocationChangeAllocatedQuantity objects. +func (c *ComponentAllocationChangeAllocatedQuantity) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ComponentAllocationChangeAllocatedQuantityContainer.From*` functions to initialize the ComponentAllocationChangeAllocatedQuantity object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the ComponentAllocationChangeAllocatedQuantity object to a map representation for JSON marshaling. +func (c *ComponentAllocationChangeAllocatedQuantity) toMap() any { + switch obj := c.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentAllocationChangeAllocatedQuantity. +// It customizes the JSON unmarshaling process for ComponentAllocationChangeAllocatedQuantity objects. +func (c *ComponentAllocationChangeAllocatedQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(string), false, &c.isString), + ) + + c.value = result + return err +} + +func (c *ComponentAllocationChangeAllocatedQuantity) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *ComponentAllocationChangeAllocatedQuantity) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +// internalComponentAllocationChangeAllocatedQuantity represents a componentAllocationChangeAllocatedQuantity struct. +// This is a container for one-of cases. +type internalComponentAllocationChangeAllocatedQuantity struct{} + +var ComponentAllocationChangeAllocatedQuantityContainer internalComponentAllocationChangeAllocatedQuantity + +func (c *internalComponentAllocationChangeAllocatedQuantity) FromNumber(val int) ComponentAllocationChangeAllocatedQuantity { + return ComponentAllocationChangeAllocatedQuantity{value: &val} +} + +func (c *internalComponentAllocationChangeAllocatedQuantity) FromString(val string) ComponentAllocationChangeAllocatedQuantity { + return ComponentAllocationChangeAllocatedQuantity{value: &val} +} diff --git a/models/component_allocation_error_item.go b/models/component_allocation_error_item.go index 25668a3c..5529f4fa 100644 --- a/models/component_allocation_error_item.go +++ b/models/component_allocation_error_item.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // ComponentAllocationErrorItem represents a ComponentAllocationErrorItem struct. type ComponentAllocationErrorItem struct { - ComponentId *int `json:"component_id,omitempty"` - Message *string `json:"message,omitempty"` - Kind *string `json:"kind,omitempty"` - On *string `json:"on,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + Message *string `json:"message,omitempty"` + Kind *string `json:"kind,omitempty"` + On *string `json:"on,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ComponentAllocationErrorItem. +// MarshalJSON implements the json.Marshaler interface for ComponentAllocationErrorItem. // It customizes the JSON marshaling process for ComponentAllocationErrorItem objects. func (c *ComponentAllocationErrorItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentAllocationErrorItem object to a map representation for JSON marshaling. func (c *ComponentAllocationErrorItem) toMap() map[string]any { - structMap := make(map[string]any) - if c.ComponentId != nil { - structMap["component_id"] = c.ComponentId - } - if c.Message != nil { - structMap["message"] = c.Message - } - if c.Kind != nil { - structMap["kind"] = c.Kind - } - if c.On != nil { - structMap["on"] = c.On - } - return structMap + structMap := make(map[string]any) + if c.ComponentId != nil { + structMap["component_id"] = c.ComponentId + } + if c.Message != nil { + structMap["message"] = c.Message + } + if c.Kind != nil { + structMap["kind"] = c.Kind + } + if c.On != nil { + structMap["on"] = c.On + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentAllocationErrorItem. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentAllocationErrorItem. // It customizes the JSON unmarshaling process for ComponentAllocationErrorItem objects. func (c *ComponentAllocationErrorItem) UnmarshalJSON(input []byte) error { - temp := &struct { - ComponentId *int `json:"component_id,omitempty"` - Message *string `json:"message,omitempty"` - Kind *string `json:"kind,omitempty"` - On *string `json:"on,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ComponentId = temp.ComponentId - c.Message = temp.Message - c.Kind = temp.Kind - c.On = temp.On - return nil + var temp componentAllocationErrorItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.ComponentId = temp.ComponentId + c.Message = temp.Message + c.Kind = temp.Kind + c.On = temp.On + return nil +} + +// TODO +type componentAllocationErrorItem struct { + ComponentId *int `json:"component_id,omitempty"` + Message *string `json:"message,omitempty"` + Kind *string `json:"kind,omitempty"` + On *string `json:"on,omitempty"` } diff --git a/models/component_cost_data.go b/models/component_cost_data.go index 2609a9e2..76749ac0 100644 --- a/models/component_cost_data.go +++ b/models/component_cost_data.go @@ -1,79 +1,85 @@ package models import ( - "encoding/json" + "encoding/json" ) // ComponentCostData represents a ComponentCostData struct. type ComponentCostData struct { - ComponentCodeId Optional[int] `json:"component_code_id"` - PricePointId *int `json:"price_point_id,omitempty"` - ProductId *int `json:"product_id,omitempty"` - Quantity *string `json:"quantity,omitempty"` - Amount *string `json:"amount,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - Tiers []ComponentCostDataRateTier `json:"tiers,omitempty"` + ComponentCodeId Optional[int] `json:"component_code_id"` + PricePointId *int `json:"price_point_id,omitempty"` + ProductId *int `json:"product_id,omitempty"` + Quantity *string `json:"quantity,omitempty"` + Amount *string `json:"amount,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + Tiers []ComponentCostDataRateTier `json:"tiers,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ComponentCostData. +// MarshalJSON implements the json.Marshaler interface for ComponentCostData. // It customizes the JSON marshaling process for ComponentCostData objects. func (c *ComponentCostData) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentCostData object to a map representation for JSON marshaling. func (c *ComponentCostData) toMap() map[string]any { - structMap := make(map[string]any) - if c.ComponentCodeId.IsValueSet() { - structMap["component_code_id"] = c.ComponentCodeId.Value() - } - if c.PricePointId != nil { - structMap["price_point_id"] = c.PricePointId - } - if c.ProductId != nil { - structMap["product_id"] = c.ProductId - } - if c.Quantity != nil { - structMap["quantity"] = c.Quantity - } - if c.Amount != nil { - structMap["amount"] = c.Amount - } - if c.PricingScheme != nil { - structMap["pricing_scheme"] = c.PricingScheme - } - if c.Tiers != nil { - structMap["tiers"] = c.Tiers - } - return structMap + structMap := make(map[string]any) + if c.ComponentCodeId.IsValueSet() { + if c.ComponentCodeId.Value() != nil { + structMap["component_code_id"] = c.ComponentCodeId.Value() + } else { + structMap["component_code_id"] = nil + } + } + if c.PricePointId != nil { + structMap["price_point_id"] = c.PricePointId + } + if c.ProductId != nil { + structMap["product_id"] = c.ProductId + } + if c.Quantity != nil { + structMap["quantity"] = c.Quantity + } + if c.Amount != nil { + structMap["amount"] = c.Amount + } + if c.PricingScheme != nil { + structMap["pricing_scheme"] = c.PricingScheme + } + if c.Tiers != nil { + structMap["tiers"] = c.Tiers + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentCostData. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentCostData. // It customizes the JSON unmarshaling process for ComponentCostData objects. func (c *ComponentCostData) UnmarshalJSON(input []byte) error { - temp := &struct { - ComponentCodeId Optional[int] `json:"component_code_id"` - PricePointId *int `json:"price_point_id,omitempty"` - ProductId *int `json:"product_id,omitempty"` - Quantity *string `json:"quantity,omitempty"` - Amount *string `json:"amount,omitempty"` - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - Tiers []ComponentCostDataRateTier `json:"tiers,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ComponentCodeId = temp.ComponentCodeId - c.PricePointId = temp.PricePointId - c.ProductId = temp.ProductId - c.Quantity = temp.Quantity - c.Amount = temp.Amount - c.PricingScheme = temp.PricingScheme - c.Tiers = temp.Tiers - return nil + var temp componentCostData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.ComponentCodeId = temp.ComponentCodeId + c.PricePointId = temp.PricePointId + c.ProductId = temp.ProductId + c.Quantity = temp.Quantity + c.Amount = temp.Amount + c.PricingScheme = temp.PricingScheme + c.Tiers = temp.Tiers + return nil +} + +// TODO +type componentCostData struct { + ComponentCodeId Optional[int] `json:"component_code_id"` + PricePointId *int `json:"price_point_id,omitempty"` + ProductId *int `json:"product_id,omitempty"` + Quantity *string `json:"quantity,omitempty"` + Amount *string `json:"amount,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + Tiers []ComponentCostDataRateTier `json:"tiers,omitempty"` } diff --git a/models/component_cost_data_rate_tier.go b/models/component_cost_data_rate_tier.go index 6b8bd49c..528f304e 100644 --- a/models/component_cost_data_rate_tier.go +++ b/models/component_cost_data_rate_tier.go @@ -1,66 +1,72 @@ package models import ( - "encoding/json" + "encoding/json" ) // ComponentCostDataRateTier represents a ComponentCostDataRateTier struct. type ComponentCostDataRateTier struct { - StartingQuantity *int `json:"starting_quantity,omitempty"` - EndingQuantity Optional[int] `json:"ending_quantity"` - Quantity *string `json:"quantity,omitempty"` - UnitPrice *string `json:"unit_price,omitempty"` - Amount *string `json:"amount,omitempty"` + StartingQuantity *int `json:"starting_quantity,omitempty"` + EndingQuantity Optional[int] `json:"ending_quantity"` + Quantity *string `json:"quantity,omitempty"` + UnitPrice *string `json:"unit_price,omitempty"` + Amount *string `json:"amount,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ComponentCostDataRateTier. +// MarshalJSON implements the json.Marshaler interface for ComponentCostDataRateTier. // It customizes the JSON marshaling process for ComponentCostDataRateTier objects. func (c *ComponentCostDataRateTier) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentCostDataRateTier object to a map representation for JSON marshaling. func (c *ComponentCostDataRateTier) toMap() map[string]any { - structMap := make(map[string]any) - if c.StartingQuantity != nil { - structMap["starting_quantity"] = c.StartingQuantity - } - if c.EndingQuantity.IsValueSet() { - structMap["ending_quantity"] = c.EndingQuantity.Value() - } - if c.Quantity != nil { - structMap["quantity"] = c.Quantity - } - if c.UnitPrice != nil { - structMap["unit_price"] = c.UnitPrice - } - if c.Amount != nil { - structMap["amount"] = c.Amount - } - return structMap + structMap := make(map[string]any) + if c.StartingQuantity != nil { + structMap["starting_quantity"] = c.StartingQuantity + } + if c.EndingQuantity.IsValueSet() { + if c.EndingQuantity.Value() != nil { + structMap["ending_quantity"] = c.EndingQuantity.Value() + } else { + structMap["ending_quantity"] = nil + } + } + if c.Quantity != nil { + structMap["quantity"] = c.Quantity + } + if c.UnitPrice != nil { + structMap["unit_price"] = c.UnitPrice + } + if c.Amount != nil { + structMap["amount"] = c.Amount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentCostDataRateTier. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentCostDataRateTier. // It customizes the JSON unmarshaling process for ComponentCostDataRateTier objects. func (c *ComponentCostDataRateTier) UnmarshalJSON(input []byte) error { - temp := &struct { - StartingQuantity *int `json:"starting_quantity,omitempty"` - EndingQuantity Optional[int] `json:"ending_quantity"` - Quantity *string `json:"quantity,omitempty"` - UnitPrice *string `json:"unit_price,omitempty"` - Amount *string `json:"amount,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.StartingQuantity = temp.StartingQuantity - c.EndingQuantity = temp.EndingQuantity - c.Quantity = temp.Quantity - c.UnitPrice = temp.UnitPrice - c.Amount = temp.Amount - return nil + var temp componentCostDataRateTier + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.StartingQuantity = temp.StartingQuantity + c.EndingQuantity = temp.EndingQuantity + c.Quantity = temp.Quantity + c.UnitPrice = temp.UnitPrice + c.Amount = temp.Amount + return nil +} + +// TODO +type componentCostDataRateTier struct { + StartingQuantity *int `json:"starting_quantity,omitempty"` + EndingQuantity Optional[int] `json:"ending_quantity"` + Quantity *string `json:"quantity,omitempty"` + UnitPrice *string `json:"unit_price,omitempty"` + Amount *string `json:"amount,omitempty"` } diff --git a/models/component_currency_price.go b/models/component_currency_price.go index edd67372..bd0acfc3 100644 --- a/models/component_currency_price.go +++ b/models/component_currency_price.go @@ -1,72 +1,74 @@ package models import ( - "encoding/json" + "encoding/json" ) // ComponentCurrencyPrice represents a ComponentCurrencyPrice struct. type ComponentCurrencyPrice struct { - Id *int `json:"id,omitempty"` - Currency *string `json:"currency,omitempty"` - Price *string `json:"price,omitempty"` - FormattedPrice *string `json:"formatted_price,omitempty"` - PriceId *int `json:"price_id,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` + Id *int `json:"id,omitempty"` + Currency *string `json:"currency,omitempty"` + Price *string `json:"price,omitempty"` + FormattedPrice *string `json:"formatted_price,omitempty"` + PriceId *int `json:"price_id,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ComponentCurrencyPrice. +// MarshalJSON implements the json.Marshaler interface for ComponentCurrencyPrice. // It customizes the JSON marshaling process for ComponentCurrencyPrice objects. func (c *ComponentCurrencyPrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentCurrencyPrice object to a map representation for JSON marshaling. func (c *ComponentCurrencyPrice) toMap() map[string]any { - structMap := make(map[string]any) - if c.Id != nil { - structMap["id"] = c.Id - } - if c.Currency != nil { - structMap["currency"] = c.Currency - } - if c.Price != nil { - structMap["price"] = c.Price - } - if c.FormattedPrice != nil { - structMap["formatted_price"] = c.FormattedPrice - } - if c.PriceId != nil { - structMap["price_id"] = c.PriceId - } - if c.PricePointId != nil { - structMap["price_point_id"] = c.PricePointId - } - return structMap + structMap := make(map[string]any) + if c.Id != nil { + structMap["id"] = c.Id + } + if c.Currency != nil { + structMap["currency"] = c.Currency + } + if c.Price != nil { + structMap["price"] = c.Price + } + if c.FormattedPrice != nil { + structMap["formatted_price"] = c.FormattedPrice + } + if c.PriceId != nil { + structMap["price_id"] = c.PriceId + } + if c.PricePointId != nil { + structMap["price_point_id"] = c.PricePointId + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentCurrencyPrice. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentCurrencyPrice. // It customizes the JSON unmarshaling process for ComponentCurrencyPrice objects. func (c *ComponentCurrencyPrice) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Currency *string `json:"currency,omitempty"` - Price *string `json:"price,omitempty"` - FormattedPrice *string `json:"formatted_price,omitempty"` - PriceId *int `json:"price_id,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Id = temp.Id - c.Currency = temp.Currency - c.Price = temp.Price - c.FormattedPrice = temp.FormattedPrice - c.PriceId = temp.PriceId - c.PricePointId = temp.PricePointId - return nil + var temp componentCurrencyPrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Id = temp.Id + c.Currency = temp.Currency + c.Price = temp.Price + c.FormattedPrice = temp.FormattedPrice + c.PriceId = temp.PriceId + c.PricePointId = temp.PricePointId + return nil +} + +// TODO +type componentCurrencyPrice struct { + Id *int `json:"id,omitempty"` + Currency *string `json:"currency,omitempty"` + Price *string `json:"price,omitempty"` + FormattedPrice *string `json:"formatted_price,omitempty"` + PriceId *int `json:"price_id,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` } diff --git a/models/component_currency_prices_response.go b/models/component_currency_prices_response.go index 196b569a..6b9243c7 100644 --- a/models/component_currency_prices_response.go +++ b/models/component_currency_prices_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ComponentCurrencyPricesResponse represents a ComponentCurrencyPricesResponse struct. type ComponentCurrencyPricesResponse struct { - CurrencyPrices []ComponentCurrencyPrice `json:"currency_prices"` + CurrencyPrices []ComponentCurrencyPrice `json:"currency_prices"` } -// MarshalJSON implements the json.Marshaler interface for ComponentCurrencyPricesResponse. +// MarshalJSON implements the json.Marshaler interface for ComponentCurrencyPricesResponse. // It customizes the JSON marshaling process for ComponentCurrencyPricesResponse objects. func (c *ComponentCurrencyPricesResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentCurrencyPricesResponse object to a map representation for JSON marshaling. func (c *ComponentCurrencyPricesResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["currency_prices"] = c.CurrencyPrices - return structMap + structMap := make(map[string]any) + structMap["currency_prices"] = c.CurrencyPrices + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentCurrencyPricesResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentCurrencyPricesResponse. // It customizes the JSON unmarshaling process for ComponentCurrencyPricesResponse objects. func (c *ComponentCurrencyPricesResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - CurrencyPrices []ComponentCurrencyPrice `json:"currency_prices"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.CurrencyPrices = temp.CurrencyPrices - return nil + var temp componentCurrencyPricesResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.CurrencyPrices = *temp.CurrencyPrices + return nil +} + +// TODO +type componentCurrencyPricesResponse struct { + CurrencyPrices *[]ComponentCurrencyPrice `json:"currency_prices"` +} + +func (c *componentCurrencyPricesResponse) validate() error { + var errs []string + if c.CurrencyPrices == nil { + errs = append(errs, "required field `currency_prices` is missing for type `Component Currency Prices Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/component_custom_price.go b/models/component_custom_price.go index 13ed89e1..e4043538 100644 --- a/models/component_custom_price.go +++ b/models/component_custom_price.go @@ -1,65 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" ) -// ComponentCustomPrice represents a ComponentCustomPrice struct. +// ComponentCustomPrice represents a ComponentCustomPrice struct. // Create or update custom pricing unique to the subscription. Used in place of `price_point_id`. type ComponentCustomPrice struct { - // Omit for On/Off components - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - // On/off components only need one price bracket starting at 1 - Prices []Price `json:"prices,omitempty"` + // Omit for On/Off components + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + // On/off components only need one price bracket starting at 1 + Prices []Price `json:"prices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ComponentCustomPrice. +// MarshalJSON implements the json.Marshaler interface for ComponentCustomPrice. // It customizes the JSON marshaling process for ComponentCustomPrice objects. func (c *ComponentCustomPrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentCustomPrice object to a map representation for JSON marshaling. func (c *ComponentCustomPrice) toMap() map[string]any { - structMap := make(map[string]any) - if c.PricingScheme != nil { - structMap["pricing_scheme"] = c.PricingScheme - } - if c.Interval != nil { - structMap["interval"] = c.Interval - } - if c.IntervalUnit != nil { - structMap["interval_unit"] = c.IntervalUnit - } - if c.Prices != nil { - structMap["prices"] = c.Prices - } - return structMap + structMap := make(map[string]any) + if c.PricingScheme != nil { + structMap["pricing_scheme"] = c.PricingScheme + } + if c.Interval != nil { + structMap["interval"] = c.Interval + } + if c.IntervalUnit != nil { + structMap["interval_unit"] = c.IntervalUnit + } + if c.Prices != nil { + structMap["prices"] = c.Prices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentCustomPrice. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentCustomPrice. // It customizes the JSON unmarshaling process for ComponentCustomPrice objects. func (c *ComponentCustomPrice) UnmarshalJSON(input []byte) error { - temp := &struct { - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - Prices []Price `json:"prices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.PricingScheme = temp.PricingScheme - c.Interval = temp.Interval - c.IntervalUnit = temp.IntervalUnit - c.Prices = temp.Prices - return nil + var temp componentCustomPrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.PricingScheme = temp.PricingScheme + c.Interval = temp.Interval + c.IntervalUnit = temp.IntervalUnit + c.Prices = temp.Prices + return nil +} + +// TODO +type componentCustomPrice struct { + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + Prices []Price `json:"prices,omitempty"` } diff --git a/models/component_price.go b/models/component_price.go index e6f01188..eff91f14 100644 --- a/models/component_price.go +++ b/models/component_price.go @@ -1,84 +1,94 @@ package models import ( - "encoding/json" + "encoding/json" ) // ComponentPrice represents a ComponentPrice struct. type ComponentPrice struct { - Id *int `json:"id,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - StartingQuantity *int `json:"starting_quantity,omitempty"` - EndingQuantity Optional[int] `json:"ending_quantity"` - UnitPrice *string `json:"unit_price,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - FormattedUnitPrice *string `json:"formatted_unit_price,omitempty"` - SegmentId Optional[int] `json:"segment_id"` + Id *int `json:"id,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + StartingQuantity *int `json:"starting_quantity,omitempty"` + EndingQuantity Optional[int] `json:"ending_quantity"` + UnitPrice *string `json:"unit_price,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + FormattedUnitPrice *string `json:"formatted_unit_price,omitempty"` + SegmentId Optional[int] `json:"segment_id"` } -// MarshalJSON implements the json.Marshaler interface for ComponentPrice. +// MarshalJSON implements the json.Marshaler interface for ComponentPrice. // It customizes the JSON marshaling process for ComponentPrice objects. func (c *ComponentPrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentPrice object to a map representation for JSON marshaling. func (c *ComponentPrice) toMap() map[string]any { - structMap := make(map[string]any) - if c.Id != nil { - structMap["id"] = c.Id - } - if c.ComponentId != nil { - structMap["component_id"] = c.ComponentId - } - if c.StartingQuantity != nil { - structMap["starting_quantity"] = c.StartingQuantity - } - if c.EndingQuantity.IsValueSet() { - structMap["ending_quantity"] = c.EndingQuantity.Value() - } - if c.UnitPrice != nil { - structMap["unit_price"] = c.UnitPrice - } - if c.PricePointId != nil { - structMap["price_point_id"] = c.PricePointId - } - if c.FormattedUnitPrice != nil { - structMap["formatted_unit_price"] = c.FormattedUnitPrice - } - if c.SegmentId.IsValueSet() { - structMap["segment_id"] = c.SegmentId.Value() - } - return structMap + structMap := make(map[string]any) + if c.Id != nil { + structMap["id"] = c.Id + } + if c.ComponentId != nil { + structMap["component_id"] = c.ComponentId + } + if c.StartingQuantity != nil { + structMap["starting_quantity"] = c.StartingQuantity + } + if c.EndingQuantity.IsValueSet() { + if c.EndingQuantity.Value() != nil { + structMap["ending_quantity"] = c.EndingQuantity.Value() + } else { + structMap["ending_quantity"] = nil + } + } + if c.UnitPrice != nil { + structMap["unit_price"] = c.UnitPrice + } + if c.PricePointId != nil { + structMap["price_point_id"] = c.PricePointId + } + if c.FormattedUnitPrice != nil { + structMap["formatted_unit_price"] = c.FormattedUnitPrice + } + if c.SegmentId.IsValueSet() { + if c.SegmentId.Value() != nil { + structMap["segment_id"] = c.SegmentId.Value() + } else { + structMap["segment_id"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPrice. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPrice. // It customizes the JSON unmarshaling process for ComponentPrice objects. func (c *ComponentPrice) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - StartingQuantity *int `json:"starting_quantity,omitempty"` - EndingQuantity Optional[int] `json:"ending_quantity"` - UnitPrice *string `json:"unit_price,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - FormattedUnitPrice *string `json:"formatted_unit_price,omitempty"` - SegmentId Optional[int] `json:"segment_id"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Id = temp.Id - c.ComponentId = temp.ComponentId - c.StartingQuantity = temp.StartingQuantity - c.EndingQuantity = temp.EndingQuantity - c.UnitPrice = temp.UnitPrice - c.PricePointId = temp.PricePointId - c.FormattedUnitPrice = temp.FormattedUnitPrice - c.SegmentId = temp.SegmentId - return nil + var temp componentPrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Id = temp.Id + c.ComponentId = temp.ComponentId + c.StartingQuantity = temp.StartingQuantity + c.EndingQuantity = temp.EndingQuantity + c.UnitPrice = temp.UnitPrice + c.PricePointId = temp.PricePointId + c.FormattedUnitPrice = temp.FormattedUnitPrice + c.SegmentId = temp.SegmentId + return nil +} + +// TODO +type componentPrice struct { + Id *int `json:"id,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + StartingQuantity *int `json:"starting_quantity,omitempty"` + EndingQuantity Optional[int] `json:"ending_quantity"` + UnitPrice *string `json:"unit_price,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + FormattedUnitPrice *string `json:"formatted_unit_price,omitempty"` + SegmentId Optional[int] `json:"segment_id"` } diff --git a/models/component_price_point.go b/models/component_price_point.go index 5391b389..20d933ae 100644 --- a/models/component_price_point.go +++ b/models/component_price_point.go @@ -1,175 +1,189 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // ComponentPricePoint represents a ComponentPricePoint struct. type ComponentPricePoint struct { - Id *int `json:"id,omitempty"` - // Price point type. We expose the following types: - // 1. **default**: a price point that is marked as a default price for a certain product. - // 2. **custom**: a custom price point. - // 3. **catalog**: a price point that is **not** marked as a default price for a certain product and is **not** a custom one. - Type *PricePointType `json:"type,omitempty"` - // Note: Refer to type attribute instead - Default *bool `json:"default,omitempty"` // Deprecated - Name *string `json:"name,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - Handle *string `json:"handle,omitempty"` - ArchivedAt Optional[time.Time] `json:"archived_at"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - Prices []ComponentPrice `json:"prices,omitempty"` - // Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. Defaults to true during creation. - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` - // (only used for Custom Pricing - ie. when the price point's type is `custom`) The id of the subscription that the custom price point is for. - SubscriptionId *int `json:"subscription_id,omitempty"` - TaxIncluded *bool `json:"tax_included,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval Optional[int] `json:"interval"` - // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit Optional[IntervalUnit] `json:"interval_unit"` - // An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. - CurrencyPrices []ComponentCurrencyPrice `json:"currency_prices,omitempty"` + Id *int `json:"id,omitempty"` + // Price point type. We expose the following types: + // 1. **default**: a price point that is marked as a default price for a certain product. + // 2. **custom**: a custom price point. + // 3. **catalog**: a price point that is **not** marked as a default price for a certain product and is **not** a custom one. + Type *PricePointType `json:"type,omitempty"` + // Note: Refer to type attribute instead + Default *bool `json:"default,omitempty"` // Deprecated + Name *string `json:"name,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + Handle *string `json:"handle,omitempty"` + ArchivedAt Optional[time.Time] `json:"archived_at"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + Prices []ComponentPrice `json:"prices,omitempty"` + // Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. Defaults to true during creation. + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + // (only used for Custom Pricing - ie. when the price point's type is `custom`) The id of the subscription that the custom price point is for. + SubscriptionId *int `json:"subscription_id,omitempty"` + TaxIncluded *bool `json:"tax_included,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval Optional[int] `json:"interval"` + // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit Optional[ComponentPricePointIntervalUnit] `json:"interval_unit"` + // An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. + CurrencyPrices []ComponentCurrencyPrice `json:"currency_prices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ComponentPricePoint. +// MarshalJSON implements the json.Marshaler interface for ComponentPricePoint. // It customizes the JSON marshaling process for ComponentPricePoint objects. func (c *ComponentPricePoint) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentPricePoint object to a map representation for JSON marshaling. func (c *ComponentPricePoint) toMap() map[string]any { - structMap := make(map[string]any) - if c.Id != nil { - structMap["id"] = c.Id - } - if c.Type != nil { - structMap["type"] = c.Type - } - if c.Default != nil { - structMap["default"] = c.Default - } - if c.Name != nil { - structMap["name"] = c.Name - } - if c.PricingScheme != nil { - structMap["pricing_scheme"] = c.PricingScheme - } - if c.ComponentId != nil { - structMap["component_id"] = c.ComponentId - } - if c.Handle != nil { - structMap["handle"] = c.Handle - } - if c.ArchivedAt.IsValueSet() { - var ArchivedAtVal *string = nil - if c.ArchivedAt.Value() != nil { - val := c.ArchivedAt.Value().Format(time.RFC3339) - ArchivedAtVal = &val - } - structMap["archived_at"] = ArchivedAtVal - } - if c.CreatedAt != nil { - structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) - } - if c.UpdatedAt != nil { - structMap["updated_at"] = c.UpdatedAt.Format(time.RFC3339) - } - if c.Prices != nil { - structMap["prices"] = c.Prices - } - if c.UseSiteExchangeRate != nil { - structMap["use_site_exchange_rate"] = c.UseSiteExchangeRate - } - if c.SubscriptionId != nil { - structMap["subscription_id"] = c.SubscriptionId - } - if c.TaxIncluded != nil { - structMap["tax_included"] = c.TaxIncluded - } - if c.Interval.IsValueSet() { - structMap["interval"] = c.Interval.Value() - } - if c.IntervalUnit.IsValueSet() { - structMap["interval_unit"] = c.IntervalUnit.Value() - } - if c.CurrencyPrices != nil { - structMap["currency_prices"] = c.CurrencyPrices - } - return structMap + structMap := make(map[string]any) + if c.Id != nil { + structMap["id"] = c.Id + } + if c.Type != nil { + structMap["type"] = c.Type + } + if c.Default != nil { + structMap["default"] = c.Default + } + if c.Name != nil { + structMap["name"] = c.Name + } + if c.PricingScheme != nil { + structMap["pricing_scheme"] = c.PricingScheme + } + if c.ComponentId != nil { + structMap["component_id"] = c.ComponentId + } + if c.Handle != nil { + structMap["handle"] = c.Handle + } + if c.ArchivedAt.IsValueSet() { + var ArchivedAtVal *string = nil + if c.ArchivedAt.Value() != nil { + val := c.ArchivedAt.Value().Format(time.RFC3339) + ArchivedAtVal = &val + } + if c.ArchivedAt.Value() != nil { + structMap["archived_at"] = ArchivedAtVal + } else { + structMap["archived_at"] = nil + } + } + if c.CreatedAt != nil { + structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) + } + if c.UpdatedAt != nil { + structMap["updated_at"] = c.UpdatedAt.Format(time.RFC3339) + } + if c.Prices != nil { + structMap["prices"] = c.Prices + } + if c.UseSiteExchangeRate != nil { + structMap["use_site_exchange_rate"] = c.UseSiteExchangeRate + } + if c.SubscriptionId != nil { + structMap["subscription_id"] = c.SubscriptionId + } + if c.TaxIncluded != nil { + structMap["tax_included"] = c.TaxIncluded + } + if c.Interval.IsValueSet() { + if c.Interval.Value() != nil { + structMap["interval"] = c.Interval.Value() + } else { + structMap["interval"] = nil + } + } + if c.IntervalUnit.IsValueSet() { + if c.IntervalUnit.Value() != nil { + structMap["interval_unit"] = c.IntervalUnit.Value().toMap() + } else { + structMap["interval_unit"] = nil + } + } + if c.CurrencyPrices != nil { + structMap["currency_prices"] = c.CurrencyPrices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePoint. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePoint. // It customizes the JSON unmarshaling process for ComponentPricePoint objects. func (c *ComponentPricePoint) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Type *PricePointType `json:"type,omitempty"` - Default *bool `json:"default,omitempty"` - Name *string `json:"name,omitempty"` - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - Handle *string `json:"handle,omitempty"` - ArchivedAt Optional[string] `json:"archived_at"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - Prices []ComponentPrice `json:"prices,omitempty"` - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - TaxIncluded *bool `json:"tax_included,omitempty"` - Interval Optional[int] `json:"interval"` - IntervalUnit Optional[IntervalUnit] `json:"interval_unit"` - CurrencyPrices []ComponentCurrencyPrice `json:"currency_prices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Id = temp.Id - c.Type = temp.Type - c.Default = temp.Default - c.Name = temp.Name - c.PricingScheme = temp.PricingScheme - c.ComponentId = temp.ComponentId - c.Handle = temp.Handle - c.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) - if temp.ArchivedAt.Value() != nil { - ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) - } - c.ArchivedAt.SetValue(&ArchivedAtVal) - } - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - c.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - c.UpdatedAt = &UpdatedAtVal - } - c.Prices = temp.Prices - c.UseSiteExchangeRate = temp.UseSiteExchangeRate - c.SubscriptionId = temp.SubscriptionId - c.TaxIncluded = temp.TaxIncluded - c.Interval = temp.Interval - c.IntervalUnit = temp.IntervalUnit - c.CurrencyPrices = temp.CurrencyPrices - return nil + var temp componentPricePoint + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Id = temp.Id + c.Type = temp.Type + c.Default = temp.Default + c.Name = temp.Name + c.PricingScheme = temp.PricingScheme + c.ComponentId = temp.ComponentId + c.Handle = temp.Handle + c.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) + if temp.ArchivedAt.Value() != nil { + ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) + } + c.ArchivedAt.SetValue(&ArchivedAtVal) + } + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + c.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + c.UpdatedAt = &UpdatedAtVal + } + c.Prices = temp.Prices + c.UseSiteExchangeRate = temp.UseSiteExchangeRate + c.SubscriptionId = temp.SubscriptionId + c.TaxIncluded = temp.TaxIncluded + c.Interval = temp.Interval + c.IntervalUnit = temp.IntervalUnit + c.CurrencyPrices = temp.CurrencyPrices + return nil +} + +// TODO +type componentPricePoint struct { + Id *int `json:"id,omitempty"` + Type *PricePointType `json:"type,omitempty"` + Default *bool `json:"default,omitempty"` + Name *string `json:"name,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + Handle *string `json:"handle,omitempty"` + ArchivedAt Optional[string] `json:"archived_at"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + Prices []ComponentPrice `json:"prices,omitempty"` + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + TaxIncluded *bool `json:"tax_included,omitempty"` + Interval Optional[int] `json:"interval"` + IntervalUnit Optional[ComponentPricePointIntervalUnit] `json:"interval_unit"` + CurrencyPrices []ComponentCurrencyPrice `json:"currency_prices,omitempty"` } diff --git a/models/component_price_point_assignment.go b/models/component_price_point_assignment.go index 745266ca..c2841abc 100644 --- a/models/component_price_point_assignment.go +++ b/models/component_price_point_assignment.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // ComponentPricePointAssignment represents a ComponentPricePointAssignment struct. type ComponentPricePointAssignment struct { - ComponentId *int `json:"component_id,omitempty"` - PricePoint *interface{} `json:"price_point,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + PricePoint *ComponentPricePointAssignmentPricePoint `json:"price_point,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ComponentPricePointAssignment. +// MarshalJSON implements the json.Marshaler interface for ComponentPricePointAssignment. // It customizes the JSON marshaling process for ComponentPricePointAssignment objects. func (c *ComponentPricePointAssignment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentPricePointAssignment object to a map representation for JSON marshaling. func (c *ComponentPricePointAssignment) toMap() map[string]any { - structMap := make(map[string]any) - if c.ComponentId != nil { - structMap["component_id"] = c.ComponentId - } - if c.PricePoint != nil { - structMap["price_point"] = c.PricePoint - } - return structMap + structMap := make(map[string]any) + if c.ComponentId != nil { + structMap["component_id"] = c.ComponentId + } + if c.PricePoint != nil { + structMap["price_point"] = c.PricePoint.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointAssignment. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointAssignment. // It customizes the JSON unmarshaling process for ComponentPricePointAssignment objects. func (c *ComponentPricePointAssignment) UnmarshalJSON(input []byte) error { - temp := &struct { - ComponentId *int `json:"component_id,omitempty"` - PricePoint *interface{} `json:"price_point,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ComponentId = temp.ComponentId - c.PricePoint = temp.PricePoint - return nil + var temp componentPricePointAssignment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.ComponentId = temp.ComponentId + c.PricePoint = temp.PricePoint + return nil +} + +// TODO +type componentPricePointAssignment struct { + ComponentId *int `json:"component_id,omitempty"` + PricePoint *ComponentPricePointAssignmentPricePoint `json:"price_point,omitempty"` } diff --git a/models/component_price_point_assignment_price_point.go b/models/component_price_point_assignment_price_point.go new file mode 100644 index 00000000..98cac069 --- /dev/null +++ b/models/component_price_point_assignment_price_point.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ComponentPricePointAssignmentPricePoint represents a ComponentPricePointAssignmentPricePoint struct. +// This is a container for one-of cases. +type ComponentPricePointAssignmentPricePoint struct { + value any + isString bool + isNumber bool +} + +// String converts the ComponentPricePointAssignmentPricePoint object to a string representation. +func (c ComponentPricePointAssignmentPricePoint) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ComponentPricePointAssignmentPricePoint. +// It customizes the JSON marshaling process for ComponentPricePointAssignmentPricePoint objects. +func (c *ComponentPricePointAssignmentPricePoint) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ComponentPricePointAssignmentPricePointContainer.From*` functions to initialize the ComponentPricePointAssignmentPricePoint object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the ComponentPricePointAssignmentPricePoint object to a map representation for JSON marshaling. +func (c *ComponentPricePointAssignmentPricePoint) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointAssignmentPricePoint. +// It customizes the JSON unmarshaling process for ComponentPricePointAssignmentPricePoint objects. +func (c *ComponentPricePointAssignmentPricePoint) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(int), false, &c.isNumber), + ) + + c.value = result + return err +} + +func (c *ComponentPricePointAssignmentPricePoint) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *ComponentPricePointAssignmentPricePoint) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +// internalComponentPricePointAssignmentPricePoint represents a componentPricePointAssignmentPricePoint struct. +// This is a container for one-of cases. +type internalComponentPricePointAssignmentPricePoint struct{} + +var ComponentPricePointAssignmentPricePointContainer internalComponentPricePointAssignmentPricePoint + +func (c *internalComponentPricePointAssignmentPricePoint) FromString(val string) ComponentPricePointAssignmentPricePoint { + return ComponentPricePointAssignmentPricePoint{value: &val} +} + +func (c *internalComponentPricePointAssignmentPricePoint) FromNumber(val int) ComponentPricePointAssignmentPricePoint { + return ComponentPricePointAssignmentPricePoint{value: &val} +} diff --git a/models/component_price_point_error_item.go b/models/component_price_point_error_item.go index d75a82e4..5c76c9d7 100644 --- a/models/component_price_point_error_item.go +++ b/models/component_price_point_error_item.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // ComponentPricePointErrorItem represents a ComponentPricePointErrorItem struct. type ComponentPricePointErrorItem struct { - ComponentId *int `json:"component_id,omitempty"` - Message *string `json:"message,omitempty"` - PricePoint *int `json:"price_point,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + Message *string `json:"message,omitempty"` + PricePoint *int `json:"price_point,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ComponentPricePointErrorItem. +// MarshalJSON implements the json.Marshaler interface for ComponentPricePointErrorItem. // It customizes the JSON marshaling process for ComponentPricePointErrorItem objects. func (c *ComponentPricePointErrorItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentPricePointErrorItem object to a map representation for JSON marshaling. func (c *ComponentPricePointErrorItem) toMap() map[string]any { - structMap := make(map[string]any) - if c.ComponentId != nil { - structMap["component_id"] = c.ComponentId - } - if c.Message != nil { - structMap["message"] = c.Message - } - if c.PricePoint != nil { - structMap["price_point"] = c.PricePoint - } - return structMap + structMap := make(map[string]any) + if c.ComponentId != nil { + structMap["component_id"] = c.ComponentId + } + if c.Message != nil { + structMap["message"] = c.Message + } + if c.PricePoint != nil { + structMap["price_point"] = c.PricePoint + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointErrorItem. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointErrorItem. // It customizes the JSON unmarshaling process for ComponentPricePointErrorItem objects. func (c *ComponentPricePointErrorItem) UnmarshalJSON(input []byte) error { - temp := &struct { - ComponentId *int `json:"component_id,omitempty"` - Message *string `json:"message,omitempty"` - PricePoint *int `json:"price_point,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ComponentId = temp.ComponentId - c.Message = temp.Message - c.PricePoint = temp.PricePoint - return nil + var temp componentPricePointErrorItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.ComponentId = temp.ComponentId + c.Message = temp.Message + c.PricePoint = temp.PricePoint + return nil +} + +// TODO +type componentPricePointErrorItem struct { + ComponentId *int `json:"component_id,omitempty"` + Message *string `json:"message,omitempty"` + PricePoint *int `json:"price_point,omitempty"` } diff --git a/models/component_price_point_interval_unit.go b/models/component_price_point_interval_unit.go new file mode 100644 index 00000000..52b9c615 --- /dev/null +++ b/models/component_price_point_interval_unit.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ComponentPricePointIntervalUnit represents a ComponentPricePointIntervalUnit struct. +// This is a container for one-of cases. +type ComponentPricePointIntervalUnit struct { + value any + isIntervalUnit bool +} + +// String converts the ComponentPricePointIntervalUnit object to a string representation. +func (c ComponentPricePointIntervalUnit) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ComponentPricePointIntervalUnit. +// It customizes the JSON marshaling process for ComponentPricePointIntervalUnit objects. +func (c *ComponentPricePointIntervalUnit) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ComponentPricePointIntervalUnitContainer.From*` functions to initialize the ComponentPricePointIntervalUnit object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the ComponentPricePointIntervalUnit object to a map representation for JSON marshaling. +func (c *ComponentPricePointIntervalUnit) toMap() any { + switch obj := c.value.(type) { + case *IntervalUnit: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointIntervalUnit. +// It customizes the JSON unmarshaling process for ComponentPricePointIntervalUnit objects. +func (c *ComponentPricePointIntervalUnit) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(IntervalUnit), false, &c.isIntervalUnit), + ) + + c.value = result + return err +} + +func (c *ComponentPricePointIntervalUnit) AsIntervalUnit() ( + *IntervalUnit, + bool) { + if !c.isIntervalUnit { + return nil, false + } + return c.value.(*IntervalUnit), true +} + +// internalComponentPricePointIntervalUnit represents a componentPricePointIntervalUnit struct. +// This is a container for one-of cases. +type internalComponentPricePointIntervalUnit struct{} + +var ComponentPricePointIntervalUnitContainer internalComponentPricePointIntervalUnit + +func (c *internalComponentPricePointIntervalUnit) FromIntervalUnit(val IntervalUnit) ComponentPricePointIntervalUnit { + return ComponentPricePointIntervalUnit{value: &val} +} diff --git a/models/component_price_point_item.go b/models/component_price_point_item.go index 077e40ec..eb517781 100644 --- a/models/component_price_point_item.go +++ b/models/component_price_point_item.go @@ -1,75 +1,77 @@ package models import ( - "encoding/json" + "encoding/json" ) // ComponentPricePointItem represents a ComponentPricePointItem struct. type ComponentPricePointItem struct { - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - Prices []Price `json:"prices,omitempty"` + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + Prices []Price `json:"prices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ComponentPricePointItem. +// MarshalJSON implements the json.Marshaler interface for ComponentPricePointItem. // It customizes the JSON marshaling process for ComponentPricePointItem objects. func (c *ComponentPricePointItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentPricePointItem object to a map representation for JSON marshaling. func (c *ComponentPricePointItem) toMap() map[string]any { - structMap := make(map[string]any) - if c.Name != nil { - structMap["name"] = c.Name - } - if c.Handle != nil { - structMap["handle"] = c.Handle - } - if c.PricingScheme != nil { - structMap["pricing_scheme"] = c.PricingScheme - } - if c.Interval != nil { - structMap["interval"] = c.Interval - } - if c.IntervalUnit != nil { - structMap["interval_unit"] = c.IntervalUnit - } - if c.Prices != nil { - structMap["prices"] = c.Prices - } - return structMap + structMap := make(map[string]any) + if c.Name != nil { + structMap["name"] = c.Name + } + if c.Handle != nil { + structMap["handle"] = c.Handle + } + if c.PricingScheme != nil { + structMap["pricing_scheme"] = c.PricingScheme + } + if c.Interval != nil { + structMap["interval"] = c.Interval + } + if c.IntervalUnit != nil { + structMap["interval_unit"] = c.IntervalUnit + } + if c.Prices != nil { + structMap["prices"] = c.Prices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointItem. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointItem. // It customizes the JSON unmarshaling process for ComponentPricePointItem objects. func (c *ComponentPricePointItem) UnmarshalJSON(input []byte) error { - temp := &struct { - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - Prices []Price `json:"prices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Name = temp.Name - c.Handle = temp.Handle - c.PricingScheme = temp.PricingScheme - c.Interval = temp.Interval - c.IntervalUnit = temp.IntervalUnit - c.Prices = temp.Prices - return nil + var temp componentPricePointItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Name = temp.Name + c.Handle = temp.Handle + c.PricingScheme = temp.PricingScheme + c.Interval = temp.Interval + c.IntervalUnit = temp.IntervalUnit + c.Prices = temp.Prices + return nil +} + +// TODO +type componentPricePointItem struct { + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + Prices []Price `json:"prices,omitempty"` } diff --git a/models/component_price_point_response.go b/models/component_price_point_response.go index 779af37c..0c19f511 100644 --- a/models/component_price_point_response.go +++ b/models/component_price_point_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ComponentPricePointResponse represents a ComponentPricePointResponse struct. type ComponentPricePointResponse struct { - PricePoint ComponentPricePoint `json:"price_point"` + PricePoint ComponentPricePoint `json:"price_point"` } -// MarshalJSON implements the json.Marshaler interface for ComponentPricePointResponse. +// MarshalJSON implements the json.Marshaler interface for ComponentPricePointResponse. // It customizes the JSON marshaling process for ComponentPricePointResponse objects. func (c *ComponentPricePointResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentPricePointResponse object to a map representation for JSON marshaling. func (c *ComponentPricePointResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["price_point"] = c.PricePoint.toMap() - return structMap + structMap := make(map[string]any) + structMap["price_point"] = c.PricePoint.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointResponse. // It customizes the JSON unmarshaling process for ComponentPricePointResponse objects. func (c *ComponentPricePointResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoint ComponentPricePoint `json:"price_point"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.PricePoint = temp.PricePoint - return nil + var temp componentPricePointResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.PricePoint = *temp.PricePoint + return nil +} + +// TODO +type componentPricePointResponse struct { + PricePoint *ComponentPricePoint `json:"price_point"` +} + +func (c *componentPricePointResponse) validate() error { + var errs []string + if c.PricePoint == nil { + errs = append(errs, "required field `price_point` is missing for type `Component Price Point Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/component_price_points_response.go b/models/component_price_points_response.go index 592a4fc0..959a8e61 100644 --- a/models/component_price_points_response.go +++ b/models/component_price_points_response.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // ComponentPricePointsResponse represents a ComponentPricePointsResponse struct. type ComponentPricePointsResponse struct { - PricePoints []ComponentPricePoint `json:"price_points,omitempty"` - Meta *ListPublicKeysMeta `json:"meta,omitempty"` + PricePoints []ComponentPricePoint `json:"price_points,omitempty"` + Meta *ListPublicKeysMeta `json:"meta,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ComponentPricePointsResponse. +// MarshalJSON implements the json.Marshaler interface for ComponentPricePointsResponse. // It customizes the JSON marshaling process for ComponentPricePointsResponse objects. func (c *ComponentPricePointsResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentPricePointsResponse object to a map representation for JSON marshaling. func (c *ComponentPricePointsResponse) toMap() map[string]any { - structMap := make(map[string]any) - if c.PricePoints != nil { - structMap["price_points"] = c.PricePoints - } - if c.Meta != nil { - structMap["meta"] = c.Meta.toMap() - } - return structMap + structMap := make(map[string]any) + if c.PricePoints != nil { + structMap["price_points"] = c.PricePoints + } + if c.Meta != nil { + structMap["meta"] = c.Meta.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointsResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricePointsResponse. // It customizes the JSON unmarshaling process for ComponentPricePointsResponse objects. func (c *ComponentPricePointsResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoints []ComponentPricePoint `json:"price_points,omitempty"` - Meta *ListPublicKeysMeta `json:"meta,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.PricePoints = temp.PricePoints - c.Meta = temp.Meta - return nil + var temp componentPricePointsResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.PricePoints = temp.PricePoints + c.Meta = temp.Meta + return nil +} + +// TODO +type componentPricePointsResponse struct { + PricePoints []ComponentPricePoint `json:"price_points,omitempty"` + Meta *ListPublicKeysMeta `json:"meta,omitempty"` } diff --git a/models/component_pricing_scheme.go b/models/component_pricing_scheme.go new file mode 100644 index 00000000..b146845c --- /dev/null +++ b/models/component_pricing_scheme.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ComponentPricingScheme represents a ComponentPricingScheme struct. +// This is a container for one-of cases. +type ComponentPricingScheme struct { + value any + isPricingScheme bool +} + +// String converts the ComponentPricingScheme object to a string representation. +func (c ComponentPricingScheme) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ComponentPricingScheme. +// It customizes the JSON marshaling process for ComponentPricingScheme objects. +func (c *ComponentPricingScheme) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ComponentPricingSchemeContainer.From*` functions to initialize the ComponentPricingScheme object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the ComponentPricingScheme object to a map representation for JSON marshaling. +func (c *ComponentPricingScheme) toMap() any { + switch obj := c.value.(type) { + case *PricingScheme: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentPricingScheme. +// It customizes the JSON unmarshaling process for ComponentPricingScheme objects. +func (c *ComponentPricingScheme) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(PricingScheme), false, &c.isPricingScheme), + ) + + c.value = result + return err +} + +func (c *ComponentPricingScheme) AsPricingScheme() ( + *PricingScheme, + bool) { + if !c.isPricingScheme { + return nil, false + } + return c.value.(*PricingScheme), true +} + +// internalComponentPricingScheme represents a componentPricingScheme struct. +// This is a container for one-of cases. +type internalComponentPricingScheme struct{} + +var ComponentPricingSchemeContainer internalComponentPricingScheme + +func (c *internalComponentPricingScheme) FromPricingScheme(val PricingScheme) ComponentPricingScheme { + return ComponentPricingScheme{value: &val} +} diff --git a/models/component_response.go b/models/component_response.go index 258cf936..af76facf 100644 --- a/models/component_response.go +++ b/models/component_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ComponentResponse represents a ComponentResponse struct. type ComponentResponse struct { - Component Component `json:"component"` + Component Component `json:"component"` } -// MarshalJSON implements the json.Marshaler interface for ComponentResponse. +// MarshalJSON implements the json.Marshaler interface for ComponentResponse. // It customizes the JSON marshaling process for ComponentResponse objects. func (c *ComponentResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ComponentResponse object to a map representation for JSON marshaling. func (c *ComponentResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["component"] = c.Component.toMap() - return structMap + structMap := make(map[string]any) + structMap["component"] = c.Component.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ComponentResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ComponentResponse. // It customizes the JSON unmarshaling process for ComponentResponse objects. func (c *ComponentResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Component Component `json:"component"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Component = temp.Component - return nil + var temp componentResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Component = *temp.Component + return nil +} + +// TODO +type componentResponse struct { + Component *Component `json:"component"` +} + +func (c *componentResponse) validate() error { + var errs []string + if c.Component == nil { + errs = append(errs, "required field `component` is missing for type `Component Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/consolidated_invoice.go b/models/consolidated_invoice.go index ce90d3c9..dad363a2 100644 --- a/models/consolidated_invoice.go +++ b/models/consolidated_invoice.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // ConsolidatedInvoice represents a ConsolidatedInvoice struct. type ConsolidatedInvoice struct { - Invoices []Invoice `json:"invoices,omitempty"` + Invoices []Invoice `json:"invoices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ConsolidatedInvoice. +// MarshalJSON implements the json.Marshaler interface for ConsolidatedInvoice. // It customizes the JSON marshaling process for ConsolidatedInvoice objects. func (c *ConsolidatedInvoice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the ConsolidatedInvoice object to a map representation for JSON marshaling. func (c *ConsolidatedInvoice) toMap() map[string]any { - structMap := make(map[string]any) - if c.Invoices != nil { - structMap["invoices"] = c.Invoices - } - return structMap + structMap := make(map[string]any) + if c.Invoices != nil { + structMap["invoices"] = c.Invoices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ConsolidatedInvoice. +// UnmarshalJSON implements the json.Unmarshaler interface for ConsolidatedInvoice. // It customizes the JSON unmarshaling process for ConsolidatedInvoice objects. func (c *ConsolidatedInvoice) UnmarshalJSON(input []byte) error { - temp := &struct { - Invoices []Invoice `json:"invoices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Invoices = temp.Invoices - return nil + var temp consolidatedInvoice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Invoices = temp.Invoices + return nil +} + +// TODO +type consolidatedInvoice struct { + Invoices []Invoice `json:"invoices,omitempty"` } diff --git a/models/count_response.go b/models/count_response.go index 09cf7dbd..adab125d 100644 --- a/models/count_response.go +++ b/models/count_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // CountResponse represents a CountResponse struct. type CountResponse struct { - Count *int `json:"count,omitempty"` + Count *int `json:"count,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CountResponse. +// MarshalJSON implements the json.Marshaler interface for CountResponse. // It customizes the JSON marshaling process for CountResponse objects. func (c *CountResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CountResponse object to a map representation for JSON marshaling. func (c *CountResponse) toMap() map[string]any { - structMap := make(map[string]any) - if c.Count != nil { - structMap["count"] = c.Count - } - return structMap + structMap := make(map[string]any) + if c.Count != nil { + structMap["count"] = c.Count + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CountResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for CountResponse. // It customizes the JSON unmarshaling process for CountResponse objects. func (c *CountResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Count *int `json:"count,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Count = temp.Count - return nil + var temp countResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Count = temp.Count + return nil +} + +// TODO +type countResponse struct { + Count *int `json:"count,omitempty"` } diff --git a/models/coupon.go b/models/coupon.go index 1de8ce6e..c900b3ff 100644 --- a/models/coupon.go +++ b/models/coupon.go @@ -1,260 +1,306 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Coupon represents a Coupon struct. type Coupon struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Code *string `json:"code,omitempty"` - Description *string `json:"description,omitempty"` - Amount Optional[float64] `json:"amount"` - AmountInCents Optional[int] `json:"amount_in_cents"` - ProductFamilyId *int `json:"product_family_id,omitempty"` - ProductFamilyName Optional[string] `json:"product_family_name"` - StartDate *time.Time `json:"start_date,omitempty"` - EndDate Optional[time.Time] `json:"end_date"` - Percentage Optional[string] `json:"percentage"` - Recurring *bool `json:"recurring,omitempty"` - RecurringScheme *RecurringScheme `json:"recurring_scheme,omitempty"` - DurationPeriodCount Optional[int] `json:"duration_period_count"` - DurationInterval Optional[int] `json:"duration_interval"` - DurationIntervalUnit Optional[string] `json:"duration_interval_unit"` - DurationIntervalSpan Optional[string] `json:"duration_interval_span"` - AllowNegativeBalance *bool `json:"allow_negative_balance,omitempty"` - ArchivedAt Optional[time.Time] `json:"archived_at"` - ConversionLimit Optional[string] `json:"conversion_limit"` - Stackable *bool `json:"stackable,omitempty"` - CompoundingStrategy *interface{} `json:"compounding_strategy,omitempty"` - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - DiscountType *DiscountType `json:"discount_type,omitempty"` - ExcludeMidPeriodAllocations *bool `json:"exclude_mid_period_allocations,omitempty"` - ApplyOnCancelAtEndOfPeriod *bool `json:"apply_on_cancel_at_end_of_period,omitempty"` - ApplyOnSubscriptionExpiration *bool `json:"apply_on_subscription_expiration,omitempty"` - CouponRestrictions []CouponRestriction `json:"coupon_restrictions,omitempty"` + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Code *string `json:"code,omitempty"` + Description *string `json:"description,omitempty"` + Amount Optional[float64] `json:"amount"` + AmountInCents Optional[int] `json:"amount_in_cents"` + ProductFamilyId *int `json:"product_family_id,omitempty"` + ProductFamilyName Optional[string] `json:"product_family_name"` + StartDate *time.Time `json:"start_date,omitempty"` + EndDate Optional[time.Time] `json:"end_date"` + Percentage Optional[string] `json:"percentage"` + Recurring *bool `json:"recurring,omitempty"` + RecurringScheme *RecurringScheme `json:"recurring_scheme,omitempty"` + DurationPeriodCount Optional[int] `json:"duration_period_count"` + DurationInterval Optional[int] `json:"duration_interval"` + DurationIntervalUnit Optional[string] `json:"duration_interval_unit"` + DurationIntervalSpan Optional[string] `json:"duration_interval_span"` + AllowNegativeBalance *bool `json:"allow_negative_balance,omitempty"` + ArchivedAt Optional[time.Time] `json:"archived_at"` + ConversionLimit Optional[string] `json:"conversion_limit"` + Stackable *bool `json:"stackable,omitempty"` + CompoundingStrategy *CouponCompoundingStrategy `json:"compounding_strategy,omitempty"` + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + DiscountType *DiscountType `json:"discount_type,omitempty"` + ExcludeMidPeriodAllocations *bool `json:"exclude_mid_period_allocations,omitempty"` + ApplyOnCancelAtEndOfPeriod *bool `json:"apply_on_cancel_at_end_of_period,omitempty"` + ApplyOnSubscriptionExpiration *bool `json:"apply_on_subscription_expiration,omitempty"` + CouponRestrictions []CouponRestriction `json:"coupon_restrictions,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Coupon. +// MarshalJSON implements the json.Marshaler interface for Coupon. // It customizes the JSON marshaling process for Coupon objects. func (c *Coupon) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the Coupon object to a map representation for JSON marshaling. func (c *Coupon) toMap() map[string]any { - structMap := make(map[string]any) - if c.Id != nil { - structMap["id"] = c.Id - } - if c.Name != nil { - structMap["name"] = c.Name - } - if c.Code != nil { - structMap["code"] = c.Code - } - if c.Description != nil { - structMap["description"] = c.Description - } - if c.Amount.IsValueSet() { - structMap["amount"] = c.Amount.Value() - } - if c.AmountInCents.IsValueSet() { - structMap["amount_in_cents"] = c.AmountInCents.Value() - } - if c.ProductFamilyId != nil { - structMap["product_family_id"] = c.ProductFamilyId - } - if c.ProductFamilyName.IsValueSet() { - structMap["product_family_name"] = c.ProductFamilyName.Value() - } - if c.StartDate != nil { - structMap["start_date"] = c.StartDate.Format(time.RFC3339) - } - if c.EndDate.IsValueSet() { - var EndDateVal *string = nil - if c.EndDate.Value() != nil { - val := c.EndDate.Value().Format(time.RFC3339) - EndDateVal = &val - } - structMap["end_date"] = EndDateVal - } - if c.Percentage.IsValueSet() { - structMap["percentage"] = c.Percentage.Value() - } - if c.Recurring != nil { - structMap["recurring"] = c.Recurring - } - if c.RecurringScheme != nil { - structMap["recurring_scheme"] = c.RecurringScheme - } - if c.DurationPeriodCount.IsValueSet() { - structMap["duration_period_count"] = c.DurationPeriodCount.Value() - } - if c.DurationInterval.IsValueSet() { - structMap["duration_interval"] = c.DurationInterval.Value() - } - if c.DurationIntervalUnit.IsValueSet() { - structMap["duration_interval_unit"] = c.DurationIntervalUnit.Value() - } - if c.DurationIntervalSpan.IsValueSet() { - structMap["duration_interval_span"] = c.DurationIntervalSpan.Value() - } - if c.AllowNegativeBalance != nil { - structMap["allow_negative_balance"] = c.AllowNegativeBalance - } - if c.ArchivedAt.IsValueSet() { - var ArchivedAtVal *string = nil - if c.ArchivedAt.Value() != nil { - val := c.ArchivedAt.Value().Format(time.RFC3339) - ArchivedAtVal = &val - } - structMap["archived_at"] = ArchivedAtVal - } - if c.ConversionLimit.IsValueSet() { - structMap["conversion_limit"] = c.ConversionLimit.Value() - } - if c.Stackable != nil { - structMap["stackable"] = c.Stackable - } - if c.CompoundingStrategy != nil { - structMap["compounding_strategy"] = c.CompoundingStrategy - } - if c.UseSiteExchangeRate != nil { - structMap["use_site_exchange_rate"] = c.UseSiteExchangeRate - } - if c.CreatedAt != nil { - structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) - } - if c.UpdatedAt != nil { - structMap["updated_at"] = c.UpdatedAt.Format(time.RFC3339) - } - if c.DiscountType != nil { - structMap["discount_type"] = c.DiscountType - } - if c.ExcludeMidPeriodAllocations != nil { - structMap["exclude_mid_period_allocations"] = c.ExcludeMidPeriodAllocations - } - if c.ApplyOnCancelAtEndOfPeriod != nil { - structMap["apply_on_cancel_at_end_of_period"] = c.ApplyOnCancelAtEndOfPeriod - } - if c.ApplyOnSubscriptionExpiration != nil { - structMap["apply_on_subscription_expiration"] = c.ApplyOnSubscriptionExpiration - } - if c.CouponRestrictions != nil { - structMap["coupon_restrictions"] = c.CouponRestrictions - } - return structMap + structMap := make(map[string]any) + if c.Id != nil { + structMap["id"] = c.Id + } + if c.Name != nil { + structMap["name"] = c.Name + } + if c.Code != nil { + structMap["code"] = c.Code + } + if c.Description != nil { + structMap["description"] = c.Description + } + if c.Amount.IsValueSet() { + if c.Amount.Value() != nil { + structMap["amount"] = c.Amount.Value() + } else { + structMap["amount"] = nil + } + } + if c.AmountInCents.IsValueSet() { + if c.AmountInCents.Value() != nil { + structMap["amount_in_cents"] = c.AmountInCents.Value() + } else { + structMap["amount_in_cents"] = nil + } + } + if c.ProductFamilyId != nil { + structMap["product_family_id"] = c.ProductFamilyId + } + if c.ProductFamilyName.IsValueSet() { + if c.ProductFamilyName.Value() != nil { + structMap["product_family_name"] = c.ProductFamilyName.Value() + } else { + structMap["product_family_name"] = nil + } + } + if c.StartDate != nil { + structMap["start_date"] = c.StartDate.Format(time.RFC3339) + } + if c.EndDate.IsValueSet() { + var EndDateVal *string = nil + if c.EndDate.Value() != nil { + val := c.EndDate.Value().Format(time.RFC3339) + EndDateVal = &val + } + if c.EndDate.Value() != nil { + structMap["end_date"] = EndDateVal + } else { + structMap["end_date"] = nil + } + } + if c.Percentage.IsValueSet() { + if c.Percentage.Value() != nil { + structMap["percentage"] = c.Percentage.Value() + } else { + structMap["percentage"] = nil + } + } + if c.Recurring != nil { + structMap["recurring"] = c.Recurring + } + if c.RecurringScheme != nil { + structMap["recurring_scheme"] = c.RecurringScheme + } + if c.DurationPeriodCount.IsValueSet() { + if c.DurationPeriodCount.Value() != nil { + structMap["duration_period_count"] = c.DurationPeriodCount.Value() + } else { + structMap["duration_period_count"] = nil + } + } + if c.DurationInterval.IsValueSet() { + if c.DurationInterval.Value() != nil { + structMap["duration_interval"] = c.DurationInterval.Value() + } else { + structMap["duration_interval"] = nil + } + } + if c.DurationIntervalUnit.IsValueSet() { + if c.DurationIntervalUnit.Value() != nil { + structMap["duration_interval_unit"] = c.DurationIntervalUnit.Value() + } else { + structMap["duration_interval_unit"] = nil + } + } + if c.DurationIntervalSpan.IsValueSet() { + if c.DurationIntervalSpan.Value() != nil { + structMap["duration_interval_span"] = c.DurationIntervalSpan.Value() + } else { + structMap["duration_interval_span"] = nil + } + } + if c.AllowNegativeBalance != nil { + structMap["allow_negative_balance"] = c.AllowNegativeBalance + } + if c.ArchivedAt.IsValueSet() { + var ArchivedAtVal *string = nil + if c.ArchivedAt.Value() != nil { + val := c.ArchivedAt.Value().Format(time.RFC3339) + ArchivedAtVal = &val + } + if c.ArchivedAt.Value() != nil { + structMap["archived_at"] = ArchivedAtVal + } else { + structMap["archived_at"] = nil + } + } + if c.ConversionLimit.IsValueSet() { + if c.ConversionLimit.Value() != nil { + structMap["conversion_limit"] = c.ConversionLimit.Value() + } else { + structMap["conversion_limit"] = nil + } + } + if c.Stackable != nil { + structMap["stackable"] = c.Stackable + } + if c.CompoundingStrategy != nil { + structMap["compounding_strategy"] = c.CompoundingStrategy.toMap() + } + if c.UseSiteExchangeRate != nil { + structMap["use_site_exchange_rate"] = c.UseSiteExchangeRate + } + if c.CreatedAt != nil { + structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) + } + if c.UpdatedAt != nil { + structMap["updated_at"] = c.UpdatedAt.Format(time.RFC3339) + } + if c.DiscountType != nil { + structMap["discount_type"] = c.DiscountType + } + if c.ExcludeMidPeriodAllocations != nil { + structMap["exclude_mid_period_allocations"] = c.ExcludeMidPeriodAllocations + } + if c.ApplyOnCancelAtEndOfPeriod != nil { + structMap["apply_on_cancel_at_end_of_period"] = c.ApplyOnCancelAtEndOfPeriod + } + if c.ApplyOnSubscriptionExpiration != nil { + structMap["apply_on_subscription_expiration"] = c.ApplyOnSubscriptionExpiration + } + if c.CouponRestrictions != nil { + structMap["coupon_restrictions"] = c.CouponRestrictions + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Coupon. +// UnmarshalJSON implements the json.Unmarshaler interface for Coupon. // It customizes the JSON unmarshaling process for Coupon objects. func (c *Coupon) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Code *string `json:"code,omitempty"` - Description *string `json:"description,omitempty"` - Amount Optional[float64] `json:"amount"` - AmountInCents Optional[int] `json:"amount_in_cents"` - ProductFamilyId *int `json:"product_family_id,omitempty"` - ProductFamilyName Optional[string] `json:"product_family_name"` - StartDate *string `json:"start_date,omitempty"` - EndDate Optional[string] `json:"end_date"` - Percentage Optional[string] `json:"percentage"` - Recurring *bool `json:"recurring,omitempty"` - RecurringScheme *RecurringScheme `json:"recurring_scheme,omitempty"` - DurationPeriodCount Optional[int] `json:"duration_period_count"` - DurationInterval Optional[int] `json:"duration_interval"` - DurationIntervalUnit Optional[string] `json:"duration_interval_unit"` - DurationIntervalSpan Optional[string] `json:"duration_interval_span"` - AllowNegativeBalance *bool `json:"allow_negative_balance,omitempty"` - ArchivedAt Optional[string] `json:"archived_at"` - ConversionLimit Optional[string] `json:"conversion_limit"` - Stackable *bool `json:"stackable,omitempty"` - CompoundingStrategy *interface{} `json:"compounding_strategy,omitempty"` - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - DiscountType *DiscountType `json:"discount_type,omitempty"` - ExcludeMidPeriodAllocations *bool `json:"exclude_mid_period_allocations,omitempty"` - ApplyOnCancelAtEndOfPeriod *bool `json:"apply_on_cancel_at_end_of_period,omitempty"` - ApplyOnSubscriptionExpiration *bool `json:"apply_on_subscription_expiration,omitempty"` - CouponRestrictions []CouponRestriction `json:"coupon_restrictions,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Id = temp.Id - c.Name = temp.Name - c.Code = temp.Code - c.Description = temp.Description - c.Amount = temp.Amount - c.AmountInCents = temp.AmountInCents - c.ProductFamilyId = temp.ProductFamilyId - c.ProductFamilyName = temp.ProductFamilyName - if temp.StartDate != nil { - StartDateVal, err := time.Parse(time.RFC3339, *temp.StartDate) - if err != nil { - log.Fatalf("Cannot Parse start_date as % s format.", time.RFC3339) - } - c.StartDate = &StartDateVal - } - c.EndDate.ShouldSetValue(temp.EndDate.IsValueSet()) - if temp.EndDate.Value() != nil { - EndDateVal, err := time.Parse(time.RFC3339, (*temp.EndDate.Value())) - if err != nil { - log.Fatalf("Cannot Parse end_date as % s format.", time.RFC3339) - } - c.EndDate.SetValue(&EndDateVal) - } - c.Percentage = temp.Percentage - c.Recurring = temp.Recurring - c.RecurringScheme = temp.RecurringScheme - c.DurationPeriodCount = temp.DurationPeriodCount - c.DurationInterval = temp.DurationInterval - c.DurationIntervalUnit = temp.DurationIntervalUnit - c.DurationIntervalSpan = temp.DurationIntervalSpan - c.AllowNegativeBalance = temp.AllowNegativeBalance - c.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) - if temp.ArchivedAt.Value() != nil { - ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) - } - c.ArchivedAt.SetValue(&ArchivedAtVal) - } - c.ConversionLimit = temp.ConversionLimit - c.Stackable = temp.Stackable - c.CompoundingStrategy = temp.CompoundingStrategy - c.UseSiteExchangeRate = temp.UseSiteExchangeRate - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - c.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - c.UpdatedAt = &UpdatedAtVal - } - c.DiscountType = temp.DiscountType - c.ExcludeMidPeriodAllocations = temp.ExcludeMidPeriodAllocations - c.ApplyOnCancelAtEndOfPeriod = temp.ApplyOnCancelAtEndOfPeriod - c.ApplyOnSubscriptionExpiration = temp.ApplyOnSubscriptionExpiration - c.CouponRestrictions = temp.CouponRestrictions - return nil + var temp coupon + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Id = temp.Id + c.Name = temp.Name + c.Code = temp.Code + c.Description = temp.Description + c.Amount = temp.Amount + c.AmountInCents = temp.AmountInCents + c.ProductFamilyId = temp.ProductFamilyId + c.ProductFamilyName = temp.ProductFamilyName + if temp.StartDate != nil { + StartDateVal, err := time.Parse(time.RFC3339, *temp.StartDate) + if err != nil { + log.Fatalf("Cannot Parse start_date as % s format.", time.RFC3339) + } + c.StartDate = &StartDateVal + } + c.EndDate.ShouldSetValue(temp.EndDate.IsValueSet()) + if temp.EndDate.Value() != nil { + EndDateVal, err := time.Parse(time.RFC3339, (*temp.EndDate.Value())) + if err != nil { + log.Fatalf("Cannot Parse end_date as % s format.", time.RFC3339) + } + c.EndDate.SetValue(&EndDateVal) + } + c.Percentage = temp.Percentage + c.Recurring = temp.Recurring + c.RecurringScheme = temp.RecurringScheme + c.DurationPeriodCount = temp.DurationPeriodCount + c.DurationInterval = temp.DurationInterval + c.DurationIntervalUnit = temp.DurationIntervalUnit + c.DurationIntervalSpan = temp.DurationIntervalSpan + c.AllowNegativeBalance = temp.AllowNegativeBalance + c.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) + if temp.ArchivedAt.Value() != nil { + ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) + } + c.ArchivedAt.SetValue(&ArchivedAtVal) + } + c.ConversionLimit = temp.ConversionLimit + c.Stackable = temp.Stackable + c.CompoundingStrategy = temp.CompoundingStrategy + c.UseSiteExchangeRate = temp.UseSiteExchangeRate + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + c.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + c.UpdatedAt = &UpdatedAtVal + } + c.DiscountType = temp.DiscountType + c.ExcludeMidPeriodAllocations = temp.ExcludeMidPeriodAllocations + c.ApplyOnCancelAtEndOfPeriod = temp.ApplyOnCancelAtEndOfPeriod + c.ApplyOnSubscriptionExpiration = temp.ApplyOnSubscriptionExpiration + c.CouponRestrictions = temp.CouponRestrictions + return nil +} + +// TODO +type coupon struct { + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Code *string `json:"code,omitempty"` + Description *string `json:"description,omitempty"` + Amount Optional[float64] `json:"amount"` + AmountInCents Optional[int] `json:"amount_in_cents"` + ProductFamilyId *int `json:"product_family_id,omitempty"` + ProductFamilyName Optional[string] `json:"product_family_name"` + StartDate *string `json:"start_date,omitempty"` + EndDate Optional[string] `json:"end_date"` + Percentage Optional[string] `json:"percentage"` + Recurring *bool `json:"recurring,omitempty"` + RecurringScheme *RecurringScheme `json:"recurring_scheme,omitempty"` + DurationPeriodCount Optional[int] `json:"duration_period_count"` + DurationInterval Optional[int] `json:"duration_interval"` + DurationIntervalUnit Optional[string] `json:"duration_interval_unit"` + DurationIntervalSpan Optional[string] `json:"duration_interval_span"` + AllowNegativeBalance *bool `json:"allow_negative_balance,omitempty"` + ArchivedAt Optional[string] `json:"archived_at"` + ConversionLimit Optional[string] `json:"conversion_limit"` + Stackable *bool `json:"stackable,omitempty"` + CompoundingStrategy *CouponCompoundingStrategy `json:"compounding_strategy,omitempty"` + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + DiscountType *DiscountType `json:"discount_type,omitempty"` + ExcludeMidPeriodAllocations *bool `json:"exclude_mid_period_allocations,omitempty"` + ApplyOnCancelAtEndOfPeriod *bool `json:"apply_on_cancel_at_end_of_period,omitempty"` + ApplyOnSubscriptionExpiration *bool `json:"apply_on_subscription_expiration,omitempty"` + CouponRestrictions []CouponRestriction `json:"coupon_restrictions,omitempty"` } diff --git a/models/coupon_compounding_strategy.go b/models/coupon_compounding_strategy.go new file mode 100644 index 00000000..738a2ea9 --- /dev/null +++ b/models/coupon_compounding_strategy.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CouponCompoundingStrategy represents a CouponCompoundingStrategy struct. +// This is a container for any-of cases. +type CouponCompoundingStrategy struct { + value any + isCompoundingStrategy bool +} + +// String converts the CouponCompoundingStrategy object to a string representation. +func (c CouponCompoundingStrategy) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CouponCompoundingStrategy. +// It customizes the JSON marshaling process for CouponCompoundingStrategy objects. +func (c *CouponCompoundingStrategy) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CouponCompoundingStrategyContainer.From*` functions to initialize the CouponCompoundingStrategy object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CouponCompoundingStrategy object to a map representation for JSON marshaling. +func (c *CouponCompoundingStrategy) toMap() any { + switch obj := c.value.(type) { + case *CompoundingStrategy: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CouponCompoundingStrategy. +// It customizes the JSON unmarshaling process for CouponCompoundingStrategy objects. +func (c *CouponCompoundingStrategy) UnmarshalJSON(input []byte) error { + result, err := UnmarshallAnyOf(input, + NewTypeHolder(new(CompoundingStrategy), false, &c.isCompoundingStrategy), + ) + + c.value = result + return err +} + +func (c *CouponCompoundingStrategy) AsCompoundingStrategy() ( + *CompoundingStrategy, + bool) { + if !c.isCompoundingStrategy { + return nil, false + } + return c.value.(*CompoundingStrategy), true +} + +// internalCouponCompoundingStrategy represents a couponCompoundingStrategy struct. +// This is a container for any-of cases. +type internalCouponCompoundingStrategy struct{} + +var CouponCompoundingStrategyContainer internalCouponCompoundingStrategy + +func (c *internalCouponCompoundingStrategy) FromCompoundingStrategy(val CompoundingStrategy) CouponCompoundingStrategy { + return CouponCompoundingStrategy{value: &val} +} diff --git a/models/coupon_currency.go b/models/coupon_currency.go index 05aaf942..2edfc5c5 100644 --- a/models/coupon_currency.go +++ b/models/coupon_currency.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // CouponCurrency represents a CouponCurrency struct. type CouponCurrency struct { - Id *int `json:"id,omitempty"` - Currency *string `json:"currency,omitempty"` - Price *int `json:"price,omitempty"` - CouponId *int `json:"coupon_id,omitempty"` + Id *int `json:"id,omitempty"` + Currency *string `json:"currency,omitempty"` + Price *int `json:"price,omitempty"` + CouponId *int `json:"coupon_id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CouponCurrency. +// MarshalJSON implements the json.Marshaler interface for CouponCurrency. // It customizes the JSON marshaling process for CouponCurrency objects. func (c *CouponCurrency) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CouponCurrency object to a map representation for JSON marshaling. func (c *CouponCurrency) toMap() map[string]any { - structMap := make(map[string]any) - if c.Id != nil { - structMap["id"] = c.Id - } - if c.Currency != nil { - structMap["currency"] = c.Currency - } - if c.Price != nil { - structMap["price"] = c.Price - } - if c.CouponId != nil { - structMap["coupon_id"] = c.CouponId - } - return structMap + structMap := make(map[string]any) + if c.Id != nil { + structMap["id"] = c.Id + } + if c.Currency != nil { + structMap["currency"] = c.Currency + } + if c.Price != nil { + structMap["price"] = c.Price + } + if c.CouponId != nil { + structMap["coupon_id"] = c.CouponId + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CouponCurrency. +// UnmarshalJSON implements the json.Unmarshaler interface for CouponCurrency. // It customizes the JSON unmarshaling process for CouponCurrency objects. func (c *CouponCurrency) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Currency *string `json:"currency,omitempty"` - Price *int `json:"price,omitempty"` - CouponId *int `json:"coupon_id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Id = temp.Id - c.Currency = temp.Currency - c.Price = temp.Price - c.CouponId = temp.CouponId - return nil + var temp couponCurrency + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Id = temp.Id + c.Currency = temp.Currency + c.Price = temp.Price + c.CouponId = temp.CouponId + return nil +} + +// TODO +type couponCurrency struct { + Id *int `json:"id,omitempty"` + Currency *string `json:"currency,omitempty"` + Price *int `json:"price,omitempty"` + CouponId *int `json:"coupon_id,omitempty"` } diff --git a/models/coupon_currency_request.go b/models/coupon_currency_request.go index 772a804f..b1868306 100644 --- a/models/coupon_currency_request.go +++ b/models/coupon_currency_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CouponCurrencyRequest represents a CouponCurrencyRequest struct. type CouponCurrencyRequest struct { - CurrencyPrices []UpdateCouponCurrency `json:"currency_prices"` + CurrencyPrices []UpdateCouponCurrency `json:"currency_prices"` } -// MarshalJSON implements the json.Marshaler interface for CouponCurrencyRequest. +// MarshalJSON implements the json.Marshaler interface for CouponCurrencyRequest. // It customizes the JSON marshaling process for CouponCurrencyRequest objects. func (c *CouponCurrencyRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CouponCurrencyRequest object to a map representation for JSON marshaling. func (c *CouponCurrencyRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["currency_prices"] = c.CurrencyPrices - return structMap + structMap := make(map[string]any) + structMap["currency_prices"] = c.CurrencyPrices + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CouponCurrencyRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CouponCurrencyRequest. // It customizes the JSON unmarshaling process for CouponCurrencyRequest objects. func (c *CouponCurrencyRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - CurrencyPrices []UpdateCouponCurrency `json:"currency_prices"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.CurrencyPrices = temp.CurrencyPrices - return nil + var temp couponCurrencyRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.CurrencyPrices = *temp.CurrencyPrices + return nil +} + +// TODO +type couponCurrencyRequest struct { + CurrencyPrices *[]UpdateCouponCurrency `json:"currency_prices"` +} + +func (c *couponCurrencyRequest) validate() error { + var errs []string + if c.CurrencyPrices == nil { + errs = append(errs, "required field `currency_prices` is missing for type `Coupon Currency Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/coupon_currency_response.go b/models/coupon_currency_response.go index 62edd85f..cdcdc112 100644 --- a/models/coupon_currency_response.go +++ b/models/coupon_currency_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // CouponCurrencyResponse represents a CouponCurrencyResponse struct. type CouponCurrencyResponse struct { - CurrencyPrices []CouponCurrency `json:"currency_prices,omitempty"` + CurrencyPrices []CouponCurrency `json:"currency_prices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CouponCurrencyResponse. +// MarshalJSON implements the json.Marshaler interface for CouponCurrencyResponse. // It customizes the JSON marshaling process for CouponCurrencyResponse objects. func (c *CouponCurrencyResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CouponCurrencyResponse object to a map representation for JSON marshaling. func (c *CouponCurrencyResponse) toMap() map[string]any { - structMap := make(map[string]any) - if c.CurrencyPrices != nil { - structMap["currency_prices"] = c.CurrencyPrices - } - return structMap + structMap := make(map[string]any) + if c.CurrencyPrices != nil { + structMap["currency_prices"] = c.CurrencyPrices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CouponCurrencyResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for CouponCurrencyResponse. // It customizes the JSON unmarshaling process for CouponCurrencyResponse objects. func (c *CouponCurrencyResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - CurrencyPrices []CouponCurrency `json:"currency_prices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.CurrencyPrices = temp.CurrencyPrices - return nil + var temp couponCurrencyResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.CurrencyPrices = temp.CurrencyPrices + return nil +} + +// TODO +type couponCurrencyResponse struct { + CurrencyPrices []CouponCurrency `json:"currency_prices,omitempty"` } diff --git a/models/coupon_response.go b/models/coupon_response.go index c00759ca..74b77c7b 100644 --- a/models/coupon_response.go +++ b/models/coupon_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // CouponResponse represents a CouponResponse struct. type CouponResponse struct { - Coupon *Coupon `json:"coupon,omitempty"` + Coupon *Coupon `json:"coupon,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CouponResponse. +// MarshalJSON implements the json.Marshaler interface for CouponResponse. // It customizes the JSON marshaling process for CouponResponse objects. func (c *CouponResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CouponResponse object to a map representation for JSON marshaling. func (c *CouponResponse) toMap() map[string]any { - structMap := make(map[string]any) - if c.Coupon != nil { - structMap["coupon"] = c.Coupon.toMap() - } - return structMap + structMap := make(map[string]any) + if c.Coupon != nil { + structMap["coupon"] = c.Coupon.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CouponResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for CouponResponse. // It customizes the JSON unmarshaling process for CouponResponse objects. func (c *CouponResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Coupon *Coupon `json:"coupon,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Coupon = temp.Coupon - return nil + var temp couponResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Coupon = temp.Coupon + return nil +} + +// TODO +type couponResponse struct { + Coupon *Coupon `json:"coupon,omitempty"` } diff --git a/models/coupon_restriction.go b/models/coupon_restriction.go index 023caf15..c28422de 100644 --- a/models/coupon_restriction.go +++ b/models/coupon_restriction.go @@ -1,66 +1,72 @@ package models import ( - "encoding/json" + "encoding/json" ) // CouponRestriction represents a CouponRestriction struct. type CouponRestriction struct { - Id *int `json:"id,omitempty"` - ItemType *RestrictionType `json:"item_type,omitempty"` - ItemId *int `json:"item_id,omitempty"` - Name *string `json:"name,omitempty"` - Handle Optional[string] `json:"handle"` + Id *int `json:"id,omitempty"` + ItemType *RestrictionType `json:"item_type,omitempty"` + ItemId *int `json:"item_id,omitempty"` + Name *string `json:"name,omitempty"` + Handle Optional[string] `json:"handle"` } -// MarshalJSON implements the json.Marshaler interface for CouponRestriction. +// MarshalJSON implements the json.Marshaler interface for CouponRestriction. // It customizes the JSON marshaling process for CouponRestriction objects. func (c *CouponRestriction) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CouponRestriction object to a map representation for JSON marshaling. func (c *CouponRestriction) toMap() map[string]any { - structMap := make(map[string]any) - if c.Id != nil { - structMap["id"] = c.Id - } - if c.ItemType != nil { - structMap["item_type"] = c.ItemType - } - if c.ItemId != nil { - structMap["item_id"] = c.ItemId - } - if c.Name != nil { - structMap["name"] = c.Name - } - if c.Handle.IsValueSet() { - structMap["handle"] = c.Handle.Value() - } - return structMap + structMap := make(map[string]any) + if c.Id != nil { + structMap["id"] = c.Id + } + if c.ItemType != nil { + structMap["item_type"] = c.ItemType + } + if c.ItemId != nil { + structMap["item_id"] = c.ItemId + } + if c.Name != nil { + structMap["name"] = c.Name + } + if c.Handle.IsValueSet() { + if c.Handle.Value() != nil { + structMap["handle"] = c.Handle.Value() + } else { + structMap["handle"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CouponRestriction. +// UnmarshalJSON implements the json.Unmarshaler interface for CouponRestriction. // It customizes the JSON unmarshaling process for CouponRestriction objects. func (c *CouponRestriction) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - ItemType *RestrictionType `json:"item_type,omitempty"` - ItemId *int `json:"item_id,omitempty"` - Name *string `json:"name,omitempty"` - Handle Optional[string] `json:"handle"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Id = temp.Id - c.ItemType = temp.ItemType - c.ItemId = temp.ItemId - c.Name = temp.Name - c.Handle = temp.Handle - return nil + var temp couponRestriction + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Id = temp.Id + c.ItemType = temp.ItemType + c.ItemId = temp.ItemId + c.Name = temp.Name + c.Handle = temp.Handle + return nil +} + +// TODO +type couponRestriction struct { + Id *int `json:"id,omitempty"` + ItemType *RestrictionType `json:"item_type,omitempty"` + ItemId *int `json:"item_id,omitempty"` + Name *string `json:"name,omitempty"` + Handle Optional[string] `json:"handle"` } diff --git a/models/coupon_subcodes.go b/models/coupon_subcodes.go index adf42cce..b8624b77 100644 --- a/models/coupon_subcodes.go +++ b/models/coupon_subcodes.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // CouponSubcodes represents a CouponSubcodes struct. type CouponSubcodes struct { - Codes []string `json:"codes,omitempty"` + Codes []string `json:"codes,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CouponSubcodes. +// MarshalJSON implements the json.Marshaler interface for CouponSubcodes. // It customizes the JSON marshaling process for CouponSubcodes objects. func (c *CouponSubcodes) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CouponSubcodes object to a map representation for JSON marshaling. func (c *CouponSubcodes) toMap() map[string]any { - structMap := make(map[string]any) - if c.Codes != nil { - structMap["codes"] = c.Codes - } - return structMap + structMap := make(map[string]any) + if c.Codes != nil { + structMap["codes"] = c.Codes + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CouponSubcodes. +// UnmarshalJSON implements the json.Unmarshaler interface for CouponSubcodes. // It customizes the JSON unmarshaling process for CouponSubcodes objects. func (c *CouponSubcodes) UnmarshalJSON(input []byte) error { - temp := &struct { - Codes []string `json:"codes,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Codes = temp.Codes - return nil + var temp couponSubcodes + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Codes = temp.Codes + return nil +} + +// TODO +type couponSubcodes struct { + Codes []string `json:"codes,omitempty"` } diff --git a/models/coupon_subcodes_response.go b/models/coupon_subcodes_response.go index 05827d4d..bfcddacc 100644 --- a/models/coupon_subcodes_response.go +++ b/models/coupon_subcodes_response.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // CouponSubcodesResponse represents a CouponSubcodesResponse struct. type CouponSubcodesResponse struct { - CreatedCodes []string `json:"created_codes,omitempty"` - DuplicateCodes []string `json:"duplicate_codes,omitempty"` - InvalidCodes []string `json:"invalid_codes,omitempty"` + CreatedCodes []string `json:"created_codes,omitempty"` + DuplicateCodes []string `json:"duplicate_codes,omitempty"` + InvalidCodes []string `json:"invalid_codes,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CouponSubcodesResponse. +// MarshalJSON implements the json.Marshaler interface for CouponSubcodesResponse. // It customizes the JSON marshaling process for CouponSubcodesResponse objects. func (c *CouponSubcodesResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CouponSubcodesResponse object to a map representation for JSON marshaling. func (c *CouponSubcodesResponse) toMap() map[string]any { - structMap := make(map[string]any) - if c.CreatedCodes != nil { - structMap["created_codes"] = c.CreatedCodes - } - if c.DuplicateCodes != nil { - structMap["duplicate_codes"] = c.DuplicateCodes - } - if c.InvalidCodes != nil { - structMap["invalid_codes"] = c.InvalidCodes - } - return structMap + structMap := make(map[string]any) + if c.CreatedCodes != nil { + structMap["created_codes"] = c.CreatedCodes + } + if c.DuplicateCodes != nil { + structMap["duplicate_codes"] = c.DuplicateCodes + } + if c.InvalidCodes != nil { + structMap["invalid_codes"] = c.InvalidCodes + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CouponSubcodesResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for CouponSubcodesResponse. // It customizes the JSON unmarshaling process for CouponSubcodesResponse objects. func (c *CouponSubcodesResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - CreatedCodes []string `json:"created_codes,omitempty"` - DuplicateCodes []string `json:"duplicate_codes,omitempty"` - InvalidCodes []string `json:"invalid_codes,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.CreatedCodes = temp.CreatedCodes - c.DuplicateCodes = temp.DuplicateCodes - c.InvalidCodes = temp.InvalidCodes - return nil + var temp couponSubcodesResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.CreatedCodes = temp.CreatedCodes + c.DuplicateCodes = temp.DuplicateCodes + c.InvalidCodes = temp.InvalidCodes + return nil +} + +// TODO +type couponSubcodesResponse struct { + CreatedCodes []string `json:"created_codes,omitempty"` + DuplicateCodes []string `json:"duplicate_codes,omitempty"` + InvalidCodes []string `json:"invalid_codes,omitempty"` } diff --git a/models/coupon_usage.go b/models/coupon_usage.go index 76941bb3..808ebb93 100644 --- a/models/coupon_usage.go +++ b/models/coupon_usage.go @@ -1,85 +1,99 @@ package models import ( - "encoding/json" + "encoding/json" ) // CouponUsage represents a CouponUsage struct. type CouponUsage struct { - // The Chargify id of the product - Id *int `json:"id,omitempty"` - // Name of the product - Name *string `json:"name,omitempty"` - // Number of times the coupon has been applied - Signups *int `json:"signups,omitempty"` - // Dollar amount of customer savings as a result of the coupon. - Savings Optional[int] `json:"savings"` - // Dollar amount of customer savings as a result of the coupon. - SavingsInCents Optional[int64] `json:"savings_in_cents"` - // Total revenue of the all subscriptions that have received a discount from this coupon. - Revenue Optional[int] `json:"revenue"` - // Total revenue of the all subscriptions that have received a discount from this coupon. - RevenueInCents *int64 `json:"revenue_in_cents,omitempty"` + // The Chargify id of the product + Id *int `json:"id,omitempty"` + // Name of the product + Name *string `json:"name,omitempty"` + // Number of times the coupon has been applied + Signups *int `json:"signups,omitempty"` + // Dollar amount of customer savings as a result of the coupon. + Savings Optional[int] `json:"savings"` + // Dollar amount of customer savings as a result of the coupon. + SavingsInCents Optional[int64] `json:"savings_in_cents"` + // Total revenue of the all subscriptions that have received a discount from this coupon. + Revenue Optional[int] `json:"revenue"` + // Total revenue of the all subscriptions that have received a discount from this coupon. + RevenueInCents *int64 `json:"revenue_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CouponUsage. +// MarshalJSON implements the json.Marshaler interface for CouponUsage. // It customizes the JSON marshaling process for CouponUsage objects. func (c *CouponUsage) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CouponUsage object to a map representation for JSON marshaling. func (c *CouponUsage) toMap() map[string]any { - structMap := make(map[string]any) - if c.Id != nil { - structMap["id"] = c.Id - } - if c.Name != nil { - structMap["name"] = c.Name - } - if c.Signups != nil { - structMap["signups"] = c.Signups - } - if c.Savings.IsValueSet() { - structMap["savings"] = c.Savings.Value() - } - if c.SavingsInCents.IsValueSet() { - structMap["savings_in_cents"] = c.SavingsInCents.Value() - } - if c.Revenue.IsValueSet() { - structMap["revenue"] = c.Revenue.Value() - } - if c.RevenueInCents != nil { - structMap["revenue_in_cents"] = c.RevenueInCents - } - return structMap + structMap := make(map[string]any) + if c.Id != nil { + structMap["id"] = c.Id + } + if c.Name != nil { + structMap["name"] = c.Name + } + if c.Signups != nil { + structMap["signups"] = c.Signups + } + if c.Savings.IsValueSet() { + if c.Savings.Value() != nil { + structMap["savings"] = c.Savings.Value() + } else { + structMap["savings"] = nil + } + } + if c.SavingsInCents.IsValueSet() { + if c.SavingsInCents.Value() != nil { + structMap["savings_in_cents"] = c.SavingsInCents.Value() + } else { + structMap["savings_in_cents"] = nil + } + } + if c.Revenue.IsValueSet() { + if c.Revenue.Value() != nil { + structMap["revenue"] = c.Revenue.Value() + } else { + structMap["revenue"] = nil + } + } + if c.RevenueInCents != nil { + structMap["revenue_in_cents"] = c.RevenueInCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CouponUsage. +// UnmarshalJSON implements the json.Unmarshaler interface for CouponUsage. // It customizes the JSON unmarshaling process for CouponUsage objects. func (c *CouponUsage) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Signups *int `json:"signups,omitempty"` - Savings Optional[int] `json:"savings"` - SavingsInCents Optional[int64] `json:"savings_in_cents"` - Revenue Optional[int] `json:"revenue"` - RevenueInCents *int64 `json:"revenue_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Id = temp.Id - c.Name = temp.Name - c.Signups = temp.Signups - c.Savings = temp.Savings - c.SavingsInCents = temp.SavingsInCents - c.Revenue = temp.Revenue - c.RevenueInCents = temp.RevenueInCents - return nil + var temp couponUsage + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Id = temp.Id + c.Name = temp.Name + c.Signups = temp.Signups + c.Savings = temp.Savings + c.SavingsInCents = temp.SavingsInCents + c.Revenue = temp.Revenue + c.RevenueInCents = temp.RevenueInCents + return nil +} + +// TODO +type couponUsage struct { + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Signups *int `json:"signups,omitempty"` + Savings Optional[int] `json:"savings"` + SavingsInCents Optional[int64] `json:"savings_in_cents"` + Revenue Optional[int] `json:"revenue"` + RevenueInCents *int64 `json:"revenue_in_cents,omitempty"` } diff --git a/models/create_allocation.go b/models/create_allocation.go index 899205e6..a75ac0ea 100644 --- a/models/create_allocation.go +++ b/models/create_allocation.go @@ -1,114 +1,146 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateAllocation represents a CreateAllocation struct. type CreateAllocation struct { - // The allocated quantity to which to set the line-items allocated quantity. By default, this is an integer. If decimal allocations are enabled for the component, it will be a decimal number. For On/Off components, use 1for on and 0 for off. - Quantity float64 `json:"quantity"` - // (required for the multiple allocations endpoint) The id associated with the component for which the allocation is being made - ComponentId *int `json:"component_id,omitempty"` - // A memo to record along with the allocation - Memo *string `json:"memo,omitempty"` - // The scheme used if the proration is a downgrade. Defaults to the site setting if one is not provided. - ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` // Deprecated - // The scheme used if the proration is an upgrade. Defaults to the site setting if one is not provided. - ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` // Deprecated - // If the change in cost is an upgrade, this determines if the charge should accrue to the next renewal or if capture should be attempted immediately. Defaults to the site setting if one is not provided. - AccrueCharge *bool `json:"accrue_charge,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // If set to true, if the immediate component payment fails, initiate dunning for the subscription. - // Otherwise, leave the charges on the subscription to pay for at renewal. Defaults to false. - InitiateDunning *bool `json:"initiate_dunning,omitempty"` - // Price point that the allocation should be charged at. Accepts either the price point's id (integer) or handle (string). When not specified, the default price point will be used. - PricePointId Optional[interface{}] `json:"price_point_id"` - // This attribute is particularly useful when you need to align billing events for different components on distinct schedules within a subscription. Please note this only works for site with Multifrequency enabled - BillingSchedule *BillingSchedule `json:"billing_schedule,omitempty"` + // The allocated quantity to which to set the line-items allocated quantity. By default, this is an integer. If decimal allocations are enabled for the component, it will be a decimal number. For On/Off components, use 1for on and 0 for off. + Quantity float64 `json:"quantity"` + // (required for the multiple allocations endpoint) The id associated with the component for which the allocation is being made + ComponentId *int `json:"component_id,omitempty"` + // A memo to record along with the allocation + Memo *string `json:"memo,omitempty"` + // The scheme used if the proration is a downgrade. Defaults to the site setting if one is not provided. + ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` // Deprecated + // The scheme used if the proration is an upgrade. Defaults to the site setting if one is not provided. + ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` // Deprecated + // If the change in cost is an upgrade, this determines if the charge should accrue to the next renewal or if capture should be attempted immediately. Defaults to the site setting if one is not provided. + AccrueCharge *bool `json:"accrue_charge,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // If set to true, if the immediate component payment fails, initiate dunning for the subscription. + // Otherwise, leave the charges on the subscription to pay for at renewal. Defaults to false. + InitiateDunning *bool `json:"initiate_dunning,omitempty"` + // Price point that the allocation should be charged at. Accepts either the price point's id (integer) or handle (string). When not specified, the default price point will be used. + PricePointId Optional[CreateAllocationPricePointId] `json:"price_point_id"` + // This attribute is particularly useful when you need to align billing events for different components on distinct schedules within a subscription. Please note this only works for site with Multifrequency enabled + BillingSchedule *BillingSchedule `json:"billing_schedule,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateAllocation. +// MarshalJSON implements the json.Marshaler interface for CreateAllocation. // It customizes the JSON marshaling process for CreateAllocation objects. func (c *CreateAllocation) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateAllocation object to a map representation for JSON marshaling. func (c *CreateAllocation) toMap() map[string]any { - structMap := make(map[string]any) - structMap["quantity"] = c.Quantity - if c.ComponentId != nil { - structMap["component_id"] = c.ComponentId - } - if c.Memo != nil { - structMap["memo"] = c.Memo - } - if c.ProrationDowngradeScheme != nil { - structMap["proration_downgrade_scheme"] = c.ProrationDowngradeScheme - } - if c.ProrationUpgradeScheme != nil { - structMap["proration_upgrade_scheme"] = c.ProrationUpgradeScheme - } - if c.AccrueCharge != nil { - structMap["accrue_charge"] = c.AccrueCharge - } - if c.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = c.DowngradeCredit.Value() - } - if c.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = c.UpgradeCharge.Value() - } - if c.InitiateDunning != nil { - structMap["initiate_dunning"] = c.InitiateDunning - } - if c.PricePointId.IsValueSet() { - structMap["price_point_id"] = c.PricePointId.Value() - } - if c.BillingSchedule != nil { - structMap["billing_schedule"] = c.BillingSchedule.toMap() - } - return structMap + structMap := make(map[string]any) + structMap["quantity"] = c.Quantity + if c.ComponentId != nil { + structMap["component_id"] = c.ComponentId + } + if c.Memo != nil { + structMap["memo"] = c.Memo + } + if c.ProrationDowngradeScheme != nil { + structMap["proration_downgrade_scheme"] = c.ProrationDowngradeScheme + } + if c.ProrationUpgradeScheme != nil { + structMap["proration_upgrade_scheme"] = c.ProrationUpgradeScheme + } + if c.AccrueCharge != nil { + structMap["accrue_charge"] = c.AccrueCharge + } + if c.DowngradeCredit.IsValueSet() { + if c.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = c.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if c.UpgradeCharge.IsValueSet() { + if c.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = c.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if c.InitiateDunning != nil { + structMap["initiate_dunning"] = c.InitiateDunning + } + if c.PricePointId.IsValueSet() { + if c.PricePointId.Value() != nil { + structMap["price_point_id"] = c.PricePointId.Value().toMap() + } else { + structMap["price_point_id"] = nil + } + } + if c.BillingSchedule != nil { + structMap["billing_schedule"] = c.BillingSchedule.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateAllocation. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateAllocation. // It customizes the JSON unmarshaling process for CreateAllocation objects. func (c *CreateAllocation) UnmarshalJSON(input []byte) error { - temp := &struct { - Quantity float64 `json:"quantity"` - ComponentId *int `json:"component_id,omitempty"` - Memo *string `json:"memo,omitempty"` - ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` - ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` - AccrueCharge *bool `json:"accrue_charge,omitempty"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - InitiateDunning *bool `json:"initiate_dunning,omitempty"` - PricePointId Optional[interface{}] `json:"price_point_id"` - BillingSchedule *BillingSchedule `json:"billing_schedule,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Quantity = temp.Quantity - c.ComponentId = temp.ComponentId - c.Memo = temp.Memo - c.ProrationDowngradeScheme = temp.ProrationDowngradeScheme - c.ProrationUpgradeScheme = temp.ProrationUpgradeScheme - c.AccrueCharge = temp.AccrueCharge - c.DowngradeCredit = temp.DowngradeCredit - c.UpgradeCharge = temp.UpgradeCharge - c.InitiateDunning = temp.InitiateDunning - c.PricePointId = temp.PricePointId - c.BillingSchedule = temp.BillingSchedule - return nil + var temp createAllocation + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Quantity = *temp.Quantity + c.ComponentId = temp.ComponentId + c.Memo = temp.Memo + c.ProrationDowngradeScheme = temp.ProrationDowngradeScheme + c.ProrationUpgradeScheme = temp.ProrationUpgradeScheme + c.AccrueCharge = temp.AccrueCharge + c.DowngradeCredit = temp.DowngradeCredit + c.UpgradeCharge = temp.UpgradeCharge + c.InitiateDunning = temp.InitiateDunning + c.PricePointId = temp.PricePointId + c.BillingSchedule = temp.BillingSchedule + return nil +} + +// TODO +type createAllocation struct { + Quantity *float64 `json:"quantity"` + ComponentId *int `json:"component_id,omitempty"` + Memo *string `json:"memo,omitempty"` + ProrationDowngradeScheme *string `json:"proration_downgrade_scheme,omitempty"` + ProrationUpgradeScheme *string `json:"proration_upgrade_scheme,omitempty"` + AccrueCharge *bool `json:"accrue_charge,omitempty"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + InitiateDunning *bool `json:"initiate_dunning,omitempty"` + PricePointId Optional[CreateAllocationPricePointId] `json:"price_point_id"` + BillingSchedule *BillingSchedule `json:"billing_schedule,omitempty"` +} + +func (c *createAllocation) validate() error { + var errs []string + if c.Quantity == nil { + errs = append(errs, "required field `quantity` is missing for type `Create Allocation`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_allocation_price_point_id.go b/models/create_allocation_price_point_id.go new file mode 100644 index 00000000..e412f588 --- /dev/null +++ b/models/create_allocation_price_point_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateAllocationPricePointId represents a CreateAllocationPricePointId struct. +// This is a container for one-of cases. +type CreateAllocationPricePointId struct { + value any + isString bool + isNumber bool +} + +// String converts the CreateAllocationPricePointId object to a string representation. +func (c CreateAllocationPricePointId) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateAllocationPricePointId. +// It customizes the JSON marshaling process for CreateAllocationPricePointId objects. +func (c *CreateAllocationPricePointId) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateAllocationPricePointIdContainer.From*` functions to initialize the CreateAllocationPricePointId object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateAllocationPricePointId object to a map representation for JSON marshaling. +func (c *CreateAllocationPricePointId) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateAllocationPricePointId. +// It customizes the JSON unmarshaling process for CreateAllocationPricePointId objects. +func (c *CreateAllocationPricePointId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(int), false, &c.isNumber), + ) + + c.value = result + return err +} + +func (c *CreateAllocationPricePointId) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateAllocationPricePointId) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +// internalCreateAllocationPricePointId represents a createAllocationPricePointId struct. +// This is a container for one-of cases. +type internalCreateAllocationPricePointId struct{} + +var CreateAllocationPricePointIdContainer internalCreateAllocationPricePointId + +func (c *internalCreateAllocationPricePointId) FromString(val string) CreateAllocationPricePointId { + return CreateAllocationPricePointId{value: &val} +} + +func (c *internalCreateAllocationPricePointId) FromNumber(val int) CreateAllocationPricePointId { + return CreateAllocationPricePointId{value: &val} +} diff --git a/models/create_allocation_request.go b/models/create_allocation_request.go index 4507d069..61eccd7b 100644 --- a/models/create_allocation_request.go +++ b/models/create_allocation_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateAllocationRequest represents a CreateAllocationRequest struct. type CreateAllocationRequest struct { - Allocation CreateAllocation `json:"allocation"` + Allocation CreateAllocation `json:"allocation"` } -// MarshalJSON implements the json.Marshaler interface for CreateAllocationRequest. +// MarshalJSON implements the json.Marshaler interface for CreateAllocationRequest. // It customizes the JSON marshaling process for CreateAllocationRequest objects. func (c *CreateAllocationRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateAllocationRequest object to a map representation for JSON marshaling. func (c *CreateAllocationRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["allocation"] = c.Allocation.toMap() - return structMap + structMap := make(map[string]any) + structMap["allocation"] = c.Allocation.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateAllocationRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateAllocationRequest. // It customizes the JSON unmarshaling process for CreateAllocationRequest objects. func (c *CreateAllocationRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Allocation CreateAllocation `json:"allocation"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Allocation = temp.Allocation - return nil + var temp createAllocationRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Allocation = *temp.Allocation + return nil +} + +// TODO +type createAllocationRequest struct { + Allocation *CreateAllocation `json:"allocation"` +} + +func (c *createAllocationRequest) validate() error { + var errs []string + if c.Allocation == nil { + errs = append(errs, "required field `allocation` is missing for type `Create Allocation Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_component_price_point.go b/models/create_component_price_point.go new file mode 100644 index 00000000..1fe8132a --- /dev/null +++ b/models/create_component_price_point.go @@ -0,0 +1,109 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateComponentPricePoint represents a CreateComponentPricePoint struct. +type CreateComponentPricePoint struct { + Name string `json:"name"` + Handle *string `json:"handle,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme PricingScheme `json:"pricing_scheme"` + Prices []Price `json:"prices"` + // Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + // Whether or not the price point includes tax + TaxIncluded *bool `json:"tax_included,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for CreateComponentPricePoint. +// It customizes the JSON marshaling process for CreateComponentPricePoint objects. +func (c *CreateComponentPricePoint) MarshalJSON() ( + []byte, + error) { + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateComponentPricePoint object to a map representation for JSON marshaling. +func (c *CreateComponentPricePoint) toMap() map[string]any { + structMap := make(map[string]any) + structMap["name"] = c.Name + if c.Handle != nil { + structMap["handle"] = c.Handle + } + structMap["pricing_scheme"] = c.PricingScheme + structMap["prices"] = c.Prices + if c.UseSiteExchangeRate != nil { + structMap["use_site_exchange_rate"] = c.UseSiteExchangeRate + } + if c.TaxIncluded != nil { + structMap["tax_included"] = c.TaxIncluded + } + if c.Interval != nil { + structMap["interval"] = c.Interval + } + if c.IntervalUnit != nil { + structMap["interval_unit"] = c.IntervalUnit + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateComponentPricePoint. +// It customizes the JSON unmarshaling process for CreateComponentPricePoint objects. +func (c *CreateComponentPricePoint) UnmarshalJSON(input []byte) error { + var temp createComponentPricePoint + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Name = *temp.Name + c.Handle = temp.Handle + c.PricingScheme = *temp.PricingScheme + c.Prices = *temp.Prices + c.UseSiteExchangeRate = temp.UseSiteExchangeRate + c.TaxIncluded = temp.TaxIncluded + c.Interval = temp.Interval + c.IntervalUnit = temp.IntervalUnit + return nil +} + +// TODO +type createComponentPricePoint struct { + Name *string `json:"name"` + Handle *string `json:"handle,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme"` + Prices *[]Price `json:"prices"` + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + TaxIncluded *bool `json:"tax_included,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` +} + +func (c *createComponentPricePoint) validate() error { + var errs []string + if c.Name == nil { + errs = append(errs, "required field `name` is missing for type `Create Component Price Point`") + } + if c.PricingScheme == nil { + errs = append(errs, "required field `pricing_scheme` is missing for type `Create Component Price Point`") + } + if c.Prices == nil { + errs = append(errs, "required field `prices` is missing for type `Create Component Price Point`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/create_component_price_point_request.go b/models/create_component_price_point_request.go index 589ddee3..14a284fd 100644 --- a/models/create_component_price_point_request.go +++ b/models/create_component_price_point_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateComponentPricePointRequest represents a CreateComponentPricePointRequest struct. type CreateComponentPricePointRequest struct { - PricePoint PricePoint `json:"price_point"` + PricePoint CreateComponentPricePointRequestPricePoint `json:"price_point"` } -// MarshalJSON implements the json.Marshaler interface for CreateComponentPricePointRequest. +// MarshalJSON implements the json.Marshaler interface for CreateComponentPricePointRequest. // It customizes the JSON marshaling process for CreateComponentPricePointRequest objects. func (c *CreateComponentPricePointRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateComponentPricePointRequest object to a map representation for JSON marshaling. func (c *CreateComponentPricePointRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["price_point"] = c.PricePoint.toMap() - return structMap + structMap := make(map[string]any) + structMap["price_point"] = c.PricePoint.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateComponentPricePointRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateComponentPricePointRequest. // It customizes the JSON unmarshaling process for CreateComponentPricePointRequest objects. func (c *CreateComponentPricePointRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoint PricePoint `json:"price_point"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.PricePoint = temp.PricePoint - return nil + var temp createComponentPricePointRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.PricePoint = *temp.PricePoint + return nil +} + +// TODO +type createComponentPricePointRequest struct { + PricePoint *CreateComponentPricePointRequestPricePoint `json:"price_point"` +} + +func (c *createComponentPricePointRequest) validate() error { + var errs []string + if c.PricePoint == nil { + errs = append(errs, "required field `price_point` is missing for type `Create Component Price Point Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_component_price_point_request_price_point.go b/models/create_component_price_point_request_price_point.go new file mode 100644 index 00000000..2223b0a2 --- /dev/null +++ b/models/create_component_price_point_request_price_point.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateComponentPricePointRequestPricePoint represents a CreateComponentPricePointRequestPricePoint struct. +// This is a container for any-of cases. +type CreateComponentPricePointRequestPricePoint struct { + value any + isCreateComponentPricePoint bool + isCreatePrepaidUsageComponentPricePoint bool +} + +// String converts the CreateComponentPricePointRequestPricePoint object to a string representation. +func (c CreateComponentPricePointRequestPricePoint) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateComponentPricePointRequestPricePoint. +// It customizes the JSON marshaling process for CreateComponentPricePointRequestPricePoint objects. +func (c *CreateComponentPricePointRequestPricePoint) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateComponentPricePointRequestPricePointContainer.From*` functions to initialize the CreateComponentPricePointRequestPricePoint object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateComponentPricePointRequestPricePoint object to a map representation for JSON marshaling. +func (c *CreateComponentPricePointRequestPricePoint) toMap() any { + switch obj := c.value.(type) { + case *CreateComponentPricePoint: + return obj.toMap() + case *CreatePrepaidUsageComponentPricePoint: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateComponentPricePointRequestPricePoint. +// It customizes the JSON unmarshaling process for CreateComponentPricePointRequestPricePoint objects. +func (c *CreateComponentPricePointRequestPricePoint) UnmarshalJSON(input []byte) error { + result, err := UnmarshallAnyOf(input, + NewTypeHolder(&CreateComponentPricePoint{}, false, &c.isCreateComponentPricePoint), + NewTypeHolder(&CreatePrepaidUsageComponentPricePoint{}, false, &c.isCreatePrepaidUsageComponentPricePoint), + ) + + c.value = result + return err +} + +func (c *CreateComponentPricePointRequestPricePoint) AsCreateComponentPricePoint() ( + *CreateComponentPricePoint, + bool) { + if !c.isCreateComponentPricePoint { + return nil, false + } + return c.value.(*CreateComponentPricePoint), true +} + +func (c *CreateComponentPricePointRequestPricePoint) AsCreatePrepaidUsageComponentPricePoint() ( + *CreatePrepaidUsageComponentPricePoint, + bool) { + if !c.isCreatePrepaidUsageComponentPricePoint { + return nil, false + } + return c.value.(*CreatePrepaidUsageComponentPricePoint), true +} + +// internalCreateComponentPricePointRequestPricePoint represents a createComponentPricePointRequestPricePoint struct. +// This is a container for any-of cases. +type internalCreateComponentPricePointRequestPricePoint struct{} + +var CreateComponentPricePointRequestPricePointContainer internalCreateComponentPricePointRequestPricePoint + +func (c *internalCreateComponentPricePointRequestPricePoint) FromCreateComponentPricePoint(val CreateComponentPricePoint) CreateComponentPricePointRequestPricePoint { + return CreateComponentPricePointRequestPricePoint{value: &val} +} + +func (c *internalCreateComponentPricePointRequestPricePoint) FromCreatePrepaidUsageComponentPricePoint(val CreatePrepaidUsageComponentPricePoint) CreateComponentPricePointRequestPricePoint { + return CreateComponentPricePointRequestPricePoint{value: &val} +} diff --git a/models/create_component_price_points_request.go b/models/create_component_price_points_request.go index 8e73e01d..88934e78 100644 --- a/models/create_component_price_points_request.go +++ b/models/create_component_price_points_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateComponentPricePointsRequest represents a CreateComponentPricePointsRequest struct. type CreateComponentPricePointsRequest struct { - PricePoints []PricePoint `json:"price_points"` + PricePoints []CreateComponentPricePointsRequestPricePoints `json:"price_points"` } -// MarshalJSON implements the json.Marshaler interface for CreateComponentPricePointsRequest. +// MarshalJSON implements the json.Marshaler interface for CreateComponentPricePointsRequest. // It customizes the JSON marshaling process for CreateComponentPricePointsRequest objects. func (c *CreateComponentPricePointsRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateComponentPricePointsRequest object to a map representation for JSON marshaling. func (c *CreateComponentPricePointsRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["price_points"] = c.PricePoints - return structMap + structMap := make(map[string]any) + structMap["price_points"] = c.PricePoints + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateComponentPricePointsRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateComponentPricePointsRequest. // It customizes the JSON unmarshaling process for CreateComponentPricePointsRequest objects. func (c *CreateComponentPricePointsRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoints []PricePoint `json:"price_points"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.PricePoints = temp.PricePoints - return nil + var temp createComponentPricePointsRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.PricePoints = *temp.PricePoints + return nil +} + +// TODO +type createComponentPricePointsRequest struct { + PricePoints *[]CreateComponentPricePointsRequestPricePoints `json:"price_points"` +} + +func (c *createComponentPricePointsRequest) validate() error { + var errs []string + if c.PricePoints == nil { + errs = append(errs, "required field `price_points` is missing for type `Create Component Price Points Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_component_price_points_request_price_points.go b/models/create_component_price_points_request_price_points.go new file mode 100644 index 00000000..e32fedc8 --- /dev/null +++ b/models/create_component_price_points_request_price_points.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateComponentPricePointsRequestPricePoints represents a CreateComponentPricePointsRequestPricePoints struct. +// This is Array of a container for any-of cases. +type CreateComponentPricePointsRequestPricePoints struct { + value any + isCreateComponentPricePoint bool + isCreatePrepaidUsageComponentPricePoint bool +} + +// String converts the CreateComponentPricePointsRequestPricePoints object to a string representation. +func (c CreateComponentPricePointsRequestPricePoints) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateComponentPricePointsRequestPricePoints. +// It customizes the JSON marshaling process for CreateComponentPricePointsRequestPricePoints objects. +func (c *CreateComponentPricePointsRequestPricePoints) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateComponentPricePointsRequestPricePointsContainer.From*` functions to initialize the CreateComponentPricePointsRequestPricePoints object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateComponentPricePointsRequestPricePoints object to a map representation for JSON marshaling. +func (c *CreateComponentPricePointsRequestPricePoints) toMap() any { + switch obj := c.value.(type) { + case *CreateComponentPricePoint: + return obj.toMap() + case *CreatePrepaidUsageComponentPricePoint: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateComponentPricePointsRequestPricePoints. +// It customizes the JSON unmarshaling process for CreateComponentPricePointsRequestPricePoints objects. +func (c *CreateComponentPricePointsRequestPricePoints) UnmarshalJSON(input []byte) error { + result, err := UnmarshallAnyOf(input, + NewTypeHolder(&CreateComponentPricePoint{}, false, &c.isCreateComponentPricePoint), + NewTypeHolder(&CreatePrepaidUsageComponentPricePoint{}, false, &c.isCreatePrepaidUsageComponentPricePoint), + ) + + c.value = result + return err +} + +func (c *CreateComponentPricePointsRequestPricePoints) AsCreateComponentPricePoint() ( + *CreateComponentPricePoint, + bool) { + if !c.isCreateComponentPricePoint { + return nil, false + } + return c.value.(*CreateComponentPricePoint), true +} + +func (c *CreateComponentPricePointsRequestPricePoints) AsCreatePrepaidUsageComponentPricePoint() ( + *CreatePrepaidUsageComponentPricePoint, + bool) { + if !c.isCreatePrepaidUsageComponentPricePoint { + return nil, false + } + return c.value.(*CreatePrepaidUsageComponentPricePoint), true +} + +// internalCreateComponentPricePointsRequestPricePoints represents a createComponentPricePointsRequestPricePoints struct. +// This is Array of a container for any-of cases. +type internalCreateComponentPricePointsRequestPricePoints struct{} + +var CreateComponentPricePointsRequestPricePointsContainer internalCreateComponentPricePointsRequestPricePoints + +func (c *internalCreateComponentPricePointsRequestPricePoints) FromCreateComponentPricePoint(val CreateComponentPricePoint) CreateComponentPricePointsRequestPricePoints { + return CreateComponentPricePointsRequestPricePoints{value: &val} +} + +func (c *internalCreateComponentPricePointsRequestPricePoints) FromCreatePrepaidUsageComponentPricePoint(val CreatePrepaidUsageComponentPricePoint) CreateComponentPricePointsRequestPricePoints { + return CreateComponentPricePointsRequestPricePoints{value: &val} +} diff --git a/models/create_currency_price.go b/models/create_currency_price.go index 0943b5f2..c7c946bd 100644 --- a/models/create_currency_price.go +++ b/models/create_currency_price.go @@ -1,57 +1,59 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreateCurrencyPrice represents a CreateCurrencyPrice struct. type CreateCurrencyPrice struct { - // ISO code for a currency defined on the site level - Currency *string `json:"currency,omitempty"` - // Price for the price level in this currency - Price *float64 `json:"price,omitempty"` - // ID of the price that this corresponds with - PriceId *int `json:"price_id,omitempty"` + // ISO code for a currency defined on the site level + Currency *string `json:"currency,omitempty"` + // Price for the price level in this currency + Price *float64 `json:"price,omitempty"` + // ID of the price that this corresponds with + PriceId *int `json:"price_id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateCurrencyPrice. +// MarshalJSON implements the json.Marshaler interface for CreateCurrencyPrice. // It customizes the JSON marshaling process for CreateCurrencyPrice objects. func (c *CreateCurrencyPrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateCurrencyPrice object to a map representation for JSON marshaling. func (c *CreateCurrencyPrice) toMap() map[string]any { - structMap := make(map[string]any) - if c.Currency != nil { - structMap["currency"] = c.Currency - } - if c.Price != nil { - structMap["price"] = c.Price - } - if c.PriceId != nil { - structMap["price_id"] = c.PriceId - } - return structMap + structMap := make(map[string]any) + if c.Currency != nil { + structMap["currency"] = c.Currency + } + if c.Price != nil { + structMap["price"] = c.Price + } + if c.PriceId != nil { + structMap["price_id"] = c.PriceId + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateCurrencyPrice. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateCurrencyPrice. // It customizes the JSON unmarshaling process for CreateCurrencyPrice objects. func (c *CreateCurrencyPrice) UnmarshalJSON(input []byte) error { - temp := &struct { - Currency *string `json:"currency,omitempty"` - Price *float64 `json:"price,omitempty"` - PriceId *int `json:"price_id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Currency = temp.Currency - c.Price = temp.Price - c.PriceId = temp.PriceId - return nil + var temp createCurrencyPrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Currency = temp.Currency + c.Price = temp.Price + c.PriceId = temp.PriceId + return nil +} + +// TODO +type createCurrencyPrice struct { + Currency *string `json:"currency,omitempty"` + Price *float64 `json:"price,omitempty"` + PriceId *int `json:"price_id,omitempty"` } diff --git a/models/create_currency_prices_request.go b/models/create_currency_prices_request.go index a8145f4c..b988bc5e 100644 --- a/models/create_currency_prices_request.go +++ b/models/create_currency_prices_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateCurrencyPricesRequest represents a CreateCurrencyPricesRequest struct. type CreateCurrencyPricesRequest struct { - CurrencyPrices []CreateCurrencyPrice `json:"currency_prices"` + CurrencyPrices []CreateCurrencyPrice `json:"currency_prices"` } -// MarshalJSON implements the json.Marshaler interface for CreateCurrencyPricesRequest. +// MarshalJSON implements the json.Marshaler interface for CreateCurrencyPricesRequest. // It customizes the JSON marshaling process for CreateCurrencyPricesRequest objects. func (c *CreateCurrencyPricesRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateCurrencyPricesRequest object to a map representation for JSON marshaling. func (c *CreateCurrencyPricesRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["currency_prices"] = c.CurrencyPrices - return structMap + structMap := make(map[string]any) + structMap["currency_prices"] = c.CurrencyPrices + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateCurrencyPricesRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateCurrencyPricesRequest. // It customizes the JSON unmarshaling process for CreateCurrencyPricesRequest objects. func (c *CreateCurrencyPricesRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - CurrencyPrices []CreateCurrencyPrice `json:"currency_prices"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.CurrencyPrices = temp.CurrencyPrices - return nil + var temp createCurrencyPricesRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.CurrencyPrices = *temp.CurrencyPrices + return nil +} + +// TODO +type createCurrencyPricesRequest struct { + CurrencyPrices *[]CreateCurrencyPrice `json:"currency_prices"` +} + +func (c *createCurrencyPricesRequest) validate() error { + var errs []string + if c.CurrencyPrices == nil { + errs = append(errs, "required field `currency_prices` is missing for type `Create Currency Prices Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_customer.go b/models/create_customer.go index f62c8946..6dd3fed1 100644 --- a/models/create_customer.go +++ b/models/create_customer.go @@ -1,140 +1,170 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateCustomer represents a CreateCustomer struct. type CreateCustomer struct { - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - Email string `json:"email"` - CcEmails *string `json:"cc_emails,omitempty"` - Organization *string `json:"organization,omitempty"` - Reference *string `json:"reference,omitempty"` - Address *string `json:"address,omitempty"` - Address2 *string `json:"address_2,omitempty"` - City *string `json:"city,omitempty"` - State *string `json:"state,omitempty"` - Zip *string `json:"zip,omitempty"` - Country *string `json:"country,omitempty"` - Phone *string `json:"phone,omitempty"` - // Set a specific language on a customer record. - Locale *string `json:"locale,omitempty"` - VatNumber *string `json:"vat_number,omitempty"` - TaxExempt *bool `json:"tax_exempt,omitempty"` - TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` - // The parent ID in Chargify if applicable. Parent is another Customer object. - ParentId Optional[int] `json:"parent_id"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Email string `json:"email"` + CcEmails *string `json:"cc_emails,omitempty"` + Organization *string `json:"organization,omitempty"` + Reference *string `json:"reference,omitempty"` + Address *string `json:"address,omitempty"` + Address2 *string `json:"address_2,omitempty"` + City *string `json:"city,omitempty"` + State *string `json:"state,omitempty"` + Zip *string `json:"zip,omitempty"` + Country *string `json:"country,omitempty"` + Phone *string `json:"phone,omitempty"` + // Set a specific language on a customer record. + Locale *string `json:"locale,omitempty"` + VatNumber *string `json:"vat_number,omitempty"` + TaxExempt *bool `json:"tax_exempt,omitempty"` + TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` + // The parent ID in Chargify if applicable. Parent is another Customer object. + ParentId Optional[int] `json:"parent_id"` } -// MarshalJSON implements the json.Marshaler interface for CreateCustomer. +// MarshalJSON implements the json.Marshaler interface for CreateCustomer. // It customizes the JSON marshaling process for CreateCustomer objects. func (c *CreateCustomer) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateCustomer object to a map representation for JSON marshaling. func (c *CreateCustomer) toMap() map[string]any { - structMap := make(map[string]any) - structMap["first_name"] = c.FirstName - structMap["last_name"] = c.LastName - structMap["email"] = c.Email - if c.CcEmails != nil { - structMap["cc_emails"] = c.CcEmails - } - if c.Organization != nil { - structMap["organization"] = c.Organization - } - if c.Reference != nil { - structMap["reference"] = c.Reference - } - if c.Address != nil { - structMap["address"] = c.Address - } - if c.Address2 != nil { - structMap["address_2"] = c.Address2 - } - if c.City != nil { - structMap["city"] = c.City - } - if c.State != nil { - structMap["state"] = c.State - } - if c.Zip != nil { - structMap["zip"] = c.Zip - } - if c.Country != nil { - structMap["country"] = c.Country - } - if c.Phone != nil { - structMap["phone"] = c.Phone - } - if c.Locale != nil { - structMap["locale"] = c.Locale - } - if c.VatNumber != nil { - structMap["vat_number"] = c.VatNumber - } - if c.TaxExempt != nil { - structMap["tax_exempt"] = c.TaxExempt - } - if c.TaxExemptReason != nil { - structMap["tax_exempt_reason"] = c.TaxExemptReason - } - if c.ParentId.IsValueSet() { - structMap["parent_id"] = c.ParentId.Value() - } - return structMap + structMap := make(map[string]any) + structMap["first_name"] = c.FirstName + structMap["last_name"] = c.LastName + structMap["email"] = c.Email + if c.CcEmails != nil { + structMap["cc_emails"] = c.CcEmails + } + if c.Organization != nil { + structMap["organization"] = c.Organization + } + if c.Reference != nil { + structMap["reference"] = c.Reference + } + if c.Address != nil { + structMap["address"] = c.Address + } + if c.Address2 != nil { + structMap["address_2"] = c.Address2 + } + if c.City != nil { + structMap["city"] = c.City + } + if c.State != nil { + structMap["state"] = c.State + } + if c.Zip != nil { + structMap["zip"] = c.Zip + } + if c.Country != nil { + structMap["country"] = c.Country + } + if c.Phone != nil { + structMap["phone"] = c.Phone + } + if c.Locale != nil { + structMap["locale"] = c.Locale + } + if c.VatNumber != nil { + structMap["vat_number"] = c.VatNumber + } + if c.TaxExempt != nil { + structMap["tax_exempt"] = c.TaxExempt + } + if c.TaxExemptReason != nil { + structMap["tax_exempt_reason"] = c.TaxExemptReason + } + if c.ParentId.IsValueSet() { + if c.ParentId.Value() != nil { + structMap["parent_id"] = c.ParentId.Value() + } else { + structMap["parent_id"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateCustomer. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateCustomer. // It customizes the JSON unmarshaling process for CreateCustomer objects. func (c *CreateCustomer) UnmarshalJSON(input []byte) error { - temp := &struct { - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - Email string `json:"email"` - CcEmails *string `json:"cc_emails,omitempty"` - Organization *string `json:"organization,omitempty"` - Reference *string `json:"reference,omitempty"` - Address *string `json:"address,omitempty"` - Address2 *string `json:"address_2,omitempty"` - City *string `json:"city,omitempty"` - State *string `json:"state,omitempty"` - Zip *string `json:"zip,omitempty"` - Country *string `json:"country,omitempty"` - Phone *string `json:"phone,omitempty"` - Locale *string `json:"locale,omitempty"` - VatNumber *string `json:"vat_number,omitempty"` - TaxExempt *bool `json:"tax_exempt,omitempty"` - TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` - ParentId Optional[int] `json:"parent_id"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.FirstName = temp.FirstName - c.LastName = temp.LastName - c.Email = temp.Email - c.CcEmails = temp.CcEmails - c.Organization = temp.Organization - c.Reference = temp.Reference - c.Address = temp.Address - c.Address2 = temp.Address2 - c.City = temp.City - c.State = temp.State - c.Zip = temp.Zip - c.Country = temp.Country - c.Phone = temp.Phone - c.Locale = temp.Locale - c.VatNumber = temp.VatNumber - c.TaxExempt = temp.TaxExempt - c.TaxExemptReason = temp.TaxExemptReason - c.ParentId = temp.ParentId - return nil + var temp createCustomer + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.FirstName = *temp.FirstName + c.LastName = *temp.LastName + c.Email = *temp.Email + c.CcEmails = temp.CcEmails + c.Organization = temp.Organization + c.Reference = temp.Reference + c.Address = temp.Address + c.Address2 = temp.Address2 + c.City = temp.City + c.State = temp.State + c.Zip = temp.Zip + c.Country = temp.Country + c.Phone = temp.Phone + c.Locale = temp.Locale + c.VatNumber = temp.VatNumber + c.TaxExempt = temp.TaxExempt + c.TaxExemptReason = temp.TaxExemptReason + c.ParentId = temp.ParentId + return nil +} + +// TODO +type createCustomer struct { + FirstName *string `json:"first_name"` + LastName *string `json:"last_name"` + Email *string `json:"email"` + CcEmails *string `json:"cc_emails,omitempty"` + Organization *string `json:"organization,omitempty"` + Reference *string `json:"reference,omitempty"` + Address *string `json:"address,omitempty"` + Address2 *string `json:"address_2,omitempty"` + City *string `json:"city,omitempty"` + State *string `json:"state,omitempty"` + Zip *string `json:"zip,omitempty"` + Country *string `json:"country,omitempty"` + Phone *string `json:"phone,omitempty"` + Locale *string `json:"locale,omitempty"` + VatNumber *string `json:"vat_number,omitempty"` + TaxExempt *bool `json:"tax_exempt,omitempty"` + TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` + ParentId Optional[int] `json:"parent_id"` +} + +func (c *createCustomer) validate() error { + var errs []string + if c.FirstName == nil { + errs = append(errs, "required field `first_name` is missing for type `Create Customer`") + } + if c.LastName == nil { + errs = append(errs, "required field `last_name` is missing for type `Create Customer`") + } + if c.Email == nil { + errs = append(errs, "required field `email` is missing for type `Create Customer`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_customer_request.go b/models/create_customer_request.go index ad7e7ae7..4da9c6dc 100644 --- a/models/create_customer_request.go +++ b/models/create_customer_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateCustomerRequest represents a CreateCustomerRequest struct. type CreateCustomerRequest struct { - Customer CreateCustomer `json:"customer"` + Customer CreateCustomer `json:"customer"` } -// MarshalJSON implements the json.Marshaler interface for CreateCustomerRequest. +// MarshalJSON implements the json.Marshaler interface for CreateCustomerRequest. // It customizes the JSON marshaling process for CreateCustomerRequest objects. func (c *CreateCustomerRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateCustomerRequest object to a map representation for JSON marshaling. func (c *CreateCustomerRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["customer"] = c.Customer.toMap() - return structMap + structMap := make(map[string]any) + structMap["customer"] = c.Customer.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateCustomerRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateCustomerRequest. // It customizes the JSON unmarshaling process for CreateCustomerRequest objects. func (c *CreateCustomerRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Customer CreateCustomer `json:"customer"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Customer = temp.Customer - return nil + var temp createCustomerRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Customer = *temp.Customer + return nil +} + +// TODO +type createCustomerRequest struct { + Customer *CreateCustomer `json:"customer"` +} + +func (c *createCustomerRequest) validate() error { + var errs []string + if c.Customer == nil { + errs = append(errs, "required field `customer` is missing for type `Create Customer Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_ebb_component.go b/models/create_ebb_component.go index 4f07533e..1eaddb0b 100644 --- a/models/create_ebb_component.go +++ b/models/create_ebb_component.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateEBBComponent represents a CreateEBBComponent struct. type CreateEBBComponent struct { - EventBasedComponent EBBComponent `json:"event_based_component"` + EventBasedComponent EBBComponent `json:"event_based_component"` } -// MarshalJSON implements the json.Marshaler interface for CreateEBBComponent. +// MarshalJSON implements the json.Marshaler interface for CreateEBBComponent. // It customizes the JSON marshaling process for CreateEBBComponent objects. func (c *CreateEBBComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateEBBComponent object to a map representation for JSON marshaling. func (c *CreateEBBComponent) toMap() map[string]any { - structMap := make(map[string]any) - structMap["event_based_component"] = c.EventBasedComponent.toMap() - return structMap + structMap := make(map[string]any) + structMap["event_based_component"] = c.EventBasedComponent.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateEBBComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateEBBComponent. // It customizes the JSON unmarshaling process for CreateEBBComponent objects. func (c *CreateEBBComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - EventBasedComponent EBBComponent `json:"event_based_component"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.EventBasedComponent = temp.EventBasedComponent - return nil + var temp createEBBComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.EventBasedComponent = *temp.EventBasedComponent + return nil +} + +// TODO +type createEBBComponent struct { + EventBasedComponent *EBBComponent `json:"event_based_component"` +} + +func (c *createEBBComponent) validate() error { + var errs []string + if c.EventBasedComponent == nil { + errs = append(errs, "required field `event_based_component` is missing for type `Create EBB Component`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_invoice.go b/models/create_invoice.go index 1a3f3bbd..14231981 100644 --- a/models/create_invoice.go +++ b/models/create_invoice.go @@ -1,109 +1,111 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // CreateInvoice represents a CreateInvoice struct. type CreateInvoice struct { - LineItems []CreateInvoiceItem `json:"line_items,omitempty"` - IssueDate *time.Time `json:"issue_date,omitempty"` - // By default, invoices will be created with a due date matching the date of invoice creation. If a different due date is desired, the net_terms parameter can be sent indicating the number of days in advance the due date should be. - NetTerms *int `json:"net_terms,omitempty"` - PaymentInstructions *string `json:"payment_instructions,omitempty"` - // A custom memo can be sent to override the site's default. - Memo *string `json:"memo,omitempty"` - // Overrides the defaults for the site - SellerAddress *CreateInvoiceAddress `json:"seller_address,omitempty"` - // Overrides the default for the customer - BillingAddress *CreateInvoiceAddress `json:"billing_address,omitempty"` - // Overrides the default for the customer - ShippingAddress *CreateInvoiceAddress `json:"shipping_address,omitempty"` - Coupons []CreateInvoiceCoupon `json:"coupons,omitempty"` - Status *CreateInvoiceStatus `json:"status,omitempty"` + LineItems []CreateInvoiceItem `json:"line_items,omitempty"` + IssueDate *time.Time `json:"issue_date,omitempty"` + // By default, invoices will be created with a due date matching the date of invoice creation. If a different due date is desired, the net_terms parameter can be sent indicating the number of days in advance the due date should be. + NetTerms *int `json:"net_terms,omitempty"` + PaymentInstructions *string `json:"payment_instructions,omitempty"` + // A custom memo can be sent to override the site's default. + Memo *string `json:"memo,omitempty"` + // Overrides the defaults for the site + SellerAddress *CreateInvoiceAddress `json:"seller_address,omitempty"` + // Overrides the default for the customer + BillingAddress *CreateInvoiceAddress `json:"billing_address,omitempty"` + // Overrides the default for the customer + ShippingAddress *CreateInvoiceAddress `json:"shipping_address,omitempty"` + Coupons []CreateInvoiceCoupon `json:"coupons,omitempty"` + Status *CreateInvoiceStatus `json:"status,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateInvoice. +// MarshalJSON implements the json.Marshaler interface for CreateInvoice. // It customizes the JSON marshaling process for CreateInvoice objects. func (c *CreateInvoice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateInvoice object to a map representation for JSON marshaling. func (c *CreateInvoice) toMap() map[string]any { - structMap := make(map[string]any) - if c.LineItems != nil { - structMap["line_items"] = c.LineItems - } - if c.IssueDate != nil { - structMap["issue_date"] = c.IssueDate.Format(DEFAULT_DATE) - } - if c.NetTerms != nil { - structMap["net_terms"] = c.NetTerms - } - if c.PaymentInstructions != nil { - structMap["payment_instructions"] = c.PaymentInstructions - } - if c.Memo != nil { - structMap["memo"] = c.Memo - } - if c.SellerAddress != nil { - structMap["seller_address"] = c.SellerAddress.toMap() - } - if c.BillingAddress != nil { - structMap["billing_address"] = c.BillingAddress.toMap() - } - if c.ShippingAddress != nil { - structMap["shipping_address"] = c.ShippingAddress.toMap() - } - if c.Coupons != nil { - structMap["coupons"] = c.Coupons - } - if c.Status != nil { - structMap["status"] = c.Status - } - return structMap + structMap := make(map[string]any) + if c.LineItems != nil { + structMap["line_items"] = c.LineItems + } + if c.IssueDate != nil { + structMap["issue_date"] = c.IssueDate.Format(DEFAULT_DATE) + } + if c.NetTerms != nil { + structMap["net_terms"] = c.NetTerms + } + if c.PaymentInstructions != nil { + structMap["payment_instructions"] = c.PaymentInstructions + } + if c.Memo != nil { + structMap["memo"] = c.Memo + } + if c.SellerAddress != nil { + structMap["seller_address"] = c.SellerAddress.toMap() + } + if c.BillingAddress != nil { + structMap["billing_address"] = c.BillingAddress.toMap() + } + if c.ShippingAddress != nil { + structMap["shipping_address"] = c.ShippingAddress.toMap() + } + if c.Coupons != nil { + structMap["coupons"] = c.Coupons + } + if c.Status != nil { + structMap["status"] = c.Status + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoice. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoice. // It customizes the JSON unmarshaling process for CreateInvoice objects. func (c *CreateInvoice) UnmarshalJSON(input []byte) error { - temp := &struct { - LineItems []CreateInvoiceItem `json:"line_items,omitempty"` - IssueDate *string `json:"issue_date,omitempty"` - NetTerms *int `json:"net_terms,omitempty"` - PaymentInstructions *string `json:"payment_instructions,omitempty"` - Memo *string `json:"memo,omitempty"` - SellerAddress *CreateInvoiceAddress `json:"seller_address,omitempty"` - BillingAddress *CreateInvoiceAddress `json:"billing_address,omitempty"` - ShippingAddress *CreateInvoiceAddress `json:"shipping_address,omitempty"` - Coupons []CreateInvoiceCoupon `json:"coupons,omitempty"` - Status *CreateInvoiceStatus `json:"status,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.LineItems = temp.LineItems - if temp.IssueDate != nil { - IssueDateVal, err := time.Parse(DEFAULT_DATE, *temp.IssueDate) - if err != nil { - log.Fatalf("Cannot Parse issue_date as % s format.", DEFAULT_DATE) - } - c.IssueDate = &IssueDateVal - } - c.NetTerms = temp.NetTerms - c.PaymentInstructions = temp.PaymentInstructions - c.Memo = temp.Memo - c.SellerAddress = temp.SellerAddress - c.BillingAddress = temp.BillingAddress - c.ShippingAddress = temp.ShippingAddress - c.Coupons = temp.Coupons - c.Status = temp.Status - return nil + var temp createInvoice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.LineItems = temp.LineItems + if temp.IssueDate != nil { + IssueDateVal, err := time.Parse(DEFAULT_DATE, *temp.IssueDate) + if err != nil { + log.Fatalf("Cannot Parse issue_date as % s format.", DEFAULT_DATE) + } + c.IssueDate = &IssueDateVal + } + c.NetTerms = temp.NetTerms + c.PaymentInstructions = temp.PaymentInstructions + c.Memo = temp.Memo + c.SellerAddress = temp.SellerAddress + c.BillingAddress = temp.BillingAddress + c.ShippingAddress = temp.ShippingAddress + c.Coupons = temp.Coupons + c.Status = temp.Status + return nil +} + +// TODO +type createInvoice struct { + LineItems []CreateInvoiceItem `json:"line_items,omitempty"` + IssueDate *string `json:"issue_date,omitempty"` + NetTerms *int `json:"net_terms,omitempty"` + PaymentInstructions *string `json:"payment_instructions,omitempty"` + Memo *string `json:"memo,omitempty"` + SellerAddress *CreateInvoiceAddress `json:"seller_address,omitempty"` + BillingAddress *CreateInvoiceAddress `json:"billing_address,omitempty"` + ShippingAddress *CreateInvoiceAddress `json:"shipping_address,omitempty"` + Coupons []CreateInvoiceCoupon `json:"coupons,omitempty"` + Status *CreateInvoiceStatus `json:"status,omitempty"` } diff --git a/models/create_invoice_address.go b/models/create_invoice_address.go index 6967daec..7e922763 100644 --- a/models/create_invoice_address.go +++ b/models/create_invoice_address.go @@ -1,91 +1,93 @@ package models import ( - "encoding/json" + "encoding/json" ) -// CreateInvoiceAddress represents a CreateInvoiceAddress struct. +// CreateInvoiceAddress represents a CreateInvoiceAddress struct. // Overrides the default address. type CreateInvoiceAddress struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Phone *string `json:"phone,omitempty"` - Address *string `json:"address,omitempty"` - Address2 *string `json:"address_2,omitempty"` - City *string `json:"city,omitempty"` - State *string `json:"state,omitempty"` - Zip *string `json:"zip,omitempty"` - Country *string `json:"country,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Phone *string `json:"phone,omitempty"` + Address *string `json:"address,omitempty"` + Address2 *string `json:"address_2,omitempty"` + City *string `json:"city,omitempty"` + State *string `json:"state,omitempty"` + Zip *string `json:"zip,omitempty"` + Country *string `json:"country,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateInvoiceAddress. +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceAddress. // It customizes the JSON marshaling process for CreateInvoiceAddress objects. func (c *CreateInvoiceAddress) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateInvoiceAddress object to a map representation for JSON marshaling. func (c *CreateInvoiceAddress) toMap() map[string]any { - structMap := make(map[string]any) - if c.FirstName != nil { - structMap["first_name"] = c.FirstName - } - if c.LastName != nil { - structMap["last_name"] = c.LastName - } - if c.Phone != nil { - structMap["phone"] = c.Phone - } - if c.Address != nil { - structMap["address"] = c.Address - } - if c.Address2 != nil { - structMap["address_2"] = c.Address2 - } - if c.City != nil { - structMap["city"] = c.City - } - if c.State != nil { - structMap["state"] = c.State - } - if c.Zip != nil { - structMap["zip"] = c.Zip - } - if c.Country != nil { - structMap["country"] = c.Country - } - return structMap + structMap := make(map[string]any) + if c.FirstName != nil { + structMap["first_name"] = c.FirstName + } + if c.LastName != nil { + structMap["last_name"] = c.LastName + } + if c.Phone != nil { + structMap["phone"] = c.Phone + } + if c.Address != nil { + structMap["address"] = c.Address + } + if c.Address2 != nil { + structMap["address_2"] = c.Address2 + } + if c.City != nil { + structMap["city"] = c.City + } + if c.State != nil { + structMap["state"] = c.State + } + if c.Zip != nil { + structMap["zip"] = c.Zip + } + if c.Country != nil { + structMap["country"] = c.Country + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceAddress. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceAddress. // It customizes the JSON unmarshaling process for CreateInvoiceAddress objects. func (c *CreateInvoiceAddress) UnmarshalJSON(input []byte) error { - temp := &struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Phone *string `json:"phone,omitempty"` - Address *string `json:"address,omitempty"` - Address2 *string `json:"address_2,omitempty"` - City *string `json:"city,omitempty"` - State *string `json:"state,omitempty"` - Zip *string `json:"zip,omitempty"` - Country *string `json:"country,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.FirstName = temp.FirstName - c.LastName = temp.LastName - c.Phone = temp.Phone - c.Address = temp.Address - c.Address2 = temp.Address2 - c.City = temp.City - c.State = temp.State - c.Zip = temp.Zip - c.Country = temp.Country - return nil + var temp createInvoiceAddress + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.FirstName = temp.FirstName + c.LastName = temp.LastName + c.Phone = temp.Phone + c.Address = temp.Address + c.Address2 = temp.Address2 + c.City = temp.City + c.State = temp.State + c.Zip = temp.Zip + c.Country = temp.Country + return nil +} + +// TODO +type createInvoiceAddress struct { + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Phone *string `json:"phone,omitempty"` + Address *string `json:"address,omitempty"` + Address2 *string `json:"address_2,omitempty"` + City *string `json:"city,omitempty"` + State *string `json:"state,omitempty"` + Zip *string `json:"zip,omitempty"` + Country *string `json:"country,omitempty"` } diff --git a/models/create_invoice_coupon.go b/models/create_invoice_coupon.go index ba536950..19a6f1f5 100644 --- a/models/create_invoice_coupon.go +++ b/models/create_invoice_coupon.go @@ -1,72 +1,74 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreateInvoiceCoupon represents a CreateInvoiceCoupon struct. type CreateInvoiceCoupon struct { - Code *string `json:"code,omitempty"` - Percentage *interface{} `json:"percentage,omitempty"` - Amount *interface{} `json:"amount,omitempty"` - Description *string `json:"description,omitempty"` - ProductFamilyId *interface{} `json:"product_family_id,omitempty"` - CompoundingStrategy *CompoundingStrategy `json:"compounding_strategy,omitempty"` + Code *string `json:"code,omitempty"` + Percentage *CreateInvoiceCouponPercentage `json:"percentage,omitempty"` + Amount *CreateInvoiceCouponAmount `json:"amount,omitempty"` + Description *string `json:"description,omitempty"` + ProductFamilyId *CreateInvoiceCouponProductFamilyId `json:"product_family_id,omitempty"` + CompoundingStrategy *CompoundingStrategy `json:"compounding_strategy,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateInvoiceCoupon. +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceCoupon. // It customizes the JSON marshaling process for CreateInvoiceCoupon objects. func (c *CreateInvoiceCoupon) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateInvoiceCoupon object to a map representation for JSON marshaling. func (c *CreateInvoiceCoupon) toMap() map[string]any { - structMap := make(map[string]any) - if c.Code != nil { - structMap["code"] = c.Code - } - if c.Percentage != nil { - structMap["percentage"] = c.Percentage - } - if c.Amount != nil { - structMap["amount"] = c.Amount - } - if c.Description != nil { - structMap["description"] = c.Description - } - if c.ProductFamilyId != nil { - structMap["product_family_id"] = c.ProductFamilyId - } - if c.CompoundingStrategy != nil { - structMap["compounding_strategy"] = c.CompoundingStrategy - } - return structMap + structMap := make(map[string]any) + if c.Code != nil { + structMap["code"] = c.Code + } + if c.Percentage != nil { + structMap["percentage"] = c.Percentage.toMap() + } + if c.Amount != nil { + structMap["amount"] = c.Amount.toMap() + } + if c.Description != nil { + structMap["description"] = c.Description + } + if c.ProductFamilyId != nil { + structMap["product_family_id"] = c.ProductFamilyId.toMap() + } + if c.CompoundingStrategy != nil { + structMap["compounding_strategy"] = c.CompoundingStrategy + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceCoupon. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceCoupon. // It customizes the JSON unmarshaling process for CreateInvoiceCoupon objects. func (c *CreateInvoiceCoupon) UnmarshalJSON(input []byte) error { - temp := &struct { - Code *string `json:"code,omitempty"` - Percentage *interface{} `json:"percentage,omitempty"` - Amount *interface{} `json:"amount,omitempty"` - Description *string `json:"description,omitempty"` - ProductFamilyId *interface{} `json:"product_family_id,omitempty"` - CompoundingStrategy *CompoundingStrategy `json:"compounding_strategy,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Code = temp.Code - c.Percentage = temp.Percentage - c.Amount = temp.Amount - c.Description = temp.Description - c.ProductFamilyId = temp.ProductFamilyId - c.CompoundingStrategy = temp.CompoundingStrategy - return nil + var temp createInvoiceCoupon + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Code = temp.Code + c.Percentage = temp.Percentage + c.Amount = temp.Amount + c.Description = temp.Description + c.ProductFamilyId = temp.ProductFamilyId + c.CompoundingStrategy = temp.CompoundingStrategy + return nil +} + +// TODO +type createInvoiceCoupon struct { + Code *string `json:"code,omitempty"` + Percentage *CreateInvoiceCouponPercentage `json:"percentage,omitempty"` + Amount *CreateInvoiceCouponAmount `json:"amount,omitempty"` + Description *string `json:"description,omitempty"` + ProductFamilyId *CreateInvoiceCouponProductFamilyId `json:"product_family_id,omitempty"` + CompoundingStrategy *CompoundingStrategy `json:"compounding_strategy,omitempty"` } diff --git a/models/create_invoice_coupon_amount.go b/models/create_invoice_coupon_amount.go new file mode 100644 index 00000000..87d33117 --- /dev/null +++ b/models/create_invoice_coupon_amount.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateInvoiceCouponAmount represents a CreateInvoiceCouponAmount struct. +// This is a container for one-of cases. +type CreateInvoiceCouponAmount struct { + value any + isString bool + isPrecision bool +} + +// String converts the CreateInvoiceCouponAmount object to a string representation. +func (c CreateInvoiceCouponAmount) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceCouponAmount. +// It customizes the JSON marshaling process for CreateInvoiceCouponAmount objects. +func (c *CreateInvoiceCouponAmount) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateInvoiceCouponAmountContainer.From*` functions to initialize the CreateInvoiceCouponAmount object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateInvoiceCouponAmount object to a map representation for JSON marshaling. +func (c *CreateInvoiceCouponAmount) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceCouponAmount. +// It customizes the JSON unmarshaling process for CreateInvoiceCouponAmount objects. +func (c *CreateInvoiceCouponAmount) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(float64), false, &c.isPrecision), + ) + + c.value = result + return err +} + +func (c *CreateInvoiceCouponAmount) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateInvoiceCouponAmount) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +// internalCreateInvoiceCouponAmount represents a createInvoiceCouponAmount struct. +// This is a container for one-of cases. +type internalCreateInvoiceCouponAmount struct{} + +var CreateInvoiceCouponAmountContainer internalCreateInvoiceCouponAmount + +func (c *internalCreateInvoiceCouponAmount) FromString(val string) CreateInvoiceCouponAmount { + return CreateInvoiceCouponAmount{value: &val} +} + +func (c *internalCreateInvoiceCouponAmount) FromPrecision(val float64) CreateInvoiceCouponAmount { + return CreateInvoiceCouponAmount{value: &val} +} diff --git a/models/create_invoice_coupon_percentage.go b/models/create_invoice_coupon_percentage.go new file mode 100644 index 00000000..a4c578b8 --- /dev/null +++ b/models/create_invoice_coupon_percentage.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateInvoiceCouponPercentage represents a CreateInvoiceCouponPercentage struct. +// This is a container for one-of cases. +type CreateInvoiceCouponPercentage struct { + value any + isString bool + isPrecision bool +} + +// String converts the CreateInvoiceCouponPercentage object to a string representation. +func (c CreateInvoiceCouponPercentage) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceCouponPercentage. +// It customizes the JSON marshaling process for CreateInvoiceCouponPercentage objects. +func (c *CreateInvoiceCouponPercentage) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateInvoiceCouponPercentageContainer.From*` functions to initialize the CreateInvoiceCouponPercentage object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateInvoiceCouponPercentage object to a map representation for JSON marshaling. +func (c *CreateInvoiceCouponPercentage) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceCouponPercentage. +// It customizes the JSON unmarshaling process for CreateInvoiceCouponPercentage objects. +func (c *CreateInvoiceCouponPercentage) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(float64), false, &c.isPrecision), + ) + + c.value = result + return err +} + +func (c *CreateInvoiceCouponPercentage) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateInvoiceCouponPercentage) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +// internalCreateInvoiceCouponPercentage represents a createInvoiceCouponPercentage struct. +// This is a container for one-of cases. +type internalCreateInvoiceCouponPercentage struct{} + +var CreateInvoiceCouponPercentageContainer internalCreateInvoiceCouponPercentage + +func (c *internalCreateInvoiceCouponPercentage) FromString(val string) CreateInvoiceCouponPercentage { + return CreateInvoiceCouponPercentage{value: &val} +} + +func (c *internalCreateInvoiceCouponPercentage) FromPrecision(val float64) CreateInvoiceCouponPercentage { + return CreateInvoiceCouponPercentage{value: &val} +} diff --git a/models/create_invoice_coupon_product_family_id.go b/models/create_invoice_coupon_product_family_id.go new file mode 100644 index 00000000..7f2276cf --- /dev/null +++ b/models/create_invoice_coupon_product_family_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateInvoiceCouponProductFamilyId represents a CreateInvoiceCouponProductFamilyId struct. +// This is a container for one-of cases. +type CreateInvoiceCouponProductFamilyId struct { + value any + isString bool + isNumber bool +} + +// String converts the CreateInvoiceCouponProductFamilyId object to a string representation. +func (c CreateInvoiceCouponProductFamilyId) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceCouponProductFamilyId. +// It customizes the JSON marshaling process for CreateInvoiceCouponProductFamilyId objects. +func (c *CreateInvoiceCouponProductFamilyId) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateInvoiceCouponProductFamilyIdContainer.From*` functions to initialize the CreateInvoiceCouponProductFamilyId object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateInvoiceCouponProductFamilyId object to a map representation for JSON marshaling. +func (c *CreateInvoiceCouponProductFamilyId) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceCouponProductFamilyId. +// It customizes the JSON unmarshaling process for CreateInvoiceCouponProductFamilyId objects. +func (c *CreateInvoiceCouponProductFamilyId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(int), false, &c.isNumber), + ) + + c.value = result + return err +} + +func (c *CreateInvoiceCouponProductFamilyId) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateInvoiceCouponProductFamilyId) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +// internalCreateInvoiceCouponProductFamilyId represents a createInvoiceCouponProductFamilyId struct. +// This is a container for one-of cases. +type internalCreateInvoiceCouponProductFamilyId struct{} + +var CreateInvoiceCouponProductFamilyIdContainer internalCreateInvoiceCouponProductFamilyId + +func (c *internalCreateInvoiceCouponProductFamilyId) FromString(val string) CreateInvoiceCouponProductFamilyId { + return CreateInvoiceCouponProductFamilyId{value: &val} +} + +func (c *internalCreateInvoiceCouponProductFamilyId) FromNumber(val int) CreateInvoiceCouponProductFamilyId { + return CreateInvoiceCouponProductFamilyId{value: &val} +} diff --git a/models/create_invoice_item.go b/models/create_invoice_item.go index 0cb980a3..d724fa03 100644 --- a/models/create_invoice_item.go +++ b/models/create_invoice_item.go @@ -1,117 +1,119 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreateInvoiceItem represents a CreateInvoiceItem struct. type CreateInvoiceItem struct { - Title *string `json:"title,omitempty"` - // The quantity can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065. If you submit a value with more than 8 decimal places, we will round it down to the 8th decimal place. - Quantity *interface{} `json:"quantity,omitempty"` - // The unit_price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065. If you submit a value with more than 8 decimal places, we will round it down to the 8th decimal place. - UnitPrice *interface{} `json:"unit_price,omitempty"` - // Set to true to automatically calculate taxes. Site must be configured to use and calculate taxes. - // If using Avalara, a tax_code parameter must also be sent. - Taxable *bool `json:"taxable,omitempty"` - TaxCode *string `json:"tax_code,omitempty"` - // YYYY-MM-DD - PeriodRangeStart *string `json:"period_range_start,omitempty"` - // YYYY-MM-DD - PeriodRangeEnd *string `json:"period_range_end,omitempty"` - // Product handle or product id. - ProductId *interface{} `json:"product_id,omitempty"` - // Component handle or component id. - ComponentId *interface{} `json:"component_id,omitempty"` - // Price point handle or id. For component. - PricePointId *interface{} `json:"price_point_id,omitempty"` - ProductPricePointId *interface{} `json:"product_price_point_id,omitempty"` - Description *string `json:"description,omitempty"` + Title *string `json:"title,omitempty"` + // The quantity can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065. If you submit a value with more than 8 decimal places, we will round it down to the 8th decimal place. + Quantity *CreateInvoiceItemQuantity `json:"quantity,omitempty"` + // The unit_price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065. If you submit a value with more than 8 decimal places, we will round it down to the 8th decimal place. + UnitPrice *CreateInvoiceItemUnitPrice `json:"unit_price,omitempty"` + // Set to true to automatically calculate taxes. Site must be configured to use and calculate taxes. + // If using Avalara, a tax_code parameter must also be sent. + Taxable *bool `json:"taxable,omitempty"` + TaxCode *string `json:"tax_code,omitempty"` + // YYYY-MM-DD + PeriodRangeStart *string `json:"period_range_start,omitempty"` + // YYYY-MM-DD + PeriodRangeEnd *string `json:"period_range_end,omitempty"` + // Product handle or product id. + ProductId *CreateInvoiceItemProductId `json:"product_id,omitempty"` + // Component handle or component id. + ComponentId *CreateInvoiceItemComponentId `json:"component_id,omitempty"` + // Price point handle or id. For component. + PricePointId *CreateInvoiceItemPricePointId `json:"price_point_id,omitempty"` + ProductPricePointId *CreateInvoiceItemProductPricePointId `json:"product_price_point_id,omitempty"` + Description *string `json:"description,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateInvoiceItem. +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceItem. // It customizes the JSON marshaling process for CreateInvoiceItem objects. func (c *CreateInvoiceItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateInvoiceItem object to a map representation for JSON marshaling. func (c *CreateInvoiceItem) toMap() map[string]any { - structMap := make(map[string]any) - if c.Title != nil { - structMap["title"] = c.Title - } - if c.Quantity != nil { - structMap["quantity"] = c.Quantity - } - if c.UnitPrice != nil { - structMap["unit_price"] = c.UnitPrice - } - if c.Taxable != nil { - structMap["taxable"] = c.Taxable - } - if c.TaxCode != nil { - structMap["tax_code"] = c.TaxCode - } - if c.PeriodRangeStart != nil { - structMap["period_range_start"] = c.PeriodRangeStart - } - if c.PeriodRangeEnd != nil { - structMap["period_range_end"] = c.PeriodRangeEnd - } - if c.ProductId != nil { - structMap["product_id"] = c.ProductId - } - if c.ComponentId != nil { - structMap["component_id"] = c.ComponentId - } - if c.PricePointId != nil { - structMap["price_point_id"] = c.PricePointId - } - if c.ProductPricePointId != nil { - structMap["product_price_point_id"] = c.ProductPricePointId - } - if c.Description != nil { - structMap["description"] = c.Description - } - return structMap + structMap := make(map[string]any) + if c.Title != nil { + structMap["title"] = c.Title + } + if c.Quantity != nil { + structMap["quantity"] = c.Quantity.toMap() + } + if c.UnitPrice != nil { + structMap["unit_price"] = c.UnitPrice.toMap() + } + if c.Taxable != nil { + structMap["taxable"] = c.Taxable + } + if c.TaxCode != nil { + structMap["tax_code"] = c.TaxCode + } + if c.PeriodRangeStart != nil { + structMap["period_range_start"] = c.PeriodRangeStart + } + if c.PeriodRangeEnd != nil { + structMap["period_range_end"] = c.PeriodRangeEnd + } + if c.ProductId != nil { + structMap["product_id"] = c.ProductId.toMap() + } + if c.ComponentId != nil { + structMap["component_id"] = c.ComponentId.toMap() + } + if c.PricePointId != nil { + structMap["price_point_id"] = c.PricePointId.toMap() + } + if c.ProductPricePointId != nil { + structMap["product_price_point_id"] = c.ProductPricePointId.toMap() + } + if c.Description != nil { + structMap["description"] = c.Description + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceItem. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceItem. // It customizes the JSON unmarshaling process for CreateInvoiceItem objects. func (c *CreateInvoiceItem) UnmarshalJSON(input []byte) error { - temp := &struct { - Title *string `json:"title,omitempty"` - Quantity *interface{} `json:"quantity,omitempty"` - UnitPrice *interface{} `json:"unit_price,omitempty"` - Taxable *bool `json:"taxable,omitempty"` - TaxCode *string `json:"tax_code,omitempty"` - PeriodRangeStart *string `json:"period_range_start,omitempty"` - PeriodRangeEnd *string `json:"period_range_end,omitempty"` - ProductId *interface{} `json:"product_id,omitempty"` - ComponentId *interface{} `json:"component_id,omitempty"` - PricePointId *interface{} `json:"price_point_id,omitempty"` - ProductPricePointId *interface{} `json:"product_price_point_id,omitempty"` - Description *string `json:"description,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Title = temp.Title - c.Quantity = temp.Quantity - c.UnitPrice = temp.UnitPrice - c.Taxable = temp.Taxable - c.TaxCode = temp.TaxCode - c.PeriodRangeStart = temp.PeriodRangeStart - c.PeriodRangeEnd = temp.PeriodRangeEnd - c.ProductId = temp.ProductId - c.ComponentId = temp.ComponentId - c.PricePointId = temp.PricePointId - c.ProductPricePointId = temp.ProductPricePointId - c.Description = temp.Description - return nil + var temp createInvoiceItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Title = temp.Title + c.Quantity = temp.Quantity + c.UnitPrice = temp.UnitPrice + c.Taxable = temp.Taxable + c.TaxCode = temp.TaxCode + c.PeriodRangeStart = temp.PeriodRangeStart + c.PeriodRangeEnd = temp.PeriodRangeEnd + c.ProductId = temp.ProductId + c.ComponentId = temp.ComponentId + c.PricePointId = temp.PricePointId + c.ProductPricePointId = temp.ProductPricePointId + c.Description = temp.Description + return nil +} + +// TODO +type createInvoiceItem struct { + Title *string `json:"title,omitempty"` + Quantity *CreateInvoiceItemQuantity `json:"quantity,omitempty"` + UnitPrice *CreateInvoiceItemUnitPrice `json:"unit_price,omitempty"` + Taxable *bool `json:"taxable,omitempty"` + TaxCode *string `json:"tax_code,omitempty"` + PeriodRangeStart *string `json:"period_range_start,omitempty"` + PeriodRangeEnd *string `json:"period_range_end,omitempty"` + ProductId *CreateInvoiceItemProductId `json:"product_id,omitempty"` + ComponentId *CreateInvoiceItemComponentId `json:"component_id,omitempty"` + PricePointId *CreateInvoiceItemPricePointId `json:"price_point_id,omitempty"` + ProductPricePointId *CreateInvoiceItemProductPricePointId `json:"product_price_point_id,omitempty"` + Description *string `json:"description,omitempty"` } diff --git a/models/create_invoice_item_component_id.go b/models/create_invoice_item_component_id.go new file mode 100644 index 00000000..f2278f27 --- /dev/null +++ b/models/create_invoice_item_component_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateInvoiceItemComponentId represents a CreateInvoiceItemComponentId struct. +// This is a container for one-of cases. +type CreateInvoiceItemComponentId struct { + value any + isString bool + isNumber bool +} + +// String converts the CreateInvoiceItemComponentId object to a string representation. +func (c CreateInvoiceItemComponentId) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceItemComponentId. +// It customizes the JSON marshaling process for CreateInvoiceItemComponentId objects. +func (c *CreateInvoiceItemComponentId) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateInvoiceItemComponentIdContainer.From*` functions to initialize the CreateInvoiceItemComponentId object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateInvoiceItemComponentId object to a map representation for JSON marshaling. +func (c *CreateInvoiceItemComponentId) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceItemComponentId. +// It customizes the JSON unmarshaling process for CreateInvoiceItemComponentId objects. +func (c *CreateInvoiceItemComponentId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(int), false, &c.isNumber), + ) + + c.value = result + return err +} + +func (c *CreateInvoiceItemComponentId) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateInvoiceItemComponentId) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +// internalCreateInvoiceItemComponentId represents a createInvoiceItemComponentId struct. +// This is a container for one-of cases. +type internalCreateInvoiceItemComponentId struct{} + +var CreateInvoiceItemComponentIdContainer internalCreateInvoiceItemComponentId + +func (c *internalCreateInvoiceItemComponentId) FromString(val string) CreateInvoiceItemComponentId { + return CreateInvoiceItemComponentId{value: &val} +} + +func (c *internalCreateInvoiceItemComponentId) FromNumber(val int) CreateInvoiceItemComponentId { + return CreateInvoiceItemComponentId{value: &val} +} diff --git a/models/create_invoice_item_price_point_id.go b/models/create_invoice_item_price_point_id.go new file mode 100644 index 00000000..28b7bd9f --- /dev/null +++ b/models/create_invoice_item_price_point_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateInvoiceItemPricePointId represents a CreateInvoiceItemPricePointId struct. +// This is a container for one-of cases. +type CreateInvoiceItemPricePointId struct { + value any + isString bool + isNumber bool +} + +// String converts the CreateInvoiceItemPricePointId object to a string representation. +func (c CreateInvoiceItemPricePointId) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceItemPricePointId. +// It customizes the JSON marshaling process for CreateInvoiceItemPricePointId objects. +func (c *CreateInvoiceItemPricePointId) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateInvoiceItemPricePointIdContainer.From*` functions to initialize the CreateInvoiceItemPricePointId object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateInvoiceItemPricePointId object to a map representation for JSON marshaling. +func (c *CreateInvoiceItemPricePointId) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceItemPricePointId. +// It customizes the JSON unmarshaling process for CreateInvoiceItemPricePointId objects. +func (c *CreateInvoiceItemPricePointId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(int), false, &c.isNumber), + ) + + c.value = result + return err +} + +func (c *CreateInvoiceItemPricePointId) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateInvoiceItemPricePointId) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +// internalCreateInvoiceItemPricePointId represents a createInvoiceItemPricePointId struct. +// This is a container for one-of cases. +type internalCreateInvoiceItemPricePointId struct{} + +var CreateInvoiceItemPricePointIdContainer internalCreateInvoiceItemPricePointId + +func (c *internalCreateInvoiceItemPricePointId) FromString(val string) CreateInvoiceItemPricePointId { + return CreateInvoiceItemPricePointId{value: &val} +} + +func (c *internalCreateInvoiceItemPricePointId) FromNumber(val int) CreateInvoiceItemPricePointId { + return CreateInvoiceItemPricePointId{value: &val} +} diff --git a/models/create_invoice_item_product_id.go b/models/create_invoice_item_product_id.go new file mode 100644 index 00000000..59327019 --- /dev/null +++ b/models/create_invoice_item_product_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateInvoiceItemProductId represents a CreateInvoiceItemProductId struct. +// This is a container for one-of cases. +type CreateInvoiceItemProductId struct { + value any + isString bool + isNumber bool +} + +// String converts the CreateInvoiceItemProductId object to a string representation. +func (c CreateInvoiceItemProductId) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceItemProductId. +// It customizes the JSON marshaling process for CreateInvoiceItemProductId objects. +func (c *CreateInvoiceItemProductId) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateInvoiceItemProductIdContainer.From*` functions to initialize the CreateInvoiceItemProductId object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateInvoiceItemProductId object to a map representation for JSON marshaling. +func (c *CreateInvoiceItemProductId) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceItemProductId. +// It customizes the JSON unmarshaling process for CreateInvoiceItemProductId objects. +func (c *CreateInvoiceItemProductId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(int), false, &c.isNumber), + ) + + c.value = result + return err +} + +func (c *CreateInvoiceItemProductId) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateInvoiceItemProductId) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +// internalCreateInvoiceItemProductId represents a createInvoiceItemProductId struct. +// This is a container for one-of cases. +type internalCreateInvoiceItemProductId struct{} + +var CreateInvoiceItemProductIdContainer internalCreateInvoiceItemProductId + +func (c *internalCreateInvoiceItemProductId) FromString(val string) CreateInvoiceItemProductId { + return CreateInvoiceItemProductId{value: &val} +} + +func (c *internalCreateInvoiceItemProductId) FromNumber(val int) CreateInvoiceItemProductId { + return CreateInvoiceItemProductId{value: &val} +} diff --git a/models/create_invoice_item_product_price_point_id.go b/models/create_invoice_item_product_price_point_id.go new file mode 100644 index 00000000..b86dd0a2 --- /dev/null +++ b/models/create_invoice_item_product_price_point_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateInvoiceItemProductPricePointId represents a CreateInvoiceItemProductPricePointId struct. +// This is a container for one-of cases. +type CreateInvoiceItemProductPricePointId struct { + value any + isString bool + isNumber bool +} + +// String converts the CreateInvoiceItemProductPricePointId object to a string representation. +func (c CreateInvoiceItemProductPricePointId) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceItemProductPricePointId. +// It customizes the JSON marshaling process for CreateInvoiceItemProductPricePointId objects. +func (c *CreateInvoiceItemProductPricePointId) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateInvoiceItemProductPricePointIdContainer.From*` functions to initialize the CreateInvoiceItemProductPricePointId object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateInvoiceItemProductPricePointId object to a map representation for JSON marshaling. +func (c *CreateInvoiceItemProductPricePointId) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceItemProductPricePointId. +// It customizes the JSON unmarshaling process for CreateInvoiceItemProductPricePointId objects. +func (c *CreateInvoiceItemProductPricePointId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(int), false, &c.isNumber), + ) + + c.value = result + return err +} + +func (c *CreateInvoiceItemProductPricePointId) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateInvoiceItemProductPricePointId) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +// internalCreateInvoiceItemProductPricePointId represents a createInvoiceItemProductPricePointId struct. +// This is a container for one-of cases. +type internalCreateInvoiceItemProductPricePointId struct{} + +var CreateInvoiceItemProductPricePointIdContainer internalCreateInvoiceItemProductPricePointId + +func (c *internalCreateInvoiceItemProductPricePointId) FromString(val string) CreateInvoiceItemProductPricePointId { + return CreateInvoiceItemProductPricePointId{value: &val} +} + +func (c *internalCreateInvoiceItemProductPricePointId) FromNumber(val int) CreateInvoiceItemProductPricePointId { + return CreateInvoiceItemProductPricePointId{value: &val} +} diff --git a/models/create_invoice_item_quantity.go b/models/create_invoice_item_quantity.go new file mode 100644 index 00000000..77787648 --- /dev/null +++ b/models/create_invoice_item_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateInvoiceItemQuantity represents a CreateInvoiceItemQuantity struct. +// This is a container for one-of cases. +type CreateInvoiceItemQuantity struct { + value any + isPrecision bool + isString bool +} + +// String converts the CreateInvoiceItemQuantity object to a string representation. +func (c CreateInvoiceItemQuantity) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceItemQuantity. +// It customizes the JSON marshaling process for CreateInvoiceItemQuantity objects. +func (c *CreateInvoiceItemQuantity) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateInvoiceItemQuantityContainer.From*` functions to initialize the CreateInvoiceItemQuantity object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateInvoiceItemQuantity object to a map representation for JSON marshaling. +func (c *CreateInvoiceItemQuantity) toMap() any { + switch obj := c.value.(type) { + case *float64: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceItemQuantity. +// It customizes the JSON unmarshaling process for CreateInvoiceItemQuantity objects. +func (c *CreateInvoiceItemQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(float64), false, &c.isPrecision), + NewTypeHolder(new(string), false, &c.isString), + ) + + c.value = result + return err +} + +func (c *CreateInvoiceItemQuantity) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +func (c *CreateInvoiceItemQuantity) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +// internalCreateInvoiceItemQuantity represents a createInvoiceItemQuantity struct. +// This is a container for one-of cases. +type internalCreateInvoiceItemQuantity struct{} + +var CreateInvoiceItemQuantityContainer internalCreateInvoiceItemQuantity + +func (c *internalCreateInvoiceItemQuantity) FromPrecision(val float64) CreateInvoiceItemQuantity { + return CreateInvoiceItemQuantity{value: &val} +} + +func (c *internalCreateInvoiceItemQuantity) FromString(val string) CreateInvoiceItemQuantity { + return CreateInvoiceItemQuantity{value: &val} +} diff --git a/models/create_invoice_item_unit_price.go b/models/create_invoice_item_unit_price.go new file mode 100644 index 00000000..ffe44a55 --- /dev/null +++ b/models/create_invoice_item_unit_price.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateInvoiceItemUnitPrice represents a CreateInvoiceItemUnitPrice struct. +// This is a container for one-of cases. +type CreateInvoiceItemUnitPrice struct { + value any + isPrecision bool + isString bool +} + +// String converts the CreateInvoiceItemUnitPrice object to a string representation. +func (c CreateInvoiceItemUnitPrice) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceItemUnitPrice. +// It customizes the JSON marshaling process for CreateInvoiceItemUnitPrice objects. +func (c *CreateInvoiceItemUnitPrice) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateInvoiceItemUnitPriceContainer.From*` functions to initialize the CreateInvoiceItemUnitPrice object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateInvoiceItemUnitPrice object to a map representation for JSON marshaling. +func (c *CreateInvoiceItemUnitPrice) toMap() any { + switch obj := c.value.(type) { + case *float64: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceItemUnitPrice. +// It customizes the JSON unmarshaling process for CreateInvoiceItemUnitPrice objects. +func (c *CreateInvoiceItemUnitPrice) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(float64), false, &c.isPrecision), + NewTypeHolder(new(string), false, &c.isString), + ) + + c.value = result + return err +} + +func (c *CreateInvoiceItemUnitPrice) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +func (c *CreateInvoiceItemUnitPrice) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +// internalCreateInvoiceItemUnitPrice represents a createInvoiceItemUnitPrice struct. +// This is a container for one-of cases. +type internalCreateInvoiceItemUnitPrice struct{} + +var CreateInvoiceItemUnitPriceContainer internalCreateInvoiceItemUnitPrice + +func (c *internalCreateInvoiceItemUnitPrice) FromPrecision(val float64) CreateInvoiceItemUnitPrice { + return CreateInvoiceItemUnitPrice{value: &val} +} + +func (c *internalCreateInvoiceItemUnitPrice) FromString(val string) CreateInvoiceItemUnitPrice { + return CreateInvoiceItemUnitPrice{value: &val} +} diff --git a/models/create_invoice_payment.go b/models/create_invoice_payment.go index a1070417..3ba057cf 100644 --- a/models/create_invoice_payment.go +++ b/models/create_invoice_payment.go @@ -1,71 +1,73 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreateInvoicePayment represents a CreateInvoicePayment struct. type CreateInvoicePayment struct { - // A string of the dollar amount to be refunded (eg. "10.50" => $10.50) - Amount *interface{} `json:"amount,omitempty"` - // A description to be attached to the payment. - Memo *string `json:"memo,omitempty"` - // The type of payment method used. Defaults to other. - Method *InvoicePaymentMethodType `json:"method,omitempty"` - // Additional information related to the payment method (eg. Check #) - Details *string `json:"details,omitempty"` - // The ID of the payment profile to be used for the payment. - PaymentProfileId *int `json:"payment_profile_id,omitempty"` + // A string of the dollar amount to be refunded (eg. "10.50" => $10.50) + Amount *CreateInvoicePaymentAmount `json:"amount,omitempty"` + // A description to be attached to the payment. + Memo *string `json:"memo,omitempty"` + // The type of payment method used. Defaults to other. + Method *InvoicePaymentMethodType `json:"method,omitempty"` + // Additional information related to the payment method (eg. Check #) + Details *string `json:"details,omitempty"` + // The ID of the payment profile to be used for the payment. + PaymentProfileId *int `json:"payment_profile_id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateInvoicePayment. +// MarshalJSON implements the json.Marshaler interface for CreateInvoicePayment. // It customizes the JSON marshaling process for CreateInvoicePayment objects. func (c *CreateInvoicePayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateInvoicePayment object to a map representation for JSON marshaling. func (c *CreateInvoicePayment) toMap() map[string]any { - structMap := make(map[string]any) - if c.Amount != nil { - structMap["amount"] = c.Amount - } - if c.Memo != nil { - structMap["memo"] = c.Memo - } - if c.Method != nil { - structMap["method"] = c.Method - } - if c.Details != nil { - structMap["details"] = c.Details - } - if c.PaymentProfileId != nil { - structMap["payment_profile_id"] = c.PaymentProfileId - } - return structMap + structMap := make(map[string]any) + if c.Amount != nil { + structMap["amount"] = c.Amount.toMap() + } + if c.Memo != nil { + structMap["memo"] = c.Memo + } + if c.Method != nil { + structMap["method"] = c.Method + } + if c.Details != nil { + structMap["details"] = c.Details + } + if c.PaymentProfileId != nil { + structMap["payment_profile_id"] = c.PaymentProfileId + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoicePayment. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoicePayment. // It customizes the JSON unmarshaling process for CreateInvoicePayment objects. func (c *CreateInvoicePayment) UnmarshalJSON(input []byte) error { - temp := &struct { - Amount *interface{} `json:"amount,omitempty"` - Memo *string `json:"memo,omitempty"` - Method *InvoicePaymentMethodType `json:"method,omitempty"` - Details *string `json:"details,omitempty"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Amount = temp.Amount - c.Memo = temp.Memo - c.Method = temp.Method - c.Details = temp.Details - c.PaymentProfileId = temp.PaymentProfileId - return nil + var temp createInvoicePayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Amount = temp.Amount + c.Memo = temp.Memo + c.Method = temp.Method + c.Details = temp.Details + c.PaymentProfileId = temp.PaymentProfileId + return nil +} + +// TODO +type createInvoicePayment struct { + Amount *CreateInvoicePaymentAmount `json:"amount,omitempty"` + Memo *string `json:"memo,omitempty"` + Method *InvoicePaymentMethodType `json:"method,omitempty"` + Details *string `json:"details,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` } diff --git a/models/create_invoice_payment_amount.go b/models/create_invoice_payment_amount.go new file mode 100644 index 00000000..a579539e --- /dev/null +++ b/models/create_invoice_payment_amount.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateInvoicePaymentAmount represents a CreateInvoicePaymentAmount struct. +// This is a container for one-of cases. +type CreateInvoicePaymentAmount struct { + value any + isString bool + isPrecision bool +} + +// String converts the CreateInvoicePaymentAmount object to a string representation. +func (c CreateInvoicePaymentAmount) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateInvoicePaymentAmount. +// It customizes the JSON marshaling process for CreateInvoicePaymentAmount objects. +func (c *CreateInvoicePaymentAmount) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateInvoicePaymentAmountContainer.From*` functions to initialize the CreateInvoicePaymentAmount object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateInvoicePaymentAmount object to a map representation for JSON marshaling. +func (c *CreateInvoicePaymentAmount) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoicePaymentAmount. +// It customizes the JSON unmarshaling process for CreateInvoicePaymentAmount objects. +func (c *CreateInvoicePaymentAmount) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(float64), false, &c.isPrecision), + ) + + c.value = result + return err +} + +func (c *CreateInvoicePaymentAmount) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateInvoicePaymentAmount) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +// internalCreateInvoicePaymentAmount represents a createInvoicePaymentAmount struct. +// This is a container for one-of cases. +type internalCreateInvoicePaymentAmount struct{} + +var CreateInvoicePaymentAmountContainer internalCreateInvoicePaymentAmount + +func (c *internalCreateInvoicePaymentAmount) FromString(val string) CreateInvoicePaymentAmount { + return CreateInvoicePaymentAmount{value: &val} +} + +func (c *internalCreateInvoicePaymentAmount) FromPrecision(val float64) CreateInvoicePaymentAmount { + return CreateInvoicePaymentAmount{value: &val} +} diff --git a/models/create_invoice_payment_application.go b/models/create_invoice_payment_application.go index d7b5c2d0..d6fa81b2 100644 --- a/models/create_invoice_payment_application.go +++ b/models/create_invoice_payment_application.go @@ -1,46 +1,69 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateInvoicePaymentApplication represents a CreateInvoicePaymentApplication struct. type CreateInvoicePaymentApplication struct { - // Unique identifier for the invoice. It has the prefix "inv_" followed by alphanumeric characters. - InvoiceUid string `json:"invoice_uid"` - // Dollar amount of the invoice payment (eg. "10.50" => $10.50). - Amount string `json:"amount"` + // Unique identifier for the invoice. It has the prefix "inv_" followed by alphanumeric characters. + InvoiceUid string `json:"invoice_uid"` + // Dollar amount of the invoice payment (eg. "10.50" => $10.50). + Amount string `json:"amount"` } -// MarshalJSON implements the json.Marshaler interface for CreateInvoicePaymentApplication. +// MarshalJSON implements the json.Marshaler interface for CreateInvoicePaymentApplication. // It customizes the JSON marshaling process for CreateInvoicePaymentApplication objects. func (c *CreateInvoicePaymentApplication) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateInvoicePaymentApplication object to a map representation for JSON marshaling. func (c *CreateInvoicePaymentApplication) toMap() map[string]any { - structMap := make(map[string]any) - structMap["invoice_uid"] = c.InvoiceUid - structMap["amount"] = c.Amount - return structMap + structMap := make(map[string]any) + structMap["invoice_uid"] = c.InvoiceUid + structMap["amount"] = c.Amount + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoicePaymentApplication. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoicePaymentApplication. // It customizes the JSON unmarshaling process for CreateInvoicePaymentApplication objects. func (c *CreateInvoicePaymentApplication) UnmarshalJSON(input []byte) error { - temp := &struct { - InvoiceUid string `json:"invoice_uid"` - Amount string `json:"amount"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.InvoiceUid = temp.InvoiceUid - c.Amount = temp.Amount - return nil + var temp createInvoicePaymentApplication + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.InvoiceUid = *temp.InvoiceUid + c.Amount = *temp.Amount + return nil +} + +// TODO +type createInvoicePaymentApplication struct { + InvoiceUid *string `json:"invoice_uid"` + Amount *string `json:"amount"` +} + +func (c *createInvoicePaymentApplication) validate() error { + var errs []string + if c.InvoiceUid == nil { + errs = append(errs, "required field `invoice_uid` is missing for type `Create Invoice Payment Application`") + } + if c.Amount == nil { + errs = append(errs, "required field `amount` is missing for type `Create Invoice Payment Application`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_invoice_payment_request.go b/models/create_invoice_payment_request.go index f47802b6..6d988aac 100644 --- a/models/create_invoice_payment_request.go +++ b/models/create_invoice_payment_request.go @@ -1,47 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateInvoicePaymentRequest represents a CreateInvoicePaymentRequest struct. type CreateInvoicePaymentRequest struct { - Payment CreateInvoicePayment `json:"payment"` - // The type of payment to be applied to an Invoice. Defaults to external. - Type *InvoicePaymentType `json:"type,omitempty"` + Payment CreateInvoicePayment `json:"payment"` + // The type of payment to be applied to an Invoice. Defaults to external. + Type *InvoicePaymentType `json:"type,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateInvoicePaymentRequest. +// MarshalJSON implements the json.Marshaler interface for CreateInvoicePaymentRequest. // It customizes the JSON marshaling process for CreateInvoicePaymentRequest objects. func (c *CreateInvoicePaymentRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateInvoicePaymentRequest object to a map representation for JSON marshaling. func (c *CreateInvoicePaymentRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["payment"] = c.Payment.toMap() - if c.Type != nil { - structMap["type"] = c.Type - } - return structMap + structMap := make(map[string]any) + structMap["payment"] = c.Payment.toMap() + if c.Type != nil { + structMap["type"] = c.Type + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoicePaymentRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoicePaymentRequest. // It customizes the JSON unmarshaling process for CreateInvoicePaymentRequest objects. func (c *CreateInvoicePaymentRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Payment CreateInvoicePayment `json:"payment"` - Type *InvoicePaymentType `json:"type,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Payment = temp.Payment - c.Type = temp.Type - return nil + var temp createInvoicePaymentRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Payment = *temp.Payment + c.Type = temp.Type + return nil +} + +// TODO +type createInvoicePaymentRequest struct { + Payment *CreateInvoicePayment `json:"payment"` + Type *InvoicePaymentType `json:"type,omitempty"` +} + +func (c *createInvoicePaymentRequest) validate() error { + var errs []string + if c.Payment == nil { + errs = append(errs, "required field `payment` is missing for type `Create Invoice Payment Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_invoice_request.go b/models/create_invoice_request.go index 6a43b87c..d9feb777 100644 --- a/models/create_invoice_request.go +++ b/models/create_invoice_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateInvoiceRequest represents a CreateInvoiceRequest struct. type CreateInvoiceRequest struct { - Invoice CreateInvoice `json:"invoice"` + Invoice CreateInvoice `json:"invoice"` } -// MarshalJSON implements the json.Marshaler interface for CreateInvoiceRequest. +// MarshalJSON implements the json.Marshaler interface for CreateInvoiceRequest. // It customizes the JSON marshaling process for CreateInvoiceRequest objects. func (c *CreateInvoiceRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateInvoiceRequest object to a map representation for JSON marshaling. func (c *CreateInvoiceRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["invoice"] = c.Invoice.toMap() - return structMap + structMap := make(map[string]any) + structMap["invoice"] = c.Invoice.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateInvoiceRequest. // It customizes the JSON unmarshaling process for CreateInvoiceRequest objects. func (c *CreateInvoiceRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Invoice CreateInvoice `json:"invoice"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Invoice = temp.Invoice - return nil + var temp createInvoiceRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Invoice = *temp.Invoice + return nil +} + +// TODO +type createInvoiceRequest struct { + Invoice *CreateInvoice `json:"invoice"` +} + +func (c *createInvoiceRequest) validate() error { + var errs []string + if c.Invoice == nil { + errs = append(errs, "required field `invoice` is missing for type `Create Invoice Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_metadata.go b/models/create_metadata.go index 699e5f1a..9318e7d0 100644 --- a/models/create_metadata.go +++ b/models/create_metadata.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreateMetadata represents a CreateMetadata struct. type CreateMetadata struct { - Name *string `json:"name,omitempty"` - Value *string `json:"value,omitempty"` + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateMetadata. +// MarshalJSON implements the json.Marshaler interface for CreateMetadata. // It customizes the JSON marshaling process for CreateMetadata objects. func (c *CreateMetadata) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateMetadata object to a map representation for JSON marshaling. func (c *CreateMetadata) toMap() map[string]any { - structMap := make(map[string]any) - if c.Name != nil { - structMap["name"] = c.Name - } - if c.Value != nil { - structMap["value"] = c.Value - } - return structMap + structMap := make(map[string]any) + if c.Name != nil { + structMap["name"] = c.Name + } + if c.Value != nil { + structMap["value"] = c.Value + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateMetadata. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateMetadata. // It customizes the JSON unmarshaling process for CreateMetadata objects. func (c *CreateMetadata) UnmarshalJSON(input []byte) error { - temp := &struct { - Name *string `json:"name,omitempty"` - Value *string `json:"value,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Name = temp.Name - c.Value = temp.Value - return nil + var temp createMetadata + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Name = temp.Name + c.Value = temp.Value + return nil +} + +// TODO +type createMetadata struct { + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` } diff --git a/models/create_metadata_request.go b/models/create_metadata_request.go index 0680cf64..74b1b9fc 100644 --- a/models/create_metadata_request.go +++ b/models/create_metadata_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateMetadataRequest represents a CreateMetadataRequest struct. type CreateMetadataRequest struct { - Metadata []CreateMetadata `json:"metadata"` + Metadata []CreateMetadata `json:"metadata"` } -// MarshalJSON implements the json.Marshaler interface for CreateMetadataRequest. +// MarshalJSON implements the json.Marshaler interface for CreateMetadataRequest. // It customizes the JSON marshaling process for CreateMetadataRequest objects. func (c *CreateMetadataRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateMetadataRequest object to a map representation for JSON marshaling. func (c *CreateMetadataRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["metadata"] = c.Metadata - return structMap + structMap := make(map[string]any) + structMap["metadata"] = c.Metadata + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateMetadataRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateMetadataRequest. // It customizes the JSON unmarshaling process for CreateMetadataRequest objects. func (c *CreateMetadataRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Metadata []CreateMetadata `json:"metadata"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Metadata = temp.Metadata - return nil + var temp createMetadataRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Metadata = *temp.Metadata + return nil +} + +// TODO +type createMetadataRequest struct { + Metadata *[]CreateMetadata `json:"metadata"` +} + +func (c *createMetadataRequest) validate() error { + var errs []string + if c.Metadata == nil { + errs = append(errs, "required field `metadata` is missing for type `Create Metadata Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_metafield.go b/models/create_metafield.go new file mode 100644 index 00000000..2161ec28 --- /dev/null +++ b/models/create_metafield.go @@ -0,0 +1,65 @@ +package models + +import ( + "encoding/json" +) + +// CreateMetafield represents a CreateMetafield struct. +type CreateMetafield struct { + Name *string `json:"name,omitempty"` + // Warning: When updating a metafield's scope attribute, all scope attributes must be passed. Partially complete scope attributes will override the existing settings. + Scope *MetafieldScope `json:"scope,omitempty"` + // Indicates how data should be added to the metafield. For example, a text type is just a string, so a given metafield of this type can have any value attached. On the other hand, dropdown and radio have a set of allowed values that can be input, and appear differently on a Public Signup Page. Defaults to 'text' + InputType *MetafieldInput `json:"input_type,omitempty"` + // Only applicable when input_type is radio or dropdown + Enum []string `json:"enum,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for CreateMetafield. +// It customizes the JSON marshaling process for CreateMetafield objects. +func (c *CreateMetafield) MarshalJSON() ( + []byte, + error) { + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateMetafield object to a map representation for JSON marshaling. +func (c *CreateMetafield) toMap() map[string]any { + structMap := make(map[string]any) + if c.Name != nil { + structMap["name"] = c.Name + } + if c.Scope != nil { + structMap["scope"] = c.Scope.toMap() + } + if c.InputType != nil { + structMap["input_type"] = c.InputType + } + if c.Enum != nil { + structMap["enum"] = c.Enum + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateMetafield. +// It customizes the JSON unmarshaling process for CreateMetafield objects. +func (c *CreateMetafield) UnmarshalJSON(input []byte) error { + var temp createMetafield + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Name = temp.Name + c.Scope = temp.Scope + c.InputType = temp.InputType + c.Enum = temp.Enum + return nil +} + +// TODO +type createMetafield struct { + Name *string `json:"name,omitempty"` + Scope *MetafieldScope `json:"scope,omitempty"` + InputType *MetafieldInput `json:"input_type,omitempty"` + Enum []string `json:"enum,omitempty"` +} diff --git a/models/create_metafields_request.go b/models/create_metafields_request.go index 12b49b07..5f5bc799 100644 --- a/models/create_metafields_request.go +++ b/models/create_metafields_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateMetafieldsRequest represents a CreateMetafieldsRequest struct. type CreateMetafieldsRequest struct { - Metafields interface{} `json:"metafields"` + Metafields CreateMetafieldsRequestMetafields `json:"metafields"` } -// MarshalJSON implements the json.Marshaler interface for CreateMetafieldsRequest. +// MarshalJSON implements the json.Marshaler interface for CreateMetafieldsRequest. // It customizes the JSON marshaling process for CreateMetafieldsRequest objects. func (c *CreateMetafieldsRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateMetafieldsRequest object to a map representation for JSON marshaling. func (c *CreateMetafieldsRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["metafields"] = c.Metafields - return structMap + structMap := make(map[string]any) + structMap["metafields"] = c.Metafields.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateMetafieldsRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateMetafieldsRequest. // It customizes the JSON unmarshaling process for CreateMetafieldsRequest objects. func (c *CreateMetafieldsRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Metafields interface{} `json:"metafields"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Metafields = temp.Metafields - return nil + var temp createMetafieldsRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Metafields = *temp.Metafields + return nil +} + +// TODO +type createMetafieldsRequest struct { + Metafields *CreateMetafieldsRequestMetafields `json:"metafields"` +} + +func (c *createMetafieldsRequest) validate() error { + var errs []string + if c.Metafields == nil { + errs = append(errs, "required field `metafields` is missing for type `Create Metafields Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_metafields_request_metafields.go b/models/create_metafields_request_metafields.go new file mode 100644 index 00000000..12dc4539 --- /dev/null +++ b/models/create_metafields_request_metafields.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateMetafieldsRequestMetafields represents a CreateMetafieldsRequestMetafields struct. +// This is a container for one-of cases. +type CreateMetafieldsRequestMetafields struct { + value any + isCreateMetafield bool + isArrayOfCreateMetafield bool +} + +// String converts the CreateMetafieldsRequestMetafields object to a string representation. +func (c CreateMetafieldsRequestMetafields) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateMetafieldsRequestMetafields. +// It customizes the JSON marshaling process for CreateMetafieldsRequestMetafields objects. +func (c *CreateMetafieldsRequestMetafields) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateMetafieldsRequestMetafieldsContainer.From*` functions to initialize the CreateMetafieldsRequestMetafields object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateMetafieldsRequestMetafields object to a map representation for JSON marshaling. +func (c *CreateMetafieldsRequestMetafields) toMap() any { + switch obj := c.value.(type) { + case *CreateMetafield: + return obj.toMap() + case *[]CreateMetafield: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateMetafieldsRequestMetafields. +// It customizes the JSON unmarshaling process for CreateMetafieldsRequestMetafields objects. +func (c *CreateMetafieldsRequestMetafields) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&CreateMetafield{}, false, &c.isCreateMetafield), + NewTypeHolder(&[]CreateMetafield{}, false, &c.isArrayOfCreateMetafield), + ) + + c.value = result + return err +} + +func (c *CreateMetafieldsRequestMetafields) AsCreateMetafield() ( + *CreateMetafield, + bool) { + if !c.isCreateMetafield { + return nil, false + } + return c.value.(*CreateMetafield), true +} + +func (c *CreateMetafieldsRequestMetafields) AsArrayOfCreateMetafield() ( + *[]CreateMetafield, + bool) { + if !c.isArrayOfCreateMetafield { + return nil, false + } + return c.value.(*[]CreateMetafield), true +} + +// internalCreateMetafieldsRequestMetafields represents a createMetafieldsRequestMetafields struct. +// This is a container for one-of cases. +type internalCreateMetafieldsRequestMetafields struct{} + +var CreateMetafieldsRequestMetafieldsContainer internalCreateMetafieldsRequestMetafields + +func (c *internalCreateMetafieldsRequestMetafields) FromCreateMetafield(val CreateMetafield) CreateMetafieldsRequestMetafields { + return CreateMetafieldsRequestMetafields{value: &val} +} + +func (c *internalCreateMetafieldsRequestMetafields) FromArrayOfCreateMetafield(val []CreateMetafield) CreateMetafieldsRequestMetafields { + return CreateMetafieldsRequestMetafields{value: &val} +} diff --git a/models/create_metered_component.go b/models/create_metered_component.go index 24c5cfac..cdafb1df 100644 --- a/models/create_metered_component.go +++ b/models/create_metered_component.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateMeteredComponent represents a CreateMeteredComponent struct. type CreateMeteredComponent struct { - MeteredComponent MeteredComponent `json:"metered_component"` + MeteredComponent MeteredComponent `json:"metered_component"` } -// MarshalJSON implements the json.Marshaler interface for CreateMeteredComponent. +// MarshalJSON implements the json.Marshaler interface for CreateMeteredComponent. // It customizes the JSON marshaling process for CreateMeteredComponent objects. func (c *CreateMeteredComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateMeteredComponent object to a map representation for JSON marshaling. func (c *CreateMeteredComponent) toMap() map[string]any { - structMap := make(map[string]any) - structMap["metered_component"] = c.MeteredComponent.toMap() - return structMap + structMap := make(map[string]any) + structMap["metered_component"] = c.MeteredComponent.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateMeteredComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateMeteredComponent. // It customizes the JSON unmarshaling process for CreateMeteredComponent objects. func (c *CreateMeteredComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - MeteredComponent MeteredComponent `json:"metered_component"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.MeteredComponent = temp.MeteredComponent - return nil + var temp createMeteredComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.MeteredComponent = *temp.MeteredComponent + return nil +} + +// TODO +type createMeteredComponent struct { + MeteredComponent *MeteredComponent `json:"metered_component"` +} + +func (c *createMeteredComponent) validate() error { + var errs []string + if c.MeteredComponent == nil { + errs = append(errs, "required field `metered_component` is missing for type `Create Metered Component`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_multi_invoice_payment.go b/models/create_multi_invoice_payment.go index 8a196b95..0c3a5ba0 100644 --- a/models/create_multi_invoice_payment.go +++ b/models/create_multi_invoice_payment.go @@ -1,73 +1,96 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateMultiInvoicePayment represents a CreateMultiInvoicePayment struct. type CreateMultiInvoicePayment struct { - // A description to be attached to the payment. - Memo *string `json:"memo,omitempty"` - // Additional information related to the payment method (eg. Check #). - Details *string `json:"details,omitempty"` - // The type of payment method used. Defaults to other. - Method *InvoicePaymentMethodType `json:"method,omitempty"` - // Dollar amount of the sum of the invoices payment (eg. "10.50" => $10.50). - Amount interface{} `json:"amount"` - // Date reflecting when the payment was received from a customer. Must be in the past. - ReceivedOn *string `json:"received_on,omitempty"` - Applications []CreateInvoicePaymentApplication `json:"applications"` + // A description to be attached to the payment. + Memo *string `json:"memo,omitempty"` + // Additional information related to the payment method (eg. Check #). + Details *string `json:"details,omitempty"` + // The type of payment method used. Defaults to other. + Method *InvoicePaymentMethodType `json:"method,omitempty"` + // Dollar amount of the sum of the invoices payment (eg. "10.50" => $10.50). + Amount CreateMultiInvoicePaymentAmount `json:"amount"` + // Date reflecting when the payment was received from a customer. Must be in the past. + ReceivedOn *string `json:"received_on,omitempty"` + Applications []CreateInvoicePaymentApplication `json:"applications"` } -// MarshalJSON implements the json.Marshaler interface for CreateMultiInvoicePayment. +// MarshalJSON implements the json.Marshaler interface for CreateMultiInvoicePayment. // It customizes the JSON marshaling process for CreateMultiInvoicePayment objects. func (c *CreateMultiInvoicePayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateMultiInvoicePayment object to a map representation for JSON marshaling. func (c *CreateMultiInvoicePayment) toMap() map[string]any { - structMap := make(map[string]any) - if c.Memo != nil { - structMap["memo"] = c.Memo - } - if c.Details != nil { - structMap["details"] = c.Details - } - if c.Method != nil { - structMap["method"] = c.Method - } - structMap["amount"] = c.Amount - if c.ReceivedOn != nil { - structMap["received_on"] = c.ReceivedOn - } - structMap["applications"] = c.Applications - return structMap + structMap := make(map[string]any) + if c.Memo != nil { + structMap["memo"] = c.Memo + } + if c.Details != nil { + structMap["details"] = c.Details + } + if c.Method != nil { + structMap["method"] = c.Method + } + structMap["amount"] = c.Amount.toMap() + if c.ReceivedOn != nil { + structMap["received_on"] = c.ReceivedOn + } + structMap["applications"] = c.Applications + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateMultiInvoicePayment. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateMultiInvoicePayment. // It customizes the JSON unmarshaling process for CreateMultiInvoicePayment objects. func (c *CreateMultiInvoicePayment) UnmarshalJSON(input []byte) error { - temp := &struct { - Memo *string `json:"memo,omitempty"` - Details *string `json:"details,omitempty"` - Method *InvoicePaymentMethodType `json:"method,omitempty"` - Amount interface{} `json:"amount"` - ReceivedOn *string `json:"received_on,omitempty"` - Applications []CreateInvoicePaymentApplication `json:"applications"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Memo = temp.Memo - c.Details = temp.Details - c.Method = temp.Method - c.Amount = temp.Amount - c.ReceivedOn = temp.ReceivedOn - c.Applications = temp.Applications - return nil + var temp createMultiInvoicePayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Memo = temp.Memo + c.Details = temp.Details + c.Method = temp.Method + c.Amount = *temp.Amount + c.ReceivedOn = temp.ReceivedOn + c.Applications = *temp.Applications + return nil +} + +// TODO +type createMultiInvoicePayment struct { + Memo *string `json:"memo,omitempty"` + Details *string `json:"details,omitempty"` + Method *InvoicePaymentMethodType `json:"method,omitempty"` + Amount *CreateMultiInvoicePaymentAmount `json:"amount"` + ReceivedOn *string `json:"received_on,omitempty"` + Applications *[]CreateInvoicePaymentApplication `json:"applications"` +} + +func (c *createMultiInvoicePayment) validate() error { + var errs []string + if c.Amount == nil { + errs = append(errs, "required field `amount` is missing for type `Create Multi Invoice Payment`") + } + if c.Applications == nil { + errs = append(errs, "required field `applications` is missing for type `Create Multi Invoice Payment`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_multi_invoice_payment_amount.go b/models/create_multi_invoice_payment_amount.go new file mode 100644 index 00000000..00458f9a --- /dev/null +++ b/models/create_multi_invoice_payment_amount.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateMultiInvoicePaymentAmount represents a CreateMultiInvoicePaymentAmount struct. +// This is a container for one-of cases. +type CreateMultiInvoicePaymentAmount struct { + value any + isString bool + isPrecision bool +} + +// String converts the CreateMultiInvoicePaymentAmount object to a string representation. +func (c CreateMultiInvoicePaymentAmount) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateMultiInvoicePaymentAmount. +// It customizes the JSON marshaling process for CreateMultiInvoicePaymentAmount objects. +func (c *CreateMultiInvoicePaymentAmount) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateMultiInvoicePaymentAmountContainer.From*` functions to initialize the CreateMultiInvoicePaymentAmount object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateMultiInvoicePaymentAmount object to a map representation for JSON marshaling. +func (c *CreateMultiInvoicePaymentAmount) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateMultiInvoicePaymentAmount. +// It customizes the JSON unmarshaling process for CreateMultiInvoicePaymentAmount objects. +func (c *CreateMultiInvoicePaymentAmount) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(float64), false, &c.isPrecision), + ) + + c.value = result + return err +} + +func (c *CreateMultiInvoicePaymentAmount) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateMultiInvoicePaymentAmount) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +// internalCreateMultiInvoicePaymentAmount represents a createMultiInvoicePaymentAmount struct. +// This is a container for one-of cases. +type internalCreateMultiInvoicePaymentAmount struct{} + +var CreateMultiInvoicePaymentAmountContainer internalCreateMultiInvoicePaymentAmount + +func (c *internalCreateMultiInvoicePaymentAmount) FromString(val string) CreateMultiInvoicePaymentAmount { + return CreateMultiInvoicePaymentAmount{value: &val} +} + +func (c *internalCreateMultiInvoicePaymentAmount) FromPrecision(val float64) CreateMultiInvoicePaymentAmount { + return CreateMultiInvoicePaymentAmount{value: &val} +} diff --git a/models/create_multi_invoice_payment_request.go b/models/create_multi_invoice_payment_request.go index 0afeb286..4893582a 100644 --- a/models/create_multi_invoice_payment_request.go +++ b/models/create_multi_invoice_payment_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateMultiInvoicePaymentRequest represents a CreateMultiInvoicePaymentRequest struct. type CreateMultiInvoicePaymentRequest struct { - Payment CreateMultiInvoicePayment `json:"payment"` + Payment CreateMultiInvoicePayment `json:"payment"` } -// MarshalJSON implements the json.Marshaler interface for CreateMultiInvoicePaymentRequest. +// MarshalJSON implements the json.Marshaler interface for CreateMultiInvoicePaymentRequest. // It customizes the JSON marshaling process for CreateMultiInvoicePaymentRequest objects. func (c *CreateMultiInvoicePaymentRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateMultiInvoicePaymentRequest object to a map representation for JSON marshaling. func (c *CreateMultiInvoicePaymentRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["payment"] = c.Payment.toMap() - return structMap + structMap := make(map[string]any) + structMap["payment"] = c.Payment.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateMultiInvoicePaymentRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateMultiInvoicePaymentRequest. // It customizes the JSON unmarshaling process for CreateMultiInvoicePaymentRequest objects. func (c *CreateMultiInvoicePaymentRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Payment CreateMultiInvoicePayment `json:"payment"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Payment = temp.Payment - return nil + var temp createMultiInvoicePaymentRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Payment = *temp.Payment + return nil +} + +// TODO +type createMultiInvoicePaymentRequest struct { + Payment *CreateMultiInvoicePayment `json:"payment"` +} + +func (c *createMultiInvoicePaymentRequest) validate() error { + var errs []string + if c.Payment == nil { + errs = append(errs, "required field `payment` is missing for type `Create Multi Invoice Payment Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_offer.go b/models/create_offer.go index b2ddb162..72c748a2 100644 --- a/models/create_offer.go +++ b/models/create_offer.go @@ -1,72 +1,98 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateOffer represents a CreateOffer struct. type CreateOffer struct { - Name string `json:"name"` - Handle string `json:"handle"` - Description *string `json:"description,omitempty"` - ProductId int `json:"product_id"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - Components []CreateOfferComponent `json:"components,omitempty"` - Coupons []string `json:"coupons,omitempty"` + Name string `json:"name"` + Handle string `json:"handle"` + Description *string `json:"description,omitempty"` + ProductId int `json:"product_id"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + Components []CreateOfferComponent `json:"components,omitempty"` + Coupons []string `json:"coupons,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateOffer. +// MarshalJSON implements the json.Marshaler interface for CreateOffer. // It customizes the JSON marshaling process for CreateOffer objects. func (c *CreateOffer) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateOffer object to a map representation for JSON marshaling. func (c *CreateOffer) toMap() map[string]any { - structMap := make(map[string]any) - structMap["name"] = c.Name - structMap["handle"] = c.Handle - if c.Description != nil { - structMap["description"] = c.Description - } - structMap["product_id"] = c.ProductId - if c.ProductPricePointId != nil { - structMap["product_price_point_id"] = c.ProductPricePointId - } - if c.Components != nil { - structMap["components"] = c.Components - } - if c.Coupons != nil { - structMap["coupons"] = c.Coupons - } - return structMap + structMap := make(map[string]any) + structMap["name"] = c.Name + structMap["handle"] = c.Handle + if c.Description != nil { + structMap["description"] = c.Description + } + structMap["product_id"] = c.ProductId + if c.ProductPricePointId != nil { + structMap["product_price_point_id"] = c.ProductPricePointId + } + if c.Components != nil { + structMap["components"] = c.Components + } + if c.Coupons != nil { + structMap["coupons"] = c.Coupons + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateOffer. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOffer. // It customizes the JSON unmarshaling process for CreateOffer objects. func (c *CreateOffer) UnmarshalJSON(input []byte) error { - temp := &struct { - Name string `json:"name"` - Handle string `json:"handle"` - Description *string `json:"description,omitempty"` - ProductId int `json:"product_id"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - Components []CreateOfferComponent `json:"components,omitempty"` - Coupons []string `json:"coupons,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Name = temp.Name - c.Handle = temp.Handle - c.Description = temp.Description - c.ProductId = temp.ProductId - c.ProductPricePointId = temp.ProductPricePointId - c.Components = temp.Components - c.Coupons = temp.Coupons - return nil + var temp createOffer + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Name = *temp.Name + c.Handle = *temp.Handle + c.Description = temp.Description + c.ProductId = *temp.ProductId + c.ProductPricePointId = temp.ProductPricePointId + c.Components = temp.Components + c.Coupons = temp.Coupons + return nil +} + +// TODO +type createOffer struct { + Name *string `json:"name"` + Handle *string `json:"handle"` + Description *string `json:"description,omitempty"` + ProductId *int `json:"product_id"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + Components []CreateOfferComponent `json:"components,omitempty"` + Coupons []string `json:"coupons,omitempty"` +} + +func (c *createOffer) validate() error { + var errs []string + if c.Name == nil { + errs = append(errs, "required field `name` is missing for type `Create Offer`") + } + if c.Handle == nil { + errs = append(errs, "required field `handle` is missing for type `Create Offer`") + } + if c.ProductId == nil { + errs = append(errs, "required field `product_id` is missing for type `Create Offer`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_offer_component.go b/models/create_offer_component.go index 1e07dde8..eb1373d2 100644 --- a/models/create_offer_component.go +++ b/models/create_offer_component.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreateOfferComponent represents a CreateOfferComponent struct. type CreateOfferComponent struct { - ComponentId *int `json:"component_id,omitempty"` - StartingQuantity *int `json:"starting_quantity,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + StartingQuantity *int `json:"starting_quantity,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateOfferComponent. +// MarshalJSON implements the json.Marshaler interface for CreateOfferComponent. // It customizes the JSON marshaling process for CreateOfferComponent objects. func (c *CreateOfferComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateOfferComponent object to a map representation for JSON marshaling. func (c *CreateOfferComponent) toMap() map[string]any { - structMap := make(map[string]any) - if c.ComponentId != nil { - structMap["component_id"] = c.ComponentId - } - if c.StartingQuantity != nil { - structMap["starting_quantity"] = c.StartingQuantity - } - return structMap + structMap := make(map[string]any) + if c.ComponentId != nil { + structMap["component_id"] = c.ComponentId + } + if c.StartingQuantity != nil { + structMap["starting_quantity"] = c.StartingQuantity + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateOfferComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOfferComponent. // It customizes the JSON unmarshaling process for CreateOfferComponent objects. func (c *CreateOfferComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - ComponentId *int `json:"component_id,omitempty"` - StartingQuantity *int `json:"starting_quantity,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ComponentId = temp.ComponentId - c.StartingQuantity = temp.StartingQuantity - return nil + var temp createOfferComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.ComponentId = temp.ComponentId + c.StartingQuantity = temp.StartingQuantity + return nil +} + +// TODO +type createOfferComponent struct { + ComponentId *int `json:"component_id,omitempty"` + StartingQuantity *int `json:"starting_quantity,omitempty"` } diff --git a/models/create_offer_request.go b/models/create_offer_request.go index acb04dd4..670c5775 100644 --- a/models/create_offer_request.go +++ b/models/create_offer_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateOfferRequest represents a CreateOfferRequest struct. type CreateOfferRequest struct { - Offer CreateOffer `json:"offer"` + Offer CreateOffer `json:"offer"` } -// MarshalJSON implements the json.Marshaler interface for CreateOfferRequest. +// MarshalJSON implements the json.Marshaler interface for CreateOfferRequest. // It customizes the JSON marshaling process for CreateOfferRequest objects. func (c *CreateOfferRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateOfferRequest object to a map representation for JSON marshaling. func (c *CreateOfferRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["offer"] = c.Offer.toMap() - return structMap + structMap := make(map[string]any) + structMap["offer"] = c.Offer.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateOfferRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOfferRequest. // It customizes the JSON unmarshaling process for CreateOfferRequest objects. func (c *CreateOfferRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Offer CreateOffer `json:"offer"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Offer = temp.Offer - return nil + var temp createOfferRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Offer = *temp.Offer + return nil +} + +// TODO +type createOfferRequest struct { + Offer *CreateOffer `json:"offer"` +} + +func (c *createOfferRequest) validate() error { + var errs []string + if c.Offer == nil { + errs = append(errs, "required field `offer` is missing for type `Create Offer Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_on_off_component.go b/models/create_on_off_component.go index 27273ca6..ceb98367 100644 --- a/models/create_on_off_component.go +++ b/models/create_on_off_component.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateOnOffComponent represents a CreateOnOffComponent struct. type CreateOnOffComponent struct { - OnOffComponent OnOffComponent `json:"on_off_component"` + OnOffComponent OnOffComponent `json:"on_off_component"` } -// MarshalJSON implements the json.Marshaler interface for CreateOnOffComponent. +// MarshalJSON implements the json.Marshaler interface for CreateOnOffComponent. // It customizes the JSON marshaling process for CreateOnOffComponent objects. func (c *CreateOnOffComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateOnOffComponent object to a map representation for JSON marshaling. func (c *CreateOnOffComponent) toMap() map[string]any { - structMap := make(map[string]any) - structMap["on_off_component"] = c.OnOffComponent.toMap() - return structMap + structMap := make(map[string]any) + structMap["on_off_component"] = c.OnOffComponent.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateOnOffComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOnOffComponent. // It customizes the JSON unmarshaling process for CreateOnOffComponent objects. func (c *CreateOnOffComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - OnOffComponent OnOffComponent `json:"on_off_component"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.OnOffComponent = temp.OnOffComponent - return nil + var temp createOnOffComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.OnOffComponent = *temp.OnOffComponent + return nil +} + +// TODO +type createOnOffComponent struct { + OnOffComponent *OnOffComponent `json:"on_off_component"` +} + +func (c *createOnOffComponent) validate() error { + var errs []string + if c.OnOffComponent == nil { + errs = append(errs, "required field `on_off_component` is missing for type `Create On/Off Component`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_or_update_coupon.go b/models/create_or_update_coupon.go index 5b8b7c74..7b38e870 100644 --- a/models/create_or_update_coupon.go +++ b/models/create_or_update_coupon.go @@ -1,56 +1,58 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreateOrUpdateCoupon represents a CreateOrUpdateCoupon struct. type CreateOrUpdateCoupon struct { - Coupon *interface{} `json:"coupon,omitempty"` - // An object where the keys are product_ids and the values are booleans indicating if the coupon should be applicable to the product - RestrictedProducts map[string]bool `json:"restricted_products,omitempty"` - // An object where the keys are component_ids and the values are booleans indicating if the coupon should be applicable to the component - RestrictedComponents map[string]bool `json:"restricted_components,omitempty"` + Coupon *CreateOrUpdateCouponCoupon `json:"coupon,omitempty"` + // An object where the keys are product_ids and the values are booleans indicating if the coupon should be applicable to the product + RestrictedProducts map[string]bool `json:"restricted_products,omitempty"` + // An object where the keys are component_ids and the values are booleans indicating if the coupon should be applicable to the component + RestrictedComponents map[string]bool `json:"restricted_components,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateCoupon. +// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateCoupon. // It customizes the JSON marshaling process for CreateOrUpdateCoupon objects. func (c *CreateOrUpdateCoupon) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateOrUpdateCoupon object to a map representation for JSON marshaling. func (c *CreateOrUpdateCoupon) toMap() map[string]any { - structMap := make(map[string]any) - if c.Coupon != nil { - structMap["coupon"] = c.Coupon - } - if c.RestrictedProducts != nil { - structMap["restricted_products"] = c.RestrictedProducts - } - if c.RestrictedComponents != nil { - structMap["restricted_components"] = c.RestrictedComponents - } - return structMap + structMap := make(map[string]any) + if c.Coupon != nil { + structMap["coupon"] = c.Coupon.toMap() + } + if c.RestrictedProducts != nil { + structMap["restricted_products"] = c.RestrictedProducts + } + if c.RestrictedComponents != nil { + structMap["restricted_components"] = c.RestrictedComponents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateCoupon. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateCoupon. // It customizes the JSON unmarshaling process for CreateOrUpdateCoupon objects. func (c *CreateOrUpdateCoupon) UnmarshalJSON(input []byte) error { - temp := &struct { - Coupon *interface{} `json:"coupon,omitempty"` - RestrictedProducts map[string]bool `json:"restricted_products,omitempty"` - RestrictedComponents map[string]bool `json:"restricted_components,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Coupon = temp.Coupon - c.RestrictedProducts = temp.RestrictedProducts - c.RestrictedComponents = temp.RestrictedComponents - return nil + var temp createOrUpdateCoupon + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Coupon = temp.Coupon + c.RestrictedProducts = temp.RestrictedProducts + c.RestrictedComponents = temp.RestrictedComponents + return nil +} + +// TODO +type createOrUpdateCoupon struct { + Coupon *CreateOrUpdateCouponCoupon `json:"coupon,omitempty"` + RestrictedProducts map[string]bool `json:"restricted_products,omitempty"` + RestrictedComponents map[string]bool `json:"restricted_components,omitempty"` } diff --git a/models/create_or_update_coupon_coupon.go b/models/create_or_update_coupon_coupon.go new file mode 100644 index 00000000..2931229b --- /dev/null +++ b/models/create_or_update_coupon_coupon.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateOrUpdateCouponCoupon represents a CreateOrUpdateCouponCoupon struct. +// This is a container for one-of cases. +type CreateOrUpdateCouponCoupon struct { + value any + isCreateOrUpdatePercentageCoupon bool + isCreateOrUpdateFlatAmountCoupon bool +} + +// String converts the CreateOrUpdateCouponCoupon object to a string representation. +func (c CreateOrUpdateCouponCoupon) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateCouponCoupon. +// It customizes the JSON marshaling process for CreateOrUpdateCouponCoupon objects. +func (c *CreateOrUpdateCouponCoupon) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateOrUpdateCouponCouponContainer.From*` functions to initialize the CreateOrUpdateCouponCoupon object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateOrUpdateCouponCoupon object to a map representation for JSON marshaling. +func (c *CreateOrUpdateCouponCoupon) toMap() any { + switch obj := c.value.(type) { + case *CreateOrUpdatePercentageCoupon: + return obj.toMap() + case *CreateOrUpdateFlatAmountCoupon: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateCouponCoupon. +// It customizes the JSON unmarshaling process for CreateOrUpdateCouponCoupon objects. +func (c *CreateOrUpdateCouponCoupon) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&CreateOrUpdatePercentageCoupon{}, false, &c.isCreateOrUpdatePercentageCoupon), + NewTypeHolder(&CreateOrUpdateFlatAmountCoupon{}, false, &c.isCreateOrUpdateFlatAmountCoupon), + ) + + c.value = result + return err +} + +func (c *CreateOrUpdateCouponCoupon) AsCreateOrUpdatePercentageCoupon() ( + *CreateOrUpdatePercentageCoupon, + bool) { + if !c.isCreateOrUpdatePercentageCoupon { + return nil, false + } + return c.value.(*CreateOrUpdatePercentageCoupon), true +} + +func (c *CreateOrUpdateCouponCoupon) AsCreateOrUpdateFlatAmountCoupon() ( + *CreateOrUpdateFlatAmountCoupon, + bool) { + if !c.isCreateOrUpdateFlatAmountCoupon { + return nil, false + } + return c.value.(*CreateOrUpdateFlatAmountCoupon), true +} + +// internalCreateOrUpdateCouponCoupon represents a createOrUpdateCouponCoupon struct. +// This is a container for one-of cases. +type internalCreateOrUpdateCouponCoupon struct{} + +var CreateOrUpdateCouponCouponContainer internalCreateOrUpdateCouponCoupon + +func (c *internalCreateOrUpdateCouponCoupon) FromCreateOrUpdatePercentageCoupon(val CreateOrUpdatePercentageCoupon) CreateOrUpdateCouponCoupon { + return CreateOrUpdateCouponCoupon{value: &val} +} + +func (c *internalCreateOrUpdateCouponCoupon) FromCreateOrUpdateFlatAmountCoupon(val CreateOrUpdateFlatAmountCoupon) CreateOrUpdateCouponCoupon { + return CreateOrUpdateCouponCoupon{value: &val} +} diff --git a/models/create_or_update_endpoint.go b/models/create_or_update_endpoint.go index b30da027..ed3679df 100644 --- a/models/create_or_update_endpoint.go +++ b/models/create_or_update_endpoint.go @@ -1,45 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) -// CreateOrUpdateEndpoint represents a CreateOrUpdateEndpoint struct. +// CreateOrUpdateEndpoint represents a CreateOrUpdateEndpoint struct. // Used to Create or Update Endpoint type CreateOrUpdateEndpoint struct { - Url string `json:"url"` - WebhookSubscriptions []WebhookSubscription `json:"webhook_subscriptions"` + Url string `json:"url"` + WebhookSubscriptions []WebhookSubscription `json:"webhook_subscriptions"` } -// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateEndpoint. +// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateEndpoint. // It customizes the JSON marshaling process for CreateOrUpdateEndpoint objects. func (c *CreateOrUpdateEndpoint) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateOrUpdateEndpoint object to a map representation for JSON marshaling. func (c *CreateOrUpdateEndpoint) toMap() map[string]any { - structMap := make(map[string]any) - structMap["url"] = c.Url - structMap["webhook_subscriptions"] = c.WebhookSubscriptions - return structMap + structMap := make(map[string]any) + structMap["url"] = c.Url + structMap["webhook_subscriptions"] = c.WebhookSubscriptions + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateEndpoint. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateEndpoint. // It customizes the JSON unmarshaling process for CreateOrUpdateEndpoint objects. func (c *CreateOrUpdateEndpoint) UnmarshalJSON(input []byte) error { - temp := &struct { - Url string `json:"url"` - WebhookSubscriptions []WebhookSubscription `json:"webhook_subscriptions"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Url = temp.Url - c.WebhookSubscriptions = temp.WebhookSubscriptions - return nil + var temp createOrUpdateEndpoint + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Url = *temp.Url + c.WebhookSubscriptions = *temp.WebhookSubscriptions + return nil +} + +// TODO +type createOrUpdateEndpoint struct { + Url *string `json:"url"` + WebhookSubscriptions *[]WebhookSubscription `json:"webhook_subscriptions"` +} + +func (c *createOrUpdateEndpoint) validate() error { + var errs []string + if c.Url == nil { + errs = append(errs, "required field `url` is missing for type `Create or Update Endpoint`") + } + if c.WebhookSubscriptions == nil { + errs = append(errs, "required field `webhook_subscriptions` is missing for type `Create or Update Endpoint`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_or_update_endpoint_request.go b/models/create_or_update_endpoint_request.go index 1af96f77..bfea9f2a 100644 --- a/models/create_or_update_endpoint_request.go +++ b/models/create_or_update_endpoint_request.go @@ -1,42 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) -// CreateOrUpdateEndpointRequest represents a CreateOrUpdateEndpointRequest struct. +// CreateOrUpdateEndpointRequest represents a CreateOrUpdateEndpointRequest struct. // Used to Create or Update Endpoint type CreateOrUpdateEndpointRequest struct { - // Used to Create or Update Endpoint - Endpoint CreateOrUpdateEndpoint `json:"endpoint"` + // Used to Create or Update Endpoint + Endpoint CreateOrUpdateEndpoint `json:"endpoint"` } -// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateEndpointRequest. +// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateEndpointRequest. // It customizes the JSON marshaling process for CreateOrUpdateEndpointRequest objects. func (c *CreateOrUpdateEndpointRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateOrUpdateEndpointRequest object to a map representation for JSON marshaling. func (c *CreateOrUpdateEndpointRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["endpoint"] = c.Endpoint.toMap() - return structMap + structMap := make(map[string]any) + structMap["endpoint"] = c.Endpoint.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateEndpointRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateEndpointRequest. // It customizes the JSON unmarshaling process for CreateOrUpdateEndpointRequest objects. func (c *CreateOrUpdateEndpointRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Endpoint CreateOrUpdateEndpoint `json:"endpoint"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Endpoint = temp.Endpoint - return nil + var temp createOrUpdateEndpointRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Endpoint = *temp.Endpoint + return nil +} + +// TODO +type createOrUpdateEndpointRequest struct { + Endpoint *CreateOrUpdateEndpoint `json:"endpoint"` +} + +func (c *createOrUpdateEndpointRequest) validate() error { + var errs []string + if c.Endpoint == nil { + errs = append(errs, "required field `endpoint` is missing for type `Create or Update Endpoint Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_or_update_flat_amount_coupon.go b/models/create_or_update_flat_amount_coupon.go new file mode 100644 index 00000000..85d966e2 --- /dev/null +++ b/models/create_or_update_flat_amount_coupon.go @@ -0,0 +1,144 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// CreateOrUpdateFlatAmountCoupon represents a CreateOrUpdateFlatAmountCoupon struct. +type CreateOrUpdateFlatAmountCoupon struct { + // the name of the coupon + Name string `json:"name"` + // may contain uppercase alphanumeric characters and these special characters (which allow for email addresses to be used): “%”, “@”, “+”, “-”, “_”, and “.” + Code string `json:"code"` + Description *string `json:"description,omitempty"` + AmountInCents int64 `json:"amount_in_cents"` + AllowNegativeBalance *bool `json:"allow_negative_balance,omitempty"` + Recurring *bool `json:"recurring,omitempty"` + EndDate *time.Time `json:"end_date,omitempty"` + ProductFamilyId *string `json:"product_family_id,omitempty"` + Stackable *bool `json:"stackable,omitempty"` + CompoundingStrategy *CompoundingStrategy `json:"compounding_strategy,omitempty"` + ExcludeMidPeriodAllocations *bool `json:"exclude_mid_period_allocations,omitempty"` + ApplyOnCancelAtEndOfPeriod *bool `json:"apply_on_cancel_at_end_of_period,omitempty"` + ApplyOnSubscriptionExpiration *bool `json:"apply_on_subscription_expiration,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateFlatAmountCoupon. +// It customizes the JSON marshaling process for CreateOrUpdateFlatAmountCoupon objects. +func (c *CreateOrUpdateFlatAmountCoupon) MarshalJSON() ( + []byte, + error) { + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateOrUpdateFlatAmountCoupon object to a map representation for JSON marshaling. +func (c *CreateOrUpdateFlatAmountCoupon) toMap() map[string]any { + structMap := make(map[string]any) + structMap["name"] = c.Name + structMap["code"] = c.Code + if c.Description != nil { + structMap["description"] = c.Description + } + structMap["amount_in_cents"] = c.AmountInCents + if c.AllowNegativeBalance != nil { + structMap["allow_negative_balance"] = c.AllowNegativeBalance + } + if c.Recurring != nil { + structMap["recurring"] = c.Recurring + } + if c.EndDate != nil { + structMap["end_date"] = c.EndDate.Format(time.RFC3339) + } + if c.ProductFamilyId != nil { + structMap["product_family_id"] = c.ProductFamilyId + } + if c.Stackable != nil { + structMap["stackable"] = c.Stackable + } + if c.CompoundingStrategy != nil { + structMap["compounding_strategy"] = c.CompoundingStrategy + } + if c.ExcludeMidPeriodAllocations != nil { + structMap["exclude_mid_period_allocations"] = c.ExcludeMidPeriodAllocations + } + if c.ApplyOnCancelAtEndOfPeriod != nil { + structMap["apply_on_cancel_at_end_of_period"] = c.ApplyOnCancelAtEndOfPeriod + } + if c.ApplyOnSubscriptionExpiration != nil { + structMap["apply_on_subscription_expiration"] = c.ApplyOnSubscriptionExpiration + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateFlatAmountCoupon. +// It customizes the JSON unmarshaling process for CreateOrUpdateFlatAmountCoupon objects. +func (c *CreateOrUpdateFlatAmountCoupon) UnmarshalJSON(input []byte) error { + var temp createOrUpdateFlatAmountCoupon + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Name = *temp.Name + c.Code = *temp.Code + c.Description = temp.Description + c.AmountInCents = *temp.AmountInCents + c.AllowNegativeBalance = temp.AllowNegativeBalance + c.Recurring = temp.Recurring + if temp.EndDate != nil { + EndDateVal, err := time.Parse(time.RFC3339, *temp.EndDate) + if err != nil { + log.Fatalf("Cannot Parse end_date as % s format.", time.RFC3339) + } + c.EndDate = &EndDateVal + } + c.ProductFamilyId = temp.ProductFamilyId + c.Stackable = temp.Stackable + c.CompoundingStrategy = temp.CompoundingStrategy + c.ExcludeMidPeriodAllocations = temp.ExcludeMidPeriodAllocations + c.ApplyOnCancelAtEndOfPeriod = temp.ApplyOnCancelAtEndOfPeriod + c.ApplyOnSubscriptionExpiration = temp.ApplyOnSubscriptionExpiration + return nil +} + +// TODO +type createOrUpdateFlatAmountCoupon struct { + Name *string `json:"name"` + Code *string `json:"code"` + Description *string `json:"description,omitempty"` + AmountInCents *int64 `json:"amount_in_cents"` + AllowNegativeBalance *bool `json:"allow_negative_balance,omitempty"` + Recurring *bool `json:"recurring,omitempty"` + EndDate *string `json:"end_date,omitempty"` + ProductFamilyId *string `json:"product_family_id,omitempty"` + Stackable *bool `json:"stackable,omitempty"` + CompoundingStrategy *CompoundingStrategy `json:"compounding_strategy,omitempty"` + ExcludeMidPeriodAllocations *bool `json:"exclude_mid_period_allocations,omitempty"` + ApplyOnCancelAtEndOfPeriod *bool `json:"apply_on_cancel_at_end_of_period,omitempty"` + ApplyOnSubscriptionExpiration *bool `json:"apply_on_subscription_expiration,omitempty"` +} + +func (c *createOrUpdateFlatAmountCoupon) validate() error { + var errs []string + if c.Name == nil { + errs = append(errs, "required field `name` is missing for type `Create or Update Flat Amount Coupon`") + } + if c.Code == nil { + errs = append(errs, "required field `code` is missing for type `Create or Update Flat Amount Coupon`") + } + if c.AmountInCents == nil { + errs = append(errs, "required field `amount_in_cents` is missing for type `Create or Update Flat Amount Coupon`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/create_or_update_percentage_coupon.go b/models/create_or_update_percentage_coupon.go new file mode 100644 index 00000000..4a1c3c67 --- /dev/null +++ b/models/create_or_update_percentage_coupon.go @@ -0,0 +1,144 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// CreateOrUpdatePercentageCoupon represents a CreateOrUpdatePercentageCoupon struct. +type CreateOrUpdatePercentageCoupon struct { + // the name of the coupon + Name string `json:"name"` + // may contain uppercase alphanumeric characters and these special characters (which allow for email addresses to be used): “%”, “@”, “+”, “-”, “_”, and “.” + Code string `json:"code"` + Description *string `json:"description,omitempty"` + Percentage CreateOrUpdatePercentageCouponPercentage `json:"percentage"` + AllowNegativeBalance *bool `json:"allow_negative_balance,omitempty"` + Recurring *bool `json:"recurring,omitempty"` + EndDate *time.Time `json:"end_date,omitempty"` + ProductFamilyId *string `json:"product_family_id,omitempty"` + Stackable *bool `json:"stackable,omitempty"` + CompoundingStrategy *CompoundingStrategy `json:"compounding_strategy,omitempty"` + ExcludeMidPeriodAllocations *bool `json:"exclude_mid_period_allocations,omitempty"` + ApplyOnCancelAtEndOfPeriod *bool `json:"apply_on_cancel_at_end_of_period,omitempty"` + ApplyOnSubscriptionExpiration *bool `json:"apply_on_subscription_expiration,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for CreateOrUpdatePercentageCoupon. +// It customizes the JSON marshaling process for CreateOrUpdatePercentageCoupon objects. +func (c *CreateOrUpdatePercentageCoupon) MarshalJSON() ( + []byte, + error) { + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateOrUpdatePercentageCoupon object to a map representation for JSON marshaling. +func (c *CreateOrUpdatePercentageCoupon) toMap() map[string]any { + structMap := make(map[string]any) + structMap["name"] = c.Name + structMap["code"] = c.Code + if c.Description != nil { + structMap["description"] = c.Description + } + structMap["percentage"] = c.Percentage.toMap() + if c.AllowNegativeBalance != nil { + structMap["allow_negative_balance"] = c.AllowNegativeBalance + } + if c.Recurring != nil { + structMap["recurring"] = c.Recurring + } + if c.EndDate != nil { + structMap["end_date"] = c.EndDate.Format(time.RFC3339) + } + if c.ProductFamilyId != nil { + structMap["product_family_id"] = c.ProductFamilyId + } + if c.Stackable != nil { + structMap["stackable"] = c.Stackable + } + if c.CompoundingStrategy != nil { + structMap["compounding_strategy"] = c.CompoundingStrategy + } + if c.ExcludeMidPeriodAllocations != nil { + structMap["exclude_mid_period_allocations"] = c.ExcludeMidPeriodAllocations + } + if c.ApplyOnCancelAtEndOfPeriod != nil { + structMap["apply_on_cancel_at_end_of_period"] = c.ApplyOnCancelAtEndOfPeriod + } + if c.ApplyOnSubscriptionExpiration != nil { + structMap["apply_on_subscription_expiration"] = c.ApplyOnSubscriptionExpiration + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdatePercentageCoupon. +// It customizes the JSON unmarshaling process for CreateOrUpdatePercentageCoupon objects. +func (c *CreateOrUpdatePercentageCoupon) UnmarshalJSON(input []byte) error { + var temp createOrUpdatePercentageCoupon + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Name = *temp.Name + c.Code = *temp.Code + c.Description = temp.Description + c.Percentage = *temp.Percentage + c.AllowNegativeBalance = temp.AllowNegativeBalance + c.Recurring = temp.Recurring + if temp.EndDate != nil { + EndDateVal, err := time.Parse(time.RFC3339, *temp.EndDate) + if err != nil { + log.Fatalf("Cannot Parse end_date as % s format.", time.RFC3339) + } + c.EndDate = &EndDateVal + } + c.ProductFamilyId = temp.ProductFamilyId + c.Stackable = temp.Stackable + c.CompoundingStrategy = temp.CompoundingStrategy + c.ExcludeMidPeriodAllocations = temp.ExcludeMidPeriodAllocations + c.ApplyOnCancelAtEndOfPeriod = temp.ApplyOnCancelAtEndOfPeriod + c.ApplyOnSubscriptionExpiration = temp.ApplyOnSubscriptionExpiration + return nil +} + +// TODO +type createOrUpdatePercentageCoupon struct { + Name *string `json:"name"` + Code *string `json:"code"` + Description *string `json:"description,omitempty"` + Percentage *CreateOrUpdatePercentageCouponPercentage `json:"percentage"` + AllowNegativeBalance *bool `json:"allow_negative_balance,omitempty"` + Recurring *bool `json:"recurring,omitempty"` + EndDate *string `json:"end_date,omitempty"` + ProductFamilyId *string `json:"product_family_id,omitempty"` + Stackable *bool `json:"stackable,omitempty"` + CompoundingStrategy *CompoundingStrategy `json:"compounding_strategy,omitempty"` + ExcludeMidPeriodAllocations *bool `json:"exclude_mid_period_allocations,omitempty"` + ApplyOnCancelAtEndOfPeriod *bool `json:"apply_on_cancel_at_end_of_period,omitempty"` + ApplyOnSubscriptionExpiration *bool `json:"apply_on_subscription_expiration,omitempty"` +} + +func (c *createOrUpdatePercentageCoupon) validate() error { + var errs []string + if c.Name == nil { + errs = append(errs, "required field `name` is missing for type `Create or Update Percentage Coupon`") + } + if c.Code == nil { + errs = append(errs, "required field `code` is missing for type `Create or Update Percentage Coupon`") + } + if c.Percentage == nil { + errs = append(errs, "required field `percentage` is missing for type `Create or Update Percentage Coupon`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/create_or_update_percentage_coupon_percentage.go b/models/create_or_update_percentage_coupon_percentage.go new file mode 100644 index 00000000..295f9306 --- /dev/null +++ b/models/create_or_update_percentage_coupon_percentage.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateOrUpdatePercentageCouponPercentage represents a CreateOrUpdatePercentageCouponPercentage struct. +// This is a container for one-of cases. +type CreateOrUpdatePercentageCouponPercentage struct { + value any + isString bool + isPrecision bool +} + +// String converts the CreateOrUpdatePercentageCouponPercentage object to a string representation. +func (c CreateOrUpdatePercentageCouponPercentage) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateOrUpdatePercentageCouponPercentage. +// It customizes the JSON marshaling process for CreateOrUpdatePercentageCouponPercentage objects. +func (c *CreateOrUpdatePercentageCouponPercentage) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateOrUpdatePercentageCouponPercentageContainer.From*` functions to initialize the CreateOrUpdatePercentageCouponPercentage object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateOrUpdatePercentageCouponPercentage object to a map representation for JSON marshaling. +func (c *CreateOrUpdatePercentageCouponPercentage) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdatePercentageCouponPercentage. +// It customizes the JSON unmarshaling process for CreateOrUpdatePercentageCouponPercentage objects. +func (c *CreateOrUpdatePercentageCouponPercentage) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(float64), false, &c.isPrecision), + ) + + c.value = result + return err +} + +func (c *CreateOrUpdatePercentageCouponPercentage) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateOrUpdatePercentageCouponPercentage) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +// internalCreateOrUpdatePercentageCouponPercentage represents a createOrUpdatePercentageCouponPercentage struct. +// This is a container for one-of cases. +type internalCreateOrUpdatePercentageCouponPercentage struct{} + +var CreateOrUpdatePercentageCouponPercentageContainer internalCreateOrUpdatePercentageCouponPercentage + +func (c *internalCreateOrUpdatePercentageCouponPercentage) FromString(val string) CreateOrUpdatePercentageCouponPercentage { + return CreateOrUpdatePercentageCouponPercentage{value: &val} +} + +func (c *internalCreateOrUpdatePercentageCouponPercentage) FromPrecision(val float64) CreateOrUpdatePercentageCouponPercentage { + return CreateOrUpdatePercentageCouponPercentage{value: &val} +} diff --git a/models/create_or_update_product.go b/models/create_or_update_product.go index 1b830324..56db017d 100644 --- a/models/create_or_update_product.go +++ b/models/create_or_update_product.go @@ -1,136 +1,168 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateOrUpdateProduct represents a CreateOrUpdateProduct struct. type CreateOrUpdateProduct struct { - // The product name - Name string `json:"name"` - // The product API handle - Handle *string `json:"handle,omitempty"` - // The product description - Description string `json:"description"` - // E.g. Internal ID or SKU Number - AccountingCode *string `json:"accounting_code,omitempty"` - // Deprecated value that can be ignored unless you have legacy hosted pages. For Public Signup Page users, please read this attribute from under the signup page. - RequireCreditCard *bool `json:"require_credit_card,omitempty"` - // The product price, in integer cents - PriceInCents int64 `json:"price_in_cents"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product would renew every 30 days - Interval int `json:"interval"` - // A string representing the interval unit for this product, either month or day - IntervalUnit IntervalUnit `json:"interval_unit"` - // The product trial price, in integer cents - TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` - // The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product trial would last 30 days. - TrialInterval *int `json:"trial_interval,omitempty"` - // A string representing the trial interval unit for this product, either month or day - TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` - TrialType *string `json:"trial_type,omitempty"` - // The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product would expire after 30 days. - ExpirationInterval *int `json:"expiration_interval,omitempty"` - // A string representing the expiration interval unit for this product, either month or day - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` - AutoCreateSignupPage *bool `json:"auto_create_signup_page,omitempty"` - // A string representing the tax code related to the product type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. - TaxCode *string `json:"tax_code,omitempty"` + // The product name + Name string `json:"name"` + // The product API handle + Handle *string `json:"handle,omitempty"` + // The product description + Description string `json:"description"` + // E.g. Internal ID or SKU Number + AccountingCode *string `json:"accounting_code,omitempty"` + // Deprecated value that can be ignored unless you have legacy hosted pages. For Public Signup Page users, please read this attribute from under the signup page. + RequireCreditCard *bool `json:"require_credit_card,omitempty"` + // The product price, in integer cents + PriceInCents int64 `json:"price_in_cents"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product would renew every 30 days + Interval int `json:"interval"` + // A string representing the interval unit for this product, either month or day + IntervalUnit IntervalUnit `json:"interval_unit"` + // The product trial price, in integer cents + TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` + // The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product trial would last 30 days. + TrialInterval *int `json:"trial_interval,omitempty"` + // A string representing the trial interval unit for this product, either month or day + TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` + TrialType *string `json:"trial_type,omitempty"` + // The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product would expire after 30 days. + ExpirationInterval *int `json:"expiration_interval,omitempty"` + // A string representing the expiration interval unit for this product, either month or day + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` + AutoCreateSignupPage *bool `json:"auto_create_signup_page,omitempty"` + // A string representing the tax code related to the product type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. + TaxCode *string `json:"tax_code,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateProduct. +// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateProduct. // It customizes the JSON marshaling process for CreateOrUpdateProduct objects. func (c *CreateOrUpdateProduct) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateOrUpdateProduct object to a map representation for JSON marshaling. func (c *CreateOrUpdateProduct) toMap() map[string]any { - structMap := make(map[string]any) - structMap["name"] = c.Name - if c.Handle != nil { - structMap["handle"] = c.Handle - } - structMap["description"] = c.Description - if c.AccountingCode != nil { - structMap["accounting_code"] = c.AccountingCode - } - if c.RequireCreditCard != nil { - structMap["require_credit_card"] = c.RequireCreditCard - } - structMap["price_in_cents"] = c.PriceInCents - structMap["interval"] = c.Interval - structMap["interval_unit"] = c.IntervalUnit - if c.TrialPriceInCents != nil { - structMap["trial_price_in_cents"] = c.TrialPriceInCents - } - if c.TrialInterval != nil { - structMap["trial_interval"] = c.TrialInterval - } - if c.TrialIntervalUnit != nil { - structMap["trial_interval_unit"] = c.TrialIntervalUnit - } - if c.TrialType != nil { - structMap["trial_type"] = c.TrialType - } - if c.ExpirationInterval != nil { - structMap["expiration_interval"] = c.ExpirationInterval - } - if c.ExpirationIntervalUnit != nil { - structMap["expiration_interval_unit"] = c.ExpirationIntervalUnit - } - if c.AutoCreateSignupPage != nil { - structMap["auto_create_signup_page"] = c.AutoCreateSignupPage - } - if c.TaxCode != nil { - structMap["tax_code"] = c.TaxCode - } - return structMap + structMap := make(map[string]any) + structMap["name"] = c.Name + if c.Handle != nil { + structMap["handle"] = c.Handle + } + structMap["description"] = c.Description + if c.AccountingCode != nil { + structMap["accounting_code"] = c.AccountingCode + } + if c.RequireCreditCard != nil { + structMap["require_credit_card"] = c.RequireCreditCard + } + structMap["price_in_cents"] = c.PriceInCents + structMap["interval"] = c.Interval + structMap["interval_unit"] = c.IntervalUnit + if c.TrialPriceInCents != nil { + structMap["trial_price_in_cents"] = c.TrialPriceInCents + } + if c.TrialInterval != nil { + structMap["trial_interval"] = c.TrialInterval + } + if c.TrialIntervalUnit != nil { + structMap["trial_interval_unit"] = c.TrialIntervalUnit + } + if c.TrialType != nil { + structMap["trial_type"] = c.TrialType + } + if c.ExpirationInterval != nil { + structMap["expiration_interval"] = c.ExpirationInterval + } + if c.ExpirationIntervalUnit != nil { + structMap["expiration_interval_unit"] = c.ExpirationIntervalUnit + } + if c.AutoCreateSignupPage != nil { + structMap["auto_create_signup_page"] = c.AutoCreateSignupPage + } + if c.TaxCode != nil { + structMap["tax_code"] = c.TaxCode + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateProduct. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateProduct. // It customizes the JSON unmarshaling process for CreateOrUpdateProduct objects. func (c *CreateOrUpdateProduct) UnmarshalJSON(input []byte) error { - temp := &struct { - Name string `json:"name"` - Handle *string `json:"handle,omitempty"` - Description string `json:"description"` - AccountingCode *string `json:"accounting_code,omitempty"` - RequireCreditCard *bool `json:"require_credit_card,omitempty"` - PriceInCents int64 `json:"price_in_cents"` - Interval int `json:"interval"` - IntervalUnit IntervalUnit `json:"interval_unit"` - TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` - TrialInterval *int `json:"trial_interval,omitempty"` - TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` - TrialType *string `json:"trial_type,omitempty"` - ExpirationInterval *int `json:"expiration_interval,omitempty"` - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` - AutoCreateSignupPage *bool `json:"auto_create_signup_page,omitempty"` - TaxCode *string `json:"tax_code,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Name = temp.Name - c.Handle = temp.Handle - c.Description = temp.Description - c.AccountingCode = temp.AccountingCode - c.RequireCreditCard = temp.RequireCreditCard - c.PriceInCents = temp.PriceInCents - c.Interval = temp.Interval - c.IntervalUnit = temp.IntervalUnit - c.TrialPriceInCents = temp.TrialPriceInCents - c.TrialInterval = temp.TrialInterval - c.TrialIntervalUnit = temp.TrialIntervalUnit - c.TrialType = temp.TrialType - c.ExpirationInterval = temp.ExpirationInterval - c.ExpirationIntervalUnit = temp.ExpirationIntervalUnit - c.AutoCreateSignupPage = temp.AutoCreateSignupPage - c.TaxCode = temp.TaxCode - return nil + var temp createOrUpdateProduct + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Name = *temp.Name + c.Handle = temp.Handle + c.Description = *temp.Description + c.AccountingCode = temp.AccountingCode + c.RequireCreditCard = temp.RequireCreditCard + c.PriceInCents = *temp.PriceInCents + c.Interval = *temp.Interval + c.IntervalUnit = *temp.IntervalUnit + c.TrialPriceInCents = temp.TrialPriceInCents + c.TrialInterval = temp.TrialInterval + c.TrialIntervalUnit = temp.TrialIntervalUnit + c.TrialType = temp.TrialType + c.ExpirationInterval = temp.ExpirationInterval + c.ExpirationIntervalUnit = temp.ExpirationIntervalUnit + c.AutoCreateSignupPage = temp.AutoCreateSignupPage + c.TaxCode = temp.TaxCode + return nil +} + +// TODO +type createOrUpdateProduct struct { + Name *string `json:"name"` + Handle *string `json:"handle,omitempty"` + Description *string `json:"description"` + AccountingCode *string `json:"accounting_code,omitempty"` + RequireCreditCard *bool `json:"require_credit_card,omitempty"` + PriceInCents *int64 `json:"price_in_cents"` + Interval *int `json:"interval"` + IntervalUnit *IntervalUnit `json:"interval_unit"` + TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` + TrialInterval *int `json:"trial_interval,omitempty"` + TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` + TrialType *string `json:"trial_type,omitempty"` + ExpirationInterval *int `json:"expiration_interval,omitempty"` + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` + AutoCreateSignupPage *bool `json:"auto_create_signup_page,omitempty"` + TaxCode *string `json:"tax_code,omitempty"` +} + +func (c *createOrUpdateProduct) validate() error { + var errs []string + if c.Name == nil { + errs = append(errs, "required field `name` is missing for type `Create or Update Product`") + } + if c.Description == nil { + errs = append(errs, "required field `description` is missing for type `Create or Update Product`") + } + if c.PriceInCents == nil { + errs = append(errs, "required field `price_in_cents` is missing for type `Create or Update Product`") + } + if c.Interval == nil { + errs = append(errs, "required field `interval` is missing for type `Create or Update Product`") + } + if c.IntervalUnit == nil { + errs = append(errs, "required field `interval_unit` is missing for type `Create or Update Product`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_or_update_product_request.go b/models/create_or_update_product_request.go index 3ffeb142..b9f2b124 100644 --- a/models/create_or_update_product_request.go +++ b/models/create_or_update_product_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateOrUpdateProductRequest represents a CreateOrUpdateProductRequest struct. type CreateOrUpdateProductRequest struct { - Product CreateOrUpdateProduct `json:"product"` + Product CreateOrUpdateProduct `json:"product"` } -// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateProductRequest. +// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateProductRequest. // It customizes the JSON marshaling process for CreateOrUpdateProductRequest objects. func (c *CreateOrUpdateProductRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateOrUpdateProductRequest object to a map representation for JSON marshaling. func (c *CreateOrUpdateProductRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["product"] = c.Product.toMap() - return structMap + structMap := make(map[string]any) + structMap["product"] = c.Product.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateProductRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateProductRequest. // It customizes the JSON unmarshaling process for CreateOrUpdateProductRequest objects. func (c *CreateOrUpdateProductRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Product CreateOrUpdateProduct `json:"product"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Product = temp.Product - return nil + var temp createOrUpdateProductRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Product = *temp.Product + return nil +} + +// TODO +type createOrUpdateProductRequest struct { + Product *CreateOrUpdateProduct `json:"product"` +} + +func (c *createOrUpdateProductRequest) validate() error { + var errs []string + if c.Product == nil { + errs = append(errs, "required field `product` is missing for type `Create or Update Product Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_or_update_segment_price.go b/models/create_or_update_segment_price.go index 57467ca3..989406e2 100644 --- a/models/create_or_update_segment_price.go +++ b/models/create_or_update_segment_price.go @@ -1,53 +1,73 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateOrUpdateSegmentPrice represents a CreateOrUpdateSegmentPrice struct. type CreateOrUpdateSegmentPrice struct { - StartingQuantity *int `json:"starting_quantity,omitempty"` - EndingQuantity *int `json:"ending_quantity,omitempty"` - // The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 - UnitPrice interface{} `json:"unit_price"` + StartingQuantity *int `json:"starting_quantity,omitempty"` + EndingQuantity *int `json:"ending_quantity,omitempty"` + // The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 + UnitPrice CreateOrUpdateSegmentPriceUnitPrice `json:"unit_price"` } -// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateSegmentPrice. +// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateSegmentPrice. // It customizes the JSON marshaling process for CreateOrUpdateSegmentPrice objects. func (c *CreateOrUpdateSegmentPrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateOrUpdateSegmentPrice object to a map representation for JSON marshaling. func (c *CreateOrUpdateSegmentPrice) toMap() map[string]any { - structMap := make(map[string]any) - if c.StartingQuantity != nil { - structMap["starting_quantity"] = c.StartingQuantity - } - if c.EndingQuantity != nil { - structMap["ending_quantity"] = c.EndingQuantity - } - structMap["unit_price"] = c.UnitPrice - return structMap + structMap := make(map[string]any) + if c.StartingQuantity != nil { + structMap["starting_quantity"] = c.StartingQuantity + } + if c.EndingQuantity != nil { + structMap["ending_quantity"] = c.EndingQuantity + } + structMap["unit_price"] = c.UnitPrice.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateSegmentPrice. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateSegmentPrice. // It customizes the JSON unmarshaling process for CreateOrUpdateSegmentPrice objects. func (c *CreateOrUpdateSegmentPrice) UnmarshalJSON(input []byte) error { - temp := &struct { - StartingQuantity *int `json:"starting_quantity,omitempty"` - EndingQuantity *int `json:"ending_quantity,omitempty"` - UnitPrice interface{} `json:"unit_price"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.StartingQuantity = temp.StartingQuantity - c.EndingQuantity = temp.EndingQuantity - c.UnitPrice = temp.UnitPrice - return nil + var temp createOrUpdateSegmentPrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.StartingQuantity = temp.StartingQuantity + c.EndingQuantity = temp.EndingQuantity + c.UnitPrice = *temp.UnitPrice + return nil +} + +// TODO +type createOrUpdateSegmentPrice struct { + StartingQuantity *int `json:"starting_quantity,omitempty"` + EndingQuantity *int `json:"ending_quantity,omitempty"` + UnitPrice *CreateOrUpdateSegmentPriceUnitPrice `json:"unit_price"` +} + +func (c *createOrUpdateSegmentPrice) validate() error { + var errs []string + if c.UnitPrice == nil { + errs = append(errs, "required field `unit_price` is missing for type `Create or Update Segment Price`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_or_update_segment_price_unit_price.go b/models/create_or_update_segment_price_unit_price.go new file mode 100644 index 00000000..575fefb3 --- /dev/null +++ b/models/create_or_update_segment_price_unit_price.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateOrUpdateSegmentPriceUnitPrice represents a CreateOrUpdateSegmentPriceUnitPrice struct. +// This is a container for one-of cases. +type CreateOrUpdateSegmentPriceUnitPrice struct { + value any + isString bool + isPrecision bool +} + +// String converts the CreateOrUpdateSegmentPriceUnitPrice object to a string representation. +func (c CreateOrUpdateSegmentPriceUnitPrice) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateOrUpdateSegmentPriceUnitPrice. +// It customizes the JSON marshaling process for CreateOrUpdateSegmentPriceUnitPrice objects. +func (c *CreateOrUpdateSegmentPriceUnitPrice) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateOrUpdateSegmentPriceUnitPriceContainer.From*` functions to initialize the CreateOrUpdateSegmentPriceUnitPrice object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateOrUpdateSegmentPriceUnitPrice object to a map representation for JSON marshaling. +func (c *CreateOrUpdateSegmentPriceUnitPrice) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateOrUpdateSegmentPriceUnitPrice. +// It customizes the JSON unmarshaling process for CreateOrUpdateSegmentPriceUnitPrice objects. +func (c *CreateOrUpdateSegmentPriceUnitPrice) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(float64), false, &c.isPrecision), + ) + + c.value = result + return err +} + +func (c *CreateOrUpdateSegmentPriceUnitPrice) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateOrUpdateSegmentPriceUnitPrice) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +// internalCreateOrUpdateSegmentPriceUnitPrice represents a createOrUpdateSegmentPriceUnitPrice struct. +// This is a container for one-of cases. +type internalCreateOrUpdateSegmentPriceUnitPrice struct{} + +var CreateOrUpdateSegmentPriceUnitPriceContainer internalCreateOrUpdateSegmentPriceUnitPrice + +func (c *internalCreateOrUpdateSegmentPriceUnitPrice) FromString(val string) CreateOrUpdateSegmentPriceUnitPrice { + return CreateOrUpdateSegmentPriceUnitPrice{value: &val} +} + +func (c *internalCreateOrUpdateSegmentPriceUnitPrice) FromPrecision(val float64) CreateOrUpdateSegmentPriceUnitPrice { + return CreateOrUpdateSegmentPriceUnitPrice{value: &val} +} diff --git a/models/create_payment.go b/models/create_payment.go index 2587ea9e..c9722ef1 100644 --- a/models/create_payment.go +++ b/models/create_payment.go @@ -1,53 +1,82 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreatePayment represents a CreatePayment struct. type CreatePayment struct { - Amount string `json:"amount"` - Memo string `json:"memo"` - PaymentDetails string `json:"payment_details"` - // The type of payment method used. Defaults to other. - PaymentMethod InvoicePaymentMethodType `json:"payment_method"` + Amount string `json:"amount"` + Memo string `json:"memo"` + PaymentDetails string `json:"payment_details"` + // The type of payment method used. Defaults to other. + PaymentMethod InvoicePaymentMethodType `json:"payment_method"` } -// MarshalJSON implements the json.Marshaler interface for CreatePayment. +// MarshalJSON implements the json.Marshaler interface for CreatePayment. // It customizes the JSON marshaling process for CreatePayment objects. func (c *CreatePayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreatePayment object to a map representation for JSON marshaling. func (c *CreatePayment) toMap() map[string]any { - structMap := make(map[string]any) - structMap["amount"] = c.Amount - structMap["memo"] = c.Memo - structMap["payment_details"] = c.PaymentDetails - structMap["payment_method"] = c.PaymentMethod - return structMap + structMap := make(map[string]any) + structMap["amount"] = c.Amount + structMap["memo"] = c.Memo + structMap["payment_details"] = c.PaymentDetails + structMap["payment_method"] = c.PaymentMethod + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreatePayment. +// UnmarshalJSON implements the json.Unmarshaler interface for CreatePayment. // It customizes the JSON unmarshaling process for CreatePayment objects. func (c *CreatePayment) UnmarshalJSON(input []byte) error { - temp := &struct { - Amount string `json:"amount"` - Memo string `json:"memo"` - PaymentDetails string `json:"payment_details"` - PaymentMethod InvoicePaymentMethodType `json:"payment_method"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Amount = temp.Amount - c.Memo = temp.Memo - c.PaymentDetails = temp.PaymentDetails - c.PaymentMethod = temp.PaymentMethod - return nil + var temp createPayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Amount = *temp.Amount + c.Memo = *temp.Memo + c.PaymentDetails = *temp.PaymentDetails + c.PaymentMethod = *temp.PaymentMethod + return nil +} + +// TODO +type createPayment struct { + Amount *string `json:"amount"` + Memo *string `json:"memo"` + PaymentDetails *string `json:"payment_details"` + PaymentMethod *InvoicePaymentMethodType `json:"payment_method"` +} + +func (c *createPayment) validate() error { + var errs []string + if c.Amount == nil { + errs = append(errs, "required field `amount` is missing for type `Create Payment`") + } + if c.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Create Payment`") + } + if c.PaymentDetails == nil { + errs = append(errs, "required field `payment_details` is missing for type `Create Payment`") + } + if c.PaymentMethod == nil { + errs = append(errs, "required field `payment_method` is missing for type `Create Payment`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_payment_profile.go b/models/create_payment_profile.go index e2d1beaf..e699ec8b 100644 --- a/models/create_payment_profile.go +++ b/models/create_payment_profile.go @@ -1,257 +1,263 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreatePaymentProfile represents a CreatePaymentProfile struct. type CreatePaymentProfile struct { - // Token received after sending billing informations using chargify.js. - ChargifyToken *string `json:"chargify_token,omitempty"` - Id *int `json:"id,omitempty"` - PaymentType *PaymentType `json:"payment_type,omitempty"` - // First name on card or bank account. If omitted, the first_name from customer attributes will be used. - FirstName *string `json:"first_name,omitempty"` - // Last name on card or bank account. If omitted, the last_name from customer attributes will be used. - LastName *string `json:"last_name,omitempty"` - MaskedCardNumber *string `json:"masked_card_number,omitempty"` - // The full credit card number - FullNumber *string `json:"full_number,omitempty"` - // The type of card used. - CardType *CardType `json:"card_type,omitempty"` - // (Optional when performing an Import via vault_token, required otherwise) The 1- or 2-digit credit card expiration month, as an integer or string, i.e. 5 - ExpirationMonth *interface{} `json:"expiration_month,omitempty"` - // (Optional when performing a Import via vault_token, required otherwise) The 4-digit credit card expiration year, as an integer or string, i.e. 2012 - ExpirationYear *interface{} `json:"expiration_year,omitempty"` - // The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. - BillingAddress *string `json:"billing_address,omitempty"` - // Second line of the customer’s billing address i.e. Apt. 100 - BillingAddress2 Optional[string] `json:"billing_address_2"` - // The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. - BillingCity *string `json:"billing_city,omitempty"` - // The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. - BillingState *string `json:"billing_state,omitempty"` - // The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. - BillingCountry *string `json:"billing_country,omitempty"` - // The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. - BillingZip *string `json:"billing_zip,omitempty"` - // The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. - CurrentVault *CurrentVault `json:"current_vault,omitempty"` - // The “token” provided by your vault storage for an already stored payment profile - VaultToken *string `json:"vault_token,omitempty"` - // (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token - CustomerVaultToken *string `json:"customer_vault_token,omitempty"` - // (Required when creating a new payment profile) The Chargify customer id. - CustomerId *int `json:"customer_id,omitempty"` - // used by merchants that implemented BraintreeBlue javaScript libraries on their own. We recommend using Chargify.js instead. - PaypalEmail *string `json:"paypal_email,omitempty"` // Deprecated - // used by merchants that implemented BraintreeBlue javaScript libraries on their own. We recommend using Chargify.js instead. - PaymentMethodNonce *string `json:"payment_method_nonce,omitempty"` // Deprecated - // This attribute is only available if MultiGateway feature is enabled for your Site. This feature is in the Private Beta currently. gateway_handle is used to directly select a gateway where a payment profile will be stored in. Every connected gateway must have a unique gateway handle specified. Read [Multigateway description](https://chargify.zendesk.com/hc/en-us/articles/4407761759643#connecting-with-multiple-gateways) to learn more about new concepts that MultiGateway introduces and the default behavior when this attribute is not passed. - GatewayHandle *string `json:"gateway_handle,omitempty"` - // The 3- or 4-digit Card Verification Value. This value is merely passed through to the payment gateway. - Cvv *string `json:"cvv,omitempty"` - // (Required when creating with ACH or GoCardless, optional with Stripe Direct Debit). The name of the bank where the customerʼs account resides - BankName *string `json:"bank_name,omitempty"` - // (Optional when creating with GoCardless, required with Stripe Direct Debit). International Bank Account Number. Alternatively, local bank details can be provided - BankIban *string `json:"bank_iban,omitempty"` - // (Required when creating with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API - BankRoutingNumber *string `json:"bank_routing_number,omitempty"` - // (Required when creating with ACH, GoCardless, Stripe BECS Direct Debit and bank_iban is blank) The customerʼs bank account number - BankAccountNumber *string `json:"bank_account_number,omitempty"` - // (Optional when creating with GoCardless, required with Stripe BECS Direct Debit) Branch code. Alternatively, an IBAN can be provided - BankBranchCode *string `json:"bank_branch_code,omitempty"` - // Defaults to checking - BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` - // Defaults to personal - BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` - // (Optional) Used for creating subscription with payment profile imported using vault_token, for proper display in Advanced Billing UI - LastFour *string `json:"last_four,omitempty"` + // Token received after sending billing informations using chargify.js. + ChargifyToken *string `json:"chargify_token,omitempty"` + Id *int `json:"id,omitempty"` + PaymentType *PaymentType `json:"payment_type,omitempty"` + // First name on card or bank account. If omitted, the first_name from customer attributes will be used. + FirstName *string `json:"first_name,omitempty"` + // Last name on card or bank account. If omitted, the last_name from customer attributes will be used. + LastName *string `json:"last_name,omitempty"` + MaskedCardNumber *string `json:"masked_card_number,omitempty"` + // The full credit card number + FullNumber *string `json:"full_number,omitempty"` + // The type of card used. + CardType *CardType `json:"card_type,omitempty"` + // (Optional when performing an Import via vault_token, required otherwise) The 1- or 2-digit credit card expiration month, as an integer or string, i.e. 5 + ExpirationMonth *CreatePaymentProfileExpirationMonth `json:"expiration_month,omitempty"` + // (Optional when performing a Import via vault_token, required otherwise) The 4-digit credit card expiration year, as an integer or string, i.e. 2012 + ExpirationYear *CreatePaymentProfileExpirationYear `json:"expiration_year,omitempty"` + // The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. + BillingAddress *string `json:"billing_address,omitempty"` + // Second line of the customer’s billing address i.e. Apt. 100 + BillingAddress2 Optional[string] `json:"billing_address_2"` + // The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. + BillingCity *string `json:"billing_city,omitempty"` + // The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. + BillingState *string `json:"billing_state,omitempty"` + // The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. + BillingCountry *string `json:"billing_country,omitempty"` + // The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. + BillingZip *string `json:"billing_zip,omitempty"` + // The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. + CurrentVault *CurrentVault `json:"current_vault,omitempty"` + // The “token” provided by your vault storage for an already stored payment profile + VaultToken *string `json:"vault_token,omitempty"` + // (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token + CustomerVaultToken *string `json:"customer_vault_token,omitempty"` + // (Required when creating a new payment profile) The Chargify customer id. + CustomerId *int `json:"customer_id,omitempty"` + // used by merchants that implemented BraintreeBlue javaScript libraries on their own. We recommend using Chargify.js instead. + PaypalEmail *string `json:"paypal_email,omitempty"` // Deprecated + // used by merchants that implemented BraintreeBlue javaScript libraries on their own. We recommend using Chargify.js instead. + PaymentMethodNonce *string `json:"payment_method_nonce,omitempty"` // Deprecated + // This attribute is only available if MultiGateway feature is enabled for your Site. This feature is in the Private Beta currently. gateway_handle is used to directly select a gateway where a payment profile will be stored in. Every connected gateway must have a unique gateway handle specified. Read [Multigateway description](https://chargify.zendesk.com/hc/en-us/articles/4407761759643#connecting-with-multiple-gateways) to learn more about new concepts that MultiGateway introduces and the default behavior when this attribute is not passed. + GatewayHandle *string `json:"gateway_handle,omitempty"` + // The 3- or 4-digit Card Verification Value. This value is merely passed through to the payment gateway. + Cvv *string `json:"cvv,omitempty"` + // (Required when creating with ACH or GoCardless, optional with Stripe Direct Debit). The name of the bank where the customerʼs account resides + BankName *string `json:"bank_name,omitempty"` + // (Optional when creating with GoCardless, required with Stripe Direct Debit). International Bank Account Number. Alternatively, local bank details can be provided + BankIban *string `json:"bank_iban,omitempty"` + // (Required when creating with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API + BankRoutingNumber *string `json:"bank_routing_number,omitempty"` + // (Required when creating with ACH, GoCardless, Stripe BECS Direct Debit and bank_iban is blank) The customerʼs bank account number + BankAccountNumber *string `json:"bank_account_number,omitempty"` + // (Optional when creating with GoCardless, required with Stripe BECS Direct Debit) Branch code. Alternatively, an IBAN can be provided + BankBranchCode *string `json:"bank_branch_code,omitempty"` + // Defaults to checking + BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` + // Defaults to personal + BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` + // (Optional) Used for creating subscription with payment profile imported using vault_token, for proper display in Advanced Billing UI + LastFour *string `json:"last_four,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreatePaymentProfile. +// MarshalJSON implements the json.Marshaler interface for CreatePaymentProfile. // It customizes the JSON marshaling process for CreatePaymentProfile objects. func (c *CreatePaymentProfile) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreatePaymentProfile object to a map representation for JSON marshaling. func (c *CreatePaymentProfile) toMap() map[string]any { - structMap := make(map[string]any) - if c.ChargifyToken != nil { - structMap["chargify_token"] = c.ChargifyToken - } - if c.Id != nil { - structMap["id"] = c.Id - } - if c.PaymentType != nil { - structMap["payment_type"] = c.PaymentType - } - if c.FirstName != nil { - structMap["first_name"] = c.FirstName - } - if c.LastName != nil { - structMap["last_name"] = c.LastName - } - if c.MaskedCardNumber != nil { - structMap["masked_card_number"] = c.MaskedCardNumber - } - if c.FullNumber != nil { - structMap["full_number"] = c.FullNumber - } - if c.CardType != nil { - structMap["card_type"] = c.CardType - } - if c.ExpirationMonth != nil { - structMap["expiration_month"] = c.ExpirationMonth - } - if c.ExpirationYear != nil { - structMap["expiration_year"] = c.ExpirationYear - } - if c.BillingAddress != nil { - structMap["billing_address"] = c.BillingAddress - } - if c.BillingAddress2.IsValueSet() { - structMap["billing_address_2"] = c.BillingAddress2.Value() - } - if c.BillingCity != nil { - structMap["billing_city"] = c.BillingCity - } - if c.BillingState != nil { - structMap["billing_state"] = c.BillingState - } - if c.BillingCountry != nil { - structMap["billing_country"] = c.BillingCountry - } - if c.BillingZip != nil { - structMap["billing_zip"] = c.BillingZip - } - if c.CurrentVault != nil { - structMap["current_vault"] = c.CurrentVault - } - if c.VaultToken != nil { - structMap["vault_token"] = c.VaultToken - } - if c.CustomerVaultToken != nil { - structMap["customer_vault_token"] = c.CustomerVaultToken - } - if c.CustomerId != nil { - structMap["customer_id"] = c.CustomerId - } - if c.PaypalEmail != nil { - structMap["paypal_email"] = c.PaypalEmail - } - if c.PaymentMethodNonce != nil { - structMap["payment_method_nonce"] = c.PaymentMethodNonce - } - if c.GatewayHandle != nil { - structMap["gateway_handle"] = c.GatewayHandle - } - if c.Cvv != nil { - structMap["cvv"] = c.Cvv - } - if c.BankName != nil { - structMap["bank_name"] = c.BankName - } - if c.BankIban != nil { - structMap["bank_iban"] = c.BankIban - } - if c.BankRoutingNumber != nil { - structMap["bank_routing_number"] = c.BankRoutingNumber - } - if c.BankAccountNumber != nil { - structMap["bank_account_number"] = c.BankAccountNumber - } - if c.BankBranchCode != nil { - structMap["bank_branch_code"] = c.BankBranchCode - } - if c.BankAccountType != nil { - structMap["bank_account_type"] = c.BankAccountType - } - if c.BankAccountHolderType != nil { - structMap["bank_account_holder_type"] = c.BankAccountHolderType - } - if c.LastFour != nil { - structMap["last_four"] = c.LastFour - } - return structMap + structMap := make(map[string]any) + if c.ChargifyToken != nil { + structMap["chargify_token"] = c.ChargifyToken + } + if c.Id != nil { + structMap["id"] = c.Id + } + if c.PaymentType != nil { + structMap["payment_type"] = c.PaymentType + } + if c.FirstName != nil { + structMap["first_name"] = c.FirstName + } + if c.LastName != nil { + structMap["last_name"] = c.LastName + } + if c.MaskedCardNumber != nil { + structMap["masked_card_number"] = c.MaskedCardNumber + } + if c.FullNumber != nil { + structMap["full_number"] = c.FullNumber + } + if c.CardType != nil { + structMap["card_type"] = c.CardType + } + if c.ExpirationMonth != nil { + structMap["expiration_month"] = c.ExpirationMonth.toMap() + } + if c.ExpirationYear != nil { + structMap["expiration_year"] = c.ExpirationYear.toMap() + } + if c.BillingAddress != nil { + structMap["billing_address"] = c.BillingAddress + } + if c.BillingAddress2.IsValueSet() { + if c.BillingAddress2.Value() != nil { + structMap["billing_address_2"] = c.BillingAddress2.Value() + } else { + structMap["billing_address_2"] = nil + } + } + if c.BillingCity != nil { + structMap["billing_city"] = c.BillingCity + } + if c.BillingState != nil { + structMap["billing_state"] = c.BillingState + } + if c.BillingCountry != nil { + structMap["billing_country"] = c.BillingCountry + } + if c.BillingZip != nil { + structMap["billing_zip"] = c.BillingZip + } + if c.CurrentVault != nil { + structMap["current_vault"] = c.CurrentVault + } + if c.VaultToken != nil { + structMap["vault_token"] = c.VaultToken + } + if c.CustomerVaultToken != nil { + structMap["customer_vault_token"] = c.CustomerVaultToken + } + if c.CustomerId != nil { + structMap["customer_id"] = c.CustomerId + } + if c.PaypalEmail != nil { + structMap["paypal_email"] = c.PaypalEmail + } + if c.PaymentMethodNonce != nil { + structMap["payment_method_nonce"] = c.PaymentMethodNonce + } + if c.GatewayHandle != nil { + structMap["gateway_handle"] = c.GatewayHandle + } + if c.Cvv != nil { + structMap["cvv"] = c.Cvv + } + if c.BankName != nil { + structMap["bank_name"] = c.BankName + } + if c.BankIban != nil { + structMap["bank_iban"] = c.BankIban + } + if c.BankRoutingNumber != nil { + structMap["bank_routing_number"] = c.BankRoutingNumber + } + if c.BankAccountNumber != nil { + structMap["bank_account_number"] = c.BankAccountNumber + } + if c.BankBranchCode != nil { + structMap["bank_branch_code"] = c.BankBranchCode + } + if c.BankAccountType != nil { + structMap["bank_account_type"] = c.BankAccountType + } + if c.BankAccountHolderType != nil { + structMap["bank_account_holder_type"] = c.BankAccountHolderType + } + if c.LastFour != nil { + structMap["last_four"] = c.LastFour + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreatePaymentProfile. +// UnmarshalJSON implements the json.Unmarshaler interface for CreatePaymentProfile. // It customizes the JSON unmarshaling process for CreatePaymentProfile objects. func (c *CreatePaymentProfile) UnmarshalJSON(input []byte) error { - temp := &struct { - ChargifyToken *string `json:"chargify_token,omitempty"` - Id *int `json:"id,omitempty"` - PaymentType *PaymentType `json:"payment_type,omitempty"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - MaskedCardNumber *string `json:"masked_card_number,omitempty"` - FullNumber *string `json:"full_number,omitempty"` - CardType *CardType `json:"card_type,omitempty"` - ExpirationMonth *interface{} `json:"expiration_month,omitempty"` - ExpirationYear *interface{} `json:"expiration_year,omitempty"` - BillingAddress *string `json:"billing_address,omitempty"` - BillingAddress2 Optional[string] `json:"billing_address_2"` - BillingCity *string `json:"billing_city,omitempty"` - BillingState *string `json:"billing_state,omitempty"` - BillingCountry *string `json:"billing_country,omitempty"` - BillingZip *string `json:"billing_zip,omitempty"` - CurrentVault *CurrentVault `json:"current_vault,omitempty"` - VaultToken *string `json:"vault_token,omitempty"` - CustomerVaultToken *string `json:"customer_vault_token,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - PaypalEmail *string `json:"paypal_email,omitempty"` - PaymentMethodNonce *string `json:"payment_method_nonce,omitempty"` - GatewayHandle *string `json:"gateway_handle,omitempty"` - Cvv *string `json:"cvv,omitempty"` - BankName *string `json:"bank_name,omitempty"` - BankIban *string `json:"bank_iban,omitempty"` - BankRoutingNumber *string `json:"bank_routing_number,omitempty"` - BankAccountNumber *string `json:"bank_account_number,omitempty"` - BankBranchCode *string `json:"bank_branch_code,omitempty"` - BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` - BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` - LastFour *string `json:"last_four,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ChargifyToken = temp.ChargifyToken - c.Id = temp.Id - c.PaymentType = temp.PaymentType - c.FirstName = temp.FirstName - c.LastName = temp.LastName - c.MaskedCardNumber = temp.MaskedCardNumber - c.FullNumber = temp.FullNumber - c.CardType = temp.CardType - c.ExpirationMonth = temp.ExpirationMonth - c.ExpirationYear = temp.ExpirationYear - c.BillingAddress = temp.BillingAddress - c.BillingAddress2 = temp.BillingAddress2 - c.BillingCity = temp.BillingCity - c.BillingState = temp.BillingState - c.BillingCountry = temp.BillingCountry - c.BillingZip = temp.BillingZip - c.CurrentVault = temp.CurrentVault - c.VaultToken = temp.VaultToken - c.CustomerVaultToken = temp.CustomerVaultToken - c.CustomerId = temp.CustomerId - c.PaypalEmail = temp.PaypalEmail - c.PaymentMethodNonce = temp.PaymentMethodNonce - c.GatewayHandle = temp.GatewayHandle - c.Cvv = temp.Cvv - c.BankName = temp.BankName - c.BankIban = temp.BankIban - c.BankRoutingNumber = temp.BankRoutingNumber - c.BankAccountNumber = temp.BankAccountNumber - c.BankBranchCode = temp.BankBranchCode - c.BankAccountType = temp.BankAccountType - c.BankAccountHolderType = temp.BankAccountHolderType - c.LastFour = temp.LastFour - return nil + var temp createPaymentProfile + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.ChargifyToken = temp.ChargifyToken + c.Id = temp.Id + c.PaymentType = temp.PaymentType + c.FirstName = temp.FirstName + c.LastName = temp.LastName + c.MaskedCardNumber = temp.MaskedCardNumber + c.FullNumber = temp.FullNumber + c.CardType = temp.CardType + c.ExpirationMonth = temp.ExpirationMonth + c.ExpirationYear = temp.ExpirationYear + c.BillingAddress = temp.BillingAddress + c.BillingAddress2 = temp.BillingAddress2 + c.BillingCity = temp.BillingCity + c.BillingState = temp.BillingState + c.BillingCountry = temp.BillingCountry + c.BillingZip = temp.BillingZip + c.CurrentVault = temp.CurrentVault + c.VaultToken = temp.VaultToken + c.CustomerVaultToken = temp.CustomerVaultToken + c.CustomerId = temp.CustomerId + c.PaypalEmail = temp.PaypalEmail + c.PaymentMethodNonce = temp.PaymentMethodNonce + c.GatewayHandle = temp.GatewayHandle + c.Cvv = temp.Cvv + c.BankName = temp.BankName + c.BankIban = temp.BankIban + c.BankRoutingNumber = temp.BankRoutingNumber + c.BankAccountNumber = temp.BankAccountNumber + c.BankBranchCode = temp.BankBranchCode + c.BankAccountType = temp.BankAccountType + c.BankAccountHolderType = temp.BankAccountHolderType + c.LastFour = temp.LastFour + return nil +} + +// TODO +type createPaymentProfile struct { + ChargifyToken *string `json:"chargify_token,omitempty"` + Id *int `json:"id,omitempty"` + PaymentType *PaymentType `json:"payment_type,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + MaskedCardNumber *string `json:"masked_card_number,omitempty"` + FullNumber *string `json:"full_number,omitempty"` + CardType *CardType `json:"card_type,omitempty"` + ExpirationMonth *CreatePaymentProfileExpirationMonth `json:"expiration_month,omitempty"` + ExpirationYear *CreatePaymentProfileExpirationYear `json:"expiration_year,omitempty"` + BillingAddress *string `json:"billing_address,omitempty"` + BillingAddress2 Optional[string] `json:"billing_address_2"` + BillingCity *string `json:"billing_city,omitempty"` + BillingState *string `json:"billing_state,omitempty"` + BillingCountry *string `json:"billing_country,omitempty"` + BillingZip *string `json:"billing_zip,omitempty"` + CurrentVault *CurrentVault `json:"current_vault,omitempty"` + VaultToken *string `json:"vault_token,omitempty"` + CustomerVaultToken *string `json:"customer_vault_token,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaypalEmail *string `json:"paypal_email,omitempty"` + PaymentMethodNonce *string `json:"payment_method_nonce,omitempty"` + GatewayHandle *string `json:"gateway_handle,omitempty"` + Cvv *string `json:"cvv,omitempty"` + BankName *string `json:"bank_name,omitempty"` + BankIban *string `json:"bank_iban,omitempty"` + BankRoutingNumber *string `json:"bank_routing_number,omitempty"` + BankAccountNumber *string `json:"bank_account_number,omitempty"` + BankBranchCode *string `json:"bank_branch_code,omitempty"` + BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` + BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` + LastFour *string `json:"last_four,omitempty"` } diff --git a/models/create_payment_profile_expiration_month.go b/models/create_payment_profile_expiration_month.go new file mode 100644 index 00000000..0cbd51ca --- /dev/null +++ b/models/create_payment_profile_expiration_month.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreatePaymentProfileExpirationMonth represents a CreatePaymentProfileExpirationMonth struct. +// This is a container for one-of cases. +type CreatePaymentProfileExpirationMonth struct { + value any + isNumber bool + isString bool +} + +// String converts the CreatePaymentProfileExpirationMonth object to a string representation. +func (c CreatePaymentProfileExpirationMonth) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreatePaymentProfileExpirationMonth. +// It customizes the JSON marshaling process for CreatePaymentProfileExpirationMonth objects. +func (c *CreatePaymentProfileExpirationMonth) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreatePaymentProfileExpirationMonthContainer.From*` functions to initialize the CreatePaymentProfileExpirationMonth object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreatePaymentProfileExpirationMonth object to a map representation for JSON marshaling. +func (c *CreatePaymentProfileExpirationMonth) toMap() any { + switch obj := c.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreatePaymentProfileExpirationMonth. +// It customizes the JSON unmarshaling process for CreatePaymentProfileExpirationMonth objects. +func (c *CreatePaymentProfileExpirationMonth) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(string), false, &c.isString), + ) + + c.value = result + return err +} + +func (c *CreatePaymentProfileExpirationMonth) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CreatePaymentProfileExpirationMonth) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +// internalCreatePaymentProfileExpirationMonth represents a createPaymentProfileExpirationMonth struct. +// This is a container for one-of cases. +type internalCreatePaymentProfileExpirationMonth struct{} + +var CreatePaymentProfileExpirationMonthContainer internalCreatePaymentProfileExpirationMonth + +func (c *internalCreatePaymentProfileExpirationMonth) FromNumber(val int) CreatePaymentProfileExpirationMonth { + return CreatePaymentProfileExpirationMonth{value: &val} +} + +func (c *internalCreatePaymentProfileExpirationMonth) FromString(val string) CreatePaymentProfileExpirationMonth { + return CreatePaymentProfileExpirationMonth{value: &val} +} diff --git a/models/create_payment_profile_expiration_year.go b/models/create_payment_profile_expiration_year.go new file mode 100644 index 00000000..683f19a1 --- /dev/null +++ b/models/create_payment_profile_expiration_year.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreatePaymentProfileExpirationYear represents a CreatePaymentProfileExpirationYear struct. +// This is a container for one-of cases. +type CreatePaymentProfileExpirationYear struct { + value any + isNumber bool + isString bool +} + +// String converts the CreatePaymentProfileExpirationYear object to a string representation. +func (c CreatePaymentProfileExpirationYear) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreatePaymentProfileExpirationYear. +// It customizes the JSON marshaling process for CreatePaymentProfileExpirationYear objects. +func (c *CreatePaymentProfileExpirationYear) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreatePaymentProfileExpirationYearContainer.From*` functions to initialize the CreatePaymentProfileExpirationYear object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreatePaymentProfileExpirationYear object to a map representation for JSON marshaling. +func (c *CreatePaymentProfileExpirationYear) toMap() any { + switch obj := c.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreatePaymentProfileExpirationYear. +// It customizes the JSON unmarshaling process for CreatePaymentProfileExpirationYear objects. +func (c *CreatePaymentProfileExpirationYear) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(string), false, &c.isString), + ) + + c.value = result + return err +} + +func (c *CreatePaymentProfileExpirationYear) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CreatePaymentProfileExpirationYear) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +// internalCreatePaymentProfileExpirationYear represents a createPaymentProfileExpirationYear struct. +// This is a container for one-of cases. +type internalCreatePaymentProfileExpirationYear struct{} + +var CreatePaymentProfileExpirationYearContainer internalCreatePaymentProfileExpirationYear + +func (c *internalCreatePaymentProfileExpirationYear) FromNumber(val int) CreatePaymentProfileExpirationYear { + return CreatePaymentProfileExpirationYear{value: &val} +} + +func (c *internalCreatePaymentProfileExpirationYear) FromString(val string) CreatePaymentProfileExpirationYear { + return CreatePaymentProfileExpirationYear{value: &val} +} diff --git a/models/create_payment_profile_request.go b/models/create_payment_profile_request.go index f8c7e703..740bc190 100644 --- a/models/create_payment_profile_request.go +++ b/models/create_payment_profile_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreatePaymentProfileRequest represents a CreatePaymentProfileRequest struct. type CreatePaymentProfileRequest struct { - PaymentProfile CreatePaymentProfile `json:"payment_profile"` + PaymentProfile CreatePaymentProfile `json:"payment_profile"` } -// MarshalJSON implements the json.Marshaler interface for CreatePaymentProfileRequest. +// MarshalJSON implements the json.Marshaler interface for CreatePaymentProfileRequest. // It customizes the JSON marshaling process for CreatePaymentProfileRequest objects. func (c *CreatePaymentProfileRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreatePaymentProfileRequest object to a map representation for JSON marshaling. func (c *CreatePaymentProfileRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["payment_profile"] = c.PaymentProfile.toMap() - return structMap + structMap := make(map[string]any) + structMap["payment_profile"] = c.PaymentProfile.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreatePaymentProfileRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreatePaymentProfileRequest. // It customizes the JSON unmarshaling process for CreatePaymentProfileRequest objects. func (c *CreatePaymentProfileRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - PaymentProfile CreatePaymentProfile `json:"payment_profile"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.PaymentProfile = temp.PaymentProfile - return nil + var temp createPaymentProfileRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.PaymentProfile = *temp.PaymentProfile + return nil +} + +// TODO +type createPaymentProfileRequest struct { + PaymentProfile *CreatePaymentProfile `json:"payment_profile"` +} + +func (c *createPaymentProfileRequest) validate() error { + var errs []string + if c.PaymentProfile == nil { + errs = append(errs, "required field `payment_profile` is missing for type `Create Payment Profile Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_prepaid_component.go b/models/create_prepaid_component.go index e7e80d37..45a7dbbc 100644 --- a/models/create_prepaid_component.go +++ b/models/create_prepaid_component.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreatePrepaidComponent represents a CreatePrepaidComponent struct. type CreatePrepaidComponent struct { - PrepaidUsageComponent PrepaidUsageComponent `json:"prepaid_usage_component"` + PrepaidUsageComponent PrepaidUsageComponent `json:"prepaid_usage_component"` } -// MarshalJSON implements the json.Marshaler interface for CreatePrepaidComponent. +// MarshalJSON implements the json.Marshaler interface for CreatePrepaidComponent. // It customizes the JSON marshaling process for CreatePrepaidComponent objects. func (c *CreatePrepaidComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreatePrepaidComponent object to a map representation for JSON marshaling. func (c *CreatePrepaidComponent) toMap() map[string]any { - structMap := make(map[string]any) - structMap["prepaid_usage_component"] = c.PrepaidUsageComponent.toMap() - return structMap + structMap := make(map[string]any) + structMap["prepaid_usage_component"] = c.PrepaidUsageComponent.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreatePrepaidComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for CreatePrepaidComponent. // It customizes the JSON unmarshaling process for CreatePrepaidComponent objects. func (c *CreatePrepaidComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - PrepaidUsageComponent PrepaidUsageComponent `json:"prepaid_usage_component"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.PrepaidUsageComponent = temp.PrepaidUsageComponent - return nil + var temp createPrepaidComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.PrepaidUsageComponent = *temp.PrepaidUsageComponent + return nil +} + +// TODO +type createPrepaidComponent struct { + PrepaidUsageComponent *PrepaidUsageComponent `json:"prepaid_usage_component"` +} + +func (c *createPrepaidComponent) validate() error { + var errs []string + if c.PrepaidUsageComponent == nil { + errs = append(errs, "required field `prepaid_usage_component` is missing for type `Create Prepaid Component`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_prepaid_usage_component_price_point.go b/models/create_prepaid_usage_component_price_point.go new file mode 100644 index 00000000..c3ff77e5 --- /dev/null +++ b/models/create_prepaid_usage_component_price_point.go @@ -0,0 +1,122 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreatePrepaidUsageComponentPricePoint represents a CreatePrepaidUsageComponentPricePoint struct. +type CreatePrepaidUsageComponentPricePoint struct { + Name string `json:"name"` + Handle *string `json:"handle,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme PricingScheme `json:"pricing_scheme"` + Prices []Price `json:"prices"` + OveragePricing OveragePricing `json:"overage_pricing"` + // Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + // Boolean which controls whether or not remaining units should be rolled over to the next period + RolloverPrepaidRemainder *bool `json:"rollover_prepaid_remainder,omitempty"` + // Boolean which controls whether or not the allocated quantity should be renewed at the beginning of each period + RenewPrepaidAllocation *bool `json:"renew_prepaid_allocation,omitempty"` + // (only for prepaid usage components where rollover_prepaid_remainder is true) The number of `expiration_interval_unit`s after which rollover amounts should expire + ExpirationInterval *float64 `json:"expiration_interval,omitempty"` + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for CreatePrepaidUsageComponentPricePoint. +// It customizes the JSON marshaling process for CreatePrepaidUsageComponentPricePoint objects. +func (c *CreatePrepaidUsageComponentPricePoint) MarshalJSON() ( + []byte, + error) { + return json.Marshal(c.toMap()) +} + +// toMap converts the CreatePrepaidUsageComponentPricePoint object to a map representation for JSON marshaling. +func (c *CreatePrepaidUsageComponentPricePoint) toMap() map[string]any { + structMap := make(map[string]any) + structMap["name"] = c.Name + if c.Handle != nil { + structMap["handle"] = c.Handle + } + structMap["pricing_scheme"] = c.PricingScheme + structMap["prices"] = c.Prices + structMap["overage_pricing"] = c.OveragePricing.toMap() + if c.UseSiteExchangeRate != nil { + structMap["use_site_exchange_rate"] = c.UseSiteExchangeRate + } + if c.RolloverPrepaidRemainder != nil { + structMap["rollover_prepaid_remainder"] = c.RolloverPrepaidRemainder + } + if c.RenewPrepaidAllocation != nil { + structMap["renew_prepaid_allocation"] = c.RenewPrepaidAllocation + } + if c.ExpirationInterval != nil { + structMap["expiration_interval"] = c.ExpirationInterval + } + if c.ExpirationIntervalUnit != nil { + structMap["expiration_interval_unit"] = c.ExpirationIntervalUnit + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreatePrepaidUsageComponentPricePoint. +// It customizes the JSON unmarshaling process for CreatePrepaidUsageComponentPricePoint objects. +func (c *CreatePrepaidUsageComponentPricePoint) UnmarshalJSON(input []byte) error { + var temp createPrepaidUsageComponentPricePoint + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Name = *temp.Name + c.Handle = temp.Handle + c.PricingScheme = *temp.PricingScheme + c.Prices = *temp.Prices + c.OveragePricing = *temp.OveragePricing + c.UseSiteExchangeRate = temp.UseSiteExchangeRate + c.RolloverPrepaidRemainder = temp.RolloverPrepaidRemainder + c.RenewPrepaidAllocation = temp.RenewPrepaidAllocation + c.ExpirationInterval = temp.ExpirationInterval + c.ExpirationIntervalUnit = temp.ExpirationIntervalUnit + return nil +} + +// TODO +type createPrepaidUsageComponentPricePoint struct { + Name *string `json:"name"` + Handle *string `json:"handle,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme"` + Prices *[]Price `json:"prices"` + OveragePricing *OveragePricing `json:"overage_pricing"` + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + RolloverPrepaidRemainder *bool `json:"rollover_prepaid_remainder,omitempty"` + RenewPrepaidAllocation *bool `json:"renew_prepaid_allocation,omitempty"` + ExpirationInterval *float64 `json:"expiration_interval,omitempty"` + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` +} + +func (c *createPrepaidUsageComponentPricePoint) validate() error { + var errs []string + if c.Name == nil { + errs = append(errs, "required field `name` is missing for type `Create Prepaid Usage Component Price Point`") + } + if c.PricingScheme == nil { + errs = append(errs, "required field `pricing_scheme` is missing for type `Create Prepaid Usage Component Price Point`") + } + if c.Prices == nil { + errs = append(errs, "required field `prices` is missing for type `Create Prepaid Usage Component Price Point`") + } + if c.OveragePricing == nil { + errs = append(errs, "required field `overage_pricing` is missing for type `Create Prepaid Usage Component Price Point`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/create_prepayment.go b/models/create_prepayment.go index e3051145..cb88da58 100644 --- a/models/create_prepayment.go +++ b/models/create_prepayment.go @@ -1,59 +1,88 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreatePrepayment represents a CreatePrepayment struct. type CreatePrepayment struct { - Amount float64 `json:"amount"` - Details string `json:"details"` - Memo string `json:"memo"` - // :- When the `method` specified is `"credit_card_on_file"`, the prepayment amount will be collected using the default credit card payment profile and applied to the prepayment account balance. This is especially useful for manual replenishment of prepaid subscriptions. - Method CreatePrepaymentMethod `json:"method"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` + Amount float64 `json:"amount"` + Details string `json:"details"` + Memo string `json:"memo"` + // :- When the `method` specified is `"credit_card_on_file"`, the prepayment amount will be collected using the default credit card payment profile and applied to the prepayment account balance. This is especially useful for manual replenishment of prepaid subscriptions. + Method CreatePrepaymentMethod `json:"method"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreatePrepayment. +// MarshalJSON implements the json.Marshaler interface for CreatePrepayment. // It customizes the JSON marshaling process for CreatePrepayment objects. func (c *CreatePrepayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreatePrepayment object to a map representation for JSON marshaling. func (c *CreatePrepayment) toMap() map[string]any { - structMap := make(map[string]any) - structMap["amount"] = c.Amount - structMap["details"] = c.Details - structMap["memo"] = c.Memo - structMap["method"] = c.Method - if c.PaymentProfileId != nil { - structMap["payment_profile_id"] = c.PaymentProfileId - } - return structMap + structMap := make(map[string]any) + structMap["amount"] = c.Amount + structMap["details"] = c.Details + structMap["memo"] = c.Memo + structMap["method"] = c.Method + if c.PaymentProfileId != nil { + structMap["payment_profile_id"] = c.PaymentProfileId + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreatePrepayment. +// UnmarshalJSON implements the json.Unmarshaler interface for CreatePrepayment. // It customizes the JSON unmarshaling process for CreatePrepayment objects. func (c *CreatePrepayment) UnmarshalJSON(input []byte) error { - temp := &struct { - Amount float64 `json:"amount"` - Details string `json:"details"` - Memo string `json:"memo"` - Method CreatePrepaymentMethod `json:"method"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Amount = temp.Amount - c.Details = temp.Details - c.Memo = temp.Memo - c.Method = temp.Method - c.PaymentProfileId = temp.PaymentProfileId - return nil + var temp createPrepayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Amount = *temp.Amount + c.Details = *temp.Details + c.Memo = *temp.Memo + c.Method = *temp.Method + c.PaymentProfileId = temp.PaymentProfileId + return nil +} + +// TODO +type createPrepayment struct { + Amount *float64 `json:"amount"` + Details *string `json:"details"` + Memo *string `json:"memo"` + Method *CreatePrepaymentMethod `json:"method"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` +} + +func (c *createPrepayment) validate() error { + var errs []string + if c.Amount == nil { + errs = append(errs, "required field `amount` is missing for type `Create Prepayment`") + } + if c.Details == nil { + errs = append(errs, "required field `details` is missing for type `Create Prepayment`") + } + if c.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Create Prepayment`") + } + if c.Method == nil { + errs = append(errs, "required field `method` is missing for type `Create Prepayment`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_prepayment_request.go b/models/create_prepayment_request.go index 23d6b5a1..b1c012e6 100644 --- a/models/create_prepayment_request.go +++ b/models/create_prepayment_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreatePrepaymentRequest represents a CreatePrepaymentRequest struct. type CreatePrepaymentRequest struct { - Prepayment CreatePrepayment `json:"prepayment"` + Prepayment CreatePrepayment `json:"prepayment"` } -// MarshalJSON implements the json.Marshaler interface for CreatePrepaymentRequest. +// MarshalJSON implements the json.Marshaler interface for CreatePrepaymentRequest. // It customizes the JSON marshaling process for CreatePrepaymentRequest objects. func (c *CreatePrepaymentRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreatePrepaymentRequest object to a map representation for JSON marshaling. func (c *CreatePrepaymentRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["prepayment"] = c.Prepayment.toMap() - return structMap + structMap := make(map[string]any) + structMap["prepayment"] = c.Prepayment.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreatePrepaymentRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreatePrepaymentRequest. // It customizes the JSON unmarshaling process for CreatePrepaymentRequest objects. func (c *CreatePrepaymentRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Prepayment CreatePrepayment `json:"prepayment"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Prepayment = temp.Prepayment - return nil + var temp createPrepaymentRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Prepayment = *temp.Prepayment + return nil +} + +// TODO +type createPrepaymentRequest struct { + Prepayment *CreatePrepayment `json:"prepayment"` +} + +func (c *createPrepaymentRequest) validate() error { + var errs []string + if c.Prepayment == nil { + errs = append(errs, "required field `prepayment` is missing for type `Create Prepayment Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_prepayment_response.go b/models/create_prepayment_response.go index 42e75900..2eff7440 100644 --- a/models/create_prepayment_response.go +++ b/models/create_prepayment_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreatePrepaymentResponse represents a CreatePrepaymentResponse struct. type CreatePrepaymentResponse struct { - Prepayment CreatedPrepayment `json:"prepayment"` + Prepayment CreatedPrepayment `json:"prepayment"` } -// MarshalJSON implements the json.Marshaler interface for CreatePrepaymentResponse. +// MarshalJSON implements the json.Marshaler interface for CreatePrepaymentResponse. // It customizes the JSON marshaling process for CreatePrepaymentResponse objects. func (c *CreatePrepaymentResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreatePrepaymentResponse object to a map representation for JSON marshaling. func (c *CreatePrepaymentResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["prepayment"] = c.Prepayment.toMap() - return structMap + structMap := make(map[string]any) + structMap["prepayment"] = c.Prepayment.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreatePrepaymentResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for CreatePrepaymentResponse. // It customizes the JSON unmarshaling process for CreatePrepaymentResponse objects. func (c *CreatePrepaymentResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Prepayment CreatedPrepayment `json:"prepayment"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Prepayment = temp.Prepayment - return nil + var temp createPrepaymentResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Prepayment = *temp.Prepayment + return nil +} + +// TODO +type createPrepaymentResponse struct { + Prepayment *CreatedPrepayment `json:"prepayment"` +} + +func (c *createPrepaymentResponse) validate() error { + var errs []string + if c.Prepayment == nil { + errs = append(errs, "required field `prepayment` is missing for type `Create Prepayment Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_product_currency_price.go b/models/create_product_currency_price.go index 702ee5d6..cb1b7d81 100644 --- a/models/create_product_currency_price.go +++ b/models/create_product_currency_price.go @@ -1,51 +1,77 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateProductCurrencyPrice represents a CreateProductCurrencyPrice struct. type CreateProductCurrencyPrice struct { - // ISO code for one of the site level currencies. - Currency string `json:"currency"` - // Price for the given role. - Price int `json:"price"` - // Role for the price. - Role CurrencyPriceRole `json:"role"` + // ISO code for one of the site level currencies. + Currency string `json:"currency"` + // Price for the given role. + Price int `json:"price"` + // Role for the price. + Role CurrencyPriceRole `json:"role"` } -// MarshalJSON implements the json.Marshaler interface for CreateProductCurrencyPrice. +// MarshalJSON implements the json.Marshaler interface for CreateProductCurrencyPrice. // It customizes the JSON marshaling process for CreateProductCurrencyPrice objects. func (c *CreateProductCurrencyPrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateProductCurrencyPrice object to a map representation for JSON marshaling. func (c *CreateProductCurrencyPrice) toMap() map[string]any { - structMap := make(map[string]any) - structMap["currency"] = c.Currency - structMap["price"] = c.Price - structMap["role"] = c.Role - return structMap + structMap := make(map[string]any) + structMap["currency"] = c.Currency + structMap["price"] = c.Price + structMap["role"] = c.Role + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductCurrencyPrice. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductCurrencyPrice. // It customizes the JSON unmarshaling process for CreateProductCurrencyPrice objects. func (c *CreateProductCurrencyPrice) UnmarshalJSON(input []byte) error { - temp := &struct { - Currency string `json:"currency"` - Price int `json:"price"` - Role CurrencyPriceRole `json:"role"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Currency = temp.Currency - c.Price = temp.Price - c.Role = temp.Role - return nil + var temp createProductCurrencyPrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Currency = *temp.Currency + c.Price = *temp.Price + c.Role = *temp.Role + return nil +} + +// TODO +type createProductCurrencyPrice struct { + Currency *string `json:"currency"` + Price *int `json:"price"` + Role *CurrencyPriceRole `json:"role"` +} + +func (c *createProductCurrencyPrice) validate() error { + var errs []string + if c.Currency == nil { + errs = append(errs, "required field `currency` is missing for type `Create Product Currency Price`") + } + if c.Price == nil { + errs = append(errs, "required field `price` is missing for type `Create Product Currency Price`") + } + if c.Role == nil { + errs = append(errs, "required field `role` is missing for type `Create Product Currency Price`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_product_currency_prices_request.go b/models/create_product_currency_prices_request.go index b9e9682a..4304b89e 100644 --- a/models/create_product_currency_prices_request.go +++ b/models/create_product_currency_prices_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateProductCurrencyPricesRequest represents a CreateProductCurrencyPricesRequest struct. type CreateProductCurrencyPricesRequest struct { - CurrencyPrices []CreateProductCurrencyPrice `json:"currency_prices"` + CurrencyPrices []CreateProductCurrencyPrice `json:"currency_prices"` } -// MarshalJSON implements the json.Marshaler interface for CreateProductCurrencyPricesRequest. +// MarshalJSON implements the json.Marshaler interface for CreateProductCurrencyPricesRequest. // It customizes the JSON marshaling process for CreateProductCurrencyPricesRequest objects. func (c *CreateProductCurrencyPricesRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateProductCurrencyPricesRequest object to a map representation for JSON marshaling. func (c *CreateProductCurrencyPricesRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["currency_prices"] = c.CurrencyPrices - return structMap + structMap := make(map[string]any) + structMap["currency_prices"] = c.CurrencyPrices + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductCurrencyPricesRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductCurrencyPricesRequest. // It customizes the JSON unmarshaling process for CreateProductCurrencyPricesRequest objects. func (c *CreateProductCurrencyPricesRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - CurrencyPrices []CreateProductCurrencyPrice `json:"currency_prices"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.CurrencyPrices = temp.CurrencyPrices - return nil + var temp createProductCurrencyPricesRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.CurrencyPrices = *temp.CurrencyPrices + return nil +} + +// TODO +type createProductCurrencyPricesRequest struct { + CurrencyPrices *[]CreateProductCurrencyPrice `json:"currency_prices"` +} + +func (c *createProductCurrencyPricesRequest) validate() error { + var errs []string + if c.CurrencyPrices == nil { + errs = append(errs, "required field `currency_prices` is missing for type `Create Product Currency Prices Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_product_family.go b/models/create_product_family.go index 41811d50..4a4b7bbc 100644 --- a/models/create_product_family.go +++ b/models/create_product_family.go @@ -1,48 +1,54 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreateProductFamily represents a CreateProductFamily struct. type CreateProductFamily struct { - Name *string `json:"name,omitempty"` - Description Optional[string] `json:"description"` + Name *string `json:"name,omitempty"` + Description Optional[string] `json:"description"` } -// MarshalJSON implements the json.Marshaler interface for CreateProductFamily. +// MarshalJSON implements the json.Marshaler interface for CreateProductFamily. // It customizes the JSON marshaling process for CreateProductFamily objects. func (c *CreateProductFamily) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateProductFamily object to a map representation for JSON marshaling. func (c *CreateProductFamily) toMap() map[string]any { - structMap := make(map[string]any) - if c.Name != nil { - structMap["name"] = c.Name - } - if c.Description.IsValueSet() { - structMap["description"] = c.Description.Value() - } - return structMap + structMap := make(map[string]any) + if c.Name != nil { + structMap["name"] = c.Name + } + if c.Description.IsValueSet() { + if c.Description.Value() != nil { + structMap["description"] = c.Description.Value() + } else { + structMap["description"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductFamily. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductFamily. // It customizes the JSON unmarshaling process for CreateProductFamily objects. func (c *CreateProductFamily) UnmarshalJSON(input []byte) error { - temp := &struct { - Name *string `json:"name,omitempty"` - Description Optional[string] `json:"description"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Name = temp.Name - c.Description = temp.Description - return nil + var temp createProductFamily + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Name = temp.Name + c.Description = temp.Description + return nil +} + +// TODO +type createProductFamily struct { + Name *string `json:"name,omitempty"` + Description Optional[string] `json:"description"` } diff --git a/models/create_product_family_request.go b/models/create_product_family_request.go index b35e81f1..f474fd83 100644 --- a/models/create_product_family_request.go +++ b/models/create_product_family_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateProductFamilyRequest represents a CreateProductFamilyRequest struct. type CreateProductFamilyRequest struct { - ProductFamily CreateProductFamily `json:"product_family"` + ProductFamily CreateProductFamily `json:"product_family"` } -// MarshalJSON implements the json.Marshaler interface for CreateProductFamilyRequest. +// MarshalJSON implements the json.Marshaler interface for CreateProductFamilyRequest. // It customizes the JSON marshaling process for CreateProductFamilyRequest objects. func (c *CreateProductFamilyRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateProductFamilyRequest object to a map representation for JSON marshaling. func (c *CreateProductFamilyRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["product_family"] = c.ProductFamily.toMap() - return structMap + structMap := make(map[string]any) + structMap["product_family"] = c.ProductFamily.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductFamilyRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductFamilyRequest. // It customizes the JSON unmarshaling process for CreateProductFamilyRequest objects. func (c *CreateProductFamilyRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - ProductFamily CreateProductFamily `json:"product_family"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ProductFamily = temp.ProductFamily - return nil + var temp createProductFamilyRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.ProductFamily = *temp.ProductFamily + return nil +} + +// TODO +type createProductFamilyRequest struct { + ProductFamily *CreateProductFamily `json:"product_family"` +} + +func (c *createProductFamilyRequest) validate() error { + var errs []string + if c.ProductFamily == nil { + errs = append(errs, "required field `product_family` is missing for type `Create Product Family Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_product_price_point.go b/models/create_product_price_point.go index 3e40e72e..2da53d99 100644 --- a/models/create_product_price_point.go +++ b/models/create_product_price_point.go @@ -1,124 +1,153 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateProductPricePoint represents a CreateProductPricePoint struct. type CreateProductPricePoint struct { - // The product price point name - Name string `json:"name"` - // The product price point API handle - Handle *string `json:"handle,omitempty"` - // The product price point price, in integer cents - PriceInCents int64 `json:"price_in_cents"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product price point would renew every 30 days - Interval int `json:"interval"` - // A string representing the interval unit for this product price point, either month or day - IntervalUnit IntervalUnit `json:"interval_unit"` - // The product price point trial price, in integer cents - TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` - // The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product price point trial would last 30 days. - TrialInterval *int `json:"trial_interval,omitempty"` - // A string representing the trial interval unit for this product price point, either month or day - TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` - TrialType *string `json:"trial_type,omitempty"` - // The product price point initial charge, in integer cents - InitialChargeInCents *int64 `json:"initial_charge_in_cents,omitempty"` - InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` - // The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product price point would expire after 30 days. - ExpirationInterval *int `json:"expiration_interval,omitempty"` - // A string representing the expiration interval unit for this product price point, either month or day - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` - // Whether or not to use the site's exchange rate or define your own pricing when your site has multiple currencies defined. - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + // The product price point name + Name string `json:"name"` + // The product price point API handle + Handle *string `json:"handle,omitempty"` + // The product price point price, in integer cents + PriceInCents int64 `json:"price_in_cents"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product price point would renew every 30 days + Interval int `json:"interval"` + // A string representing the interval unit for this product price point, either month or day + IntervalUnit IntervalUnit `json:"interval_unit"` + // The product price point trial price, in integer cents + TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` + // The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product price point trial would last 30 days. + TrialInterval *int `json:"trial_interval,omitempty"` + // A string representing the trial interval unit for this product price point, either month or day + TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` + TrialType *string `json:"trial_type,omitempty"` + // The product price point initial charge, in integer cents + InitialChargeInCents *int64 `json:"initial_charge_in_cents,omitempty"` + InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` + // The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product price point would expire after 30 days. + ExpirationInterval *int `json:"expiration_interval,omitempty"` + // A string representing the expiration interval unit for this product price point, either month or day + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` + // Whether or not to use the site's exchange rate or define your own pricing when your site has multiple currencies defined. + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateProductPricePoint. +// MarshalJSON implements the json.Marshaler interface for CreateProductPricePoint. // It customizes the JSON marshaling process for CreateProductPricePoint objects. func (c *CreateProductPricePoint) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateProductPricePoint object to a map representation for JSON marshaling. func (c *CreateProductPricePoint) toMap() map[string]any { - structMap := make(map[string]any) - structMap["name"] = c.Name - if c.Handle != nil { - structMap["handle"] = c.Handle - } - structMap["price_in_cents"] = c.PriceInCents - structMap["interval"] = c.Interval - structMap["interval_unit"] = c.IntervalUnit - if c.TrialPriceInCents != nil { - structMap["trial_price_in_cents"] = c.TrialPriceInCents - } - if c.TrialInterval != nil { - structMap["trial_interval"] = c.TrialInterval - } - if c.TrialIntervalUnit != nil { - structMap["trial_interval_unit"] = c.TrialIntervalUnit - } - if c.TrialType != nil { - structMap["trial_type"] = c.TrialType - } - if c.InitialChargeInCents != nil { - structMap["initial_charge_in_cents"] = c.InitialChargeInCents - } - if c.InitialChargeAfterTrial != nil { - structMap["initial_charge_after_trial"] = c.InitialChargeAfterTrial - } - if c.ExpirationInterval != nil { - structMap["expiration_interval"] = c.ExpirationInterval - } - if c.ExpirationIntervalUnit != nil { - structMap["expiration_interval_unit"] = c.ExpirationIntervalUnit - } - if c.UseSiteExchangeRate != nil { - structMap["use_site_exchange_rate"] = c.UseSiteExchangeRate - } - return structMap + structMap := make(map[string]any) + structMap["name"] = c.Name + if c.Handle != nil { + structMap["handle"] = c.Handle + } + structMap["price_in_cents"] = c.PriceInCents + structMap["interval"] = c.Interval + structMap["interval_unit"] = c.IntervalUnit + if c.TrialPriceInCents != nil { + structMap["trial_price_in_cents"] = c.TrialPriceInCents + } + if c.TrialInterval != nil { + structMap["trial_interval"] = c.TrialInterval + } + if c.TrialIntervalUnit != nil { + structMap["trial_interval_unit"] = c.TrialIntervalUnit + } + if c.TrialType != nil { + structMap["trial_type"] = c.TrialType + } + if c.InitialChargeInCents != nil { + structMap["initial_charge_in_cents"] = c.InitialChargeInCents + } + if c.InitialChargeAfterTrial != nil { + structMap["initial_charge_after_trial"] = c.InitialChargeAfterTrial + } + if c.ExpirationInterval != nil { + structMap["expiration_interval"] = c.ExpirationInterval + } + if c.ExpirationIntervalUnit != nil { + structMap["expiration_interval_unit"] = c.ExpirationIntervalUnit + } + if c.UseSiteExchangeRate != nil { + structMap["use_site_exchange_rate"] = c.UseSiteExchangeRate + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductPricePoint. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductPricePoint. // It customizes the JSON unmarshaling process for CreateProductPricePoint objects. func (c *CreateProductPricePoint) UnmarshalJSON(input []byte) error { - temp := &struct { - Name string `json:"name"` - Handle *string `json:"handle,omitempty"` - PriceInCents int64 `json:"price_in_cents"` - Interval int `json:"interval"` - IntervalUnit IntervalUnit `json:"interval_unit"` - TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` - TrialInterval *int `json:"trial_interval,omitempty"` - TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` - TrialType *string `json:"trial_type,omitempty"` - InitialChargeInCents *int64 `json:"initial_charge_in_cents,omitempty"` - InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` - ExpirationInterval *int `json:"expiration_interval,omitempty"` - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Name = temp.Name - c.Handle = temp.Handle - c.PriceInCents = temp.PriceInCents - c.Interval = temp.Interval - c.IntervalUnit = temp.IntervalUnit - c.TrialPriceInCents = temp.TrialPriceInCents - c.TrialInterval = temp.TrialInterval - c.TrialIntervalUnit = temp.TrialIntervalUnit - c.TrialType = temp.TrialType - c.InitialChargeInCents = temp.InitialChargeInCents - c.InitialChargeAfterTrial = temp.InitialChargeAfterTrial - c.ExpirationInterval = temp.ExpirationInterval - c.ExpirationIntervalUnit = temp.ExpirationIntervalUnit - c.UseSiteExchangeRate = temp.UseSiteExchangeRate - return nil + var temp createProductPricePoint + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Name = *temp.Name + c.Handle = temp.Handle + c.PriceInCents = *temp.PriceInCents + c.Interval = *temp.Interval + c.IntervalUnit = *temp.IntervalUnit + c.TrialPriceInCents = temp.TrialPriceInCents + c.TrialInterval = temp.TrialInterval + c.TrialIntervalUnit = temp.TrialIntervalUnit + c.TrialType = temp.TrialType + c.InitialChargeInCents = temp.InitialChargeInCents + c.InitialChargeAfterTrial = temp.InitialChargeAfterTrial + c.ExpirationInterval = temp.ExpirationInterval + c.ExpirationIntervalUnit = temp.ExpirationIntervalUnit + c.UseSiteExchangeRate = temp.UseSiteExchangeRate + return nil +} + +// TODO +type createProductPricePoint struct { + Name *string `json:"name"` + Handle *string `json:"handle,omitempty"` + PriceInCents *int64 `json:"price_in_cents"` + Interval *int `json:"interval"` + IntervalUnit *IntervalUnit `json:"interval_unit"` + TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` + TrialInterval *int `json:"trial_interval,omitempty"` + TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` + TrialType *string `json:"trial_type,omitempty"` + InitialChargeInCents *int64 `json:"initial_charge_in_cents,omitempty"` + InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` + ExpirationInterval *int `json:"expiration_interval,omitempty"` + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` +} + +func (c *createProductPricePoint) validate() error { + var errs []string + if c.Name == nil { + errs = append(errs, "required field `name` is missing for type `Create Product Price Point`") + } + if c.PriceInCents == nil { + errs = append(errs, "required field `price_in_cents` is missing for type `Create Product Price Point`") + } + if c.Interval == nil { + errs = append(errs, "required field `interval` is missing for type `Create Product Price Point`") + } + if c.IntervalUnit == nil { + errs = append(errs, "required field `interval_unit` is missing for type `Create Product Price Point`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_product_price_point_product_id.go b/models/create_product_price_point_product_id.go new file mode 100644 index 00000000..7619badc --- /dev/null +++ b/models/create_product_price_point_product_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateProductPricePointProductId represents a CreateProductPricePointProductId struct. +// This is a container for one-of cases. +type CreateProductPricePointProductId struct { + value any + isNumber bool + isString bool +} + +// String converts the CreateProductPricePointProductId object to a string representation. +func (c CreateProductPricePointProductId) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateProductPricePointProductId. +// It customizes the JSON marshaling process for CreateProductPricePointProductId objects. +func (c *CreateProductPricePointProductId) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateProductPricePointProductIdContainer.From*` functions to initialize the CreateProductPricePointProductId object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateProductPricePointProductId object to a map representation for JSON marshaling. +func (c *CreateProductPricePointProductId) toMap() any { + switch obj := c.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductPricePointProductId. +// It customizes the JSON unmarshaling process for CreateProductPricePointProductId objects. +func (c *CreateProductPricePointProductId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(string), false, &c.isString), + ) + + c.value = result + return err +} + +func (c *CreateProductPricePointProductId) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CreateProductPricePointProductId) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +// internalCreateProductPricePointProductId represents a createProductPricePointProductId struct. +// This is a container for one-of cases. +type internalCreateProductPricePointProductId struct{} + +var CreateProductPricePointProductIdContainer internalCreateProductPricePointProductId + +func (c *internalCreateProductPricePointProductId) FromNumber(val int) CreateProductPricePointProductId { + return CreateProductPricePointProductId{value: &val} +} + +func (c *internalCreateProductPricePointProductId) FromString(val string) CreateProductPricePointProductId { + return CreateProductPricePointProductId{value: &val} +} diff --git a/models/create_product_price_point_request.go b/models/create_product_price_point_request.go index 618509d9..305185a6 100644 --- a/models/create_product_price_point_request.go +++ b/models/create_product_price_point_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateProductPricePointRequest represents a CreateProductPricePointRequest struct. type CreateProductPricePointRequest struct { - PricePoint CreateProductPricePoint `json:"price_point"` + PricePoint CreateProductPricePoint `json:"price_point"` } -// MarshalJSON implements the json.Marshaler interface for CreateProductPricePointRequest. +// MarshalJSON implements the json.Marshaler interface for CreateProductPricePointRequest. // It customizes the JSON marshaling process for CreateProductPricePointRequest objects. func (c *CreateProductPricePointRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateProductPricePointRequest object to a map representation for JSON marshaling. func (c *CreateProductPricePointRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["price_point"] = c.PricePoint.toMap() - return structMap + structMap := make(map[string]any) + structMap["price_point"] = c.PricePoint.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductPricePointRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateProductPricePointRequest. // It customizes the JSON unmarshaling process for CreateProductPricePointRequest objects. func (c *CreateProductPricePointRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoint CreateProductPricePoint `json:"price_point"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.PricePoint = temp.PricePoint - return nil + var temp createProductPricePointRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.PricePoint = *temp.PricePoint + return nil +} + +// TODO +type createProductPricePointRequest struct { + PricePoint *CreateProductPricePoint `json:"price_point"` +} + +func (c *createProductPricePointRequest) validate() error { + var errs []string + if c.PricePoint == nil { + errs = append(errs, "required field `price_point` is missing for type `Create Product Price Point Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_quantity_based_component.go b/models/create_quantity_based_component.go index 9c1da459..8a9e218c 100644 --- a/models/create_quantity_based_component.go +++ b/models/create_quantity_based_component.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateQuantityBasedComponent represents a CreateQuantityBasedComponent struct. type CreateQuantityBasedComponent struct { - QuantityBasedComponent QuantityBasedComponent `json:"quantity_based_component"` + QuantityBasedComponent QuantityBasedComponent `json:"quantity_based_component"` } -// MarshalJSON implements the json.Marshaler interface for CreateQuantityBasedComponent. +// MarshalJSON implements the json.Marshaler interface for CreateQuantityBasedComponent. // It customizes the JSON marshaling process for CreateQuantityBasedComponent objects. func (c *CreateQuantityBasedComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateQuantityBasedComponent object to a map representation for JSON marshaling. func (c *CreateQuantityBasedComponent) toMap() map[string]any { - structMap := make(map[string]any) - structMap["quantity_based_component"] = c.QuantityBasedComponent.toMap() - return structMap + structMap := make(map[string]any) + structMap["quantity_based_component"] = c.QuantityBasedComponent.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateQuantityBasedComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateQuantityBasedComponent. // It customizes the JSON unmarshaling process for CreateQuantityBasedComponent objects. func (c *CreateQuantityBasedComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - QuantityBasedComponent QuantityBasedComponent `json:"quantity_based_component"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.QuantityBasedComponent = temp.QuantityBasedComponent - return nil + var temp createQuantityBasedComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.QuantityBasedComponent = *temp.QuantityBasedComponent + return nil +} + +// TODO +type createQuantityBasedComponent struct { + QuantityBasedComponent *QuantityBasedComponent `json:"quantity_based_component"` +} + +func (c *createQuantityBasedComponent) validate() error { + var errs []string + if c.QuantityBasedComponent == nil { + errs = append(errs, "required field `quantity_based_component` is missing for type `Create Quantity Based Component`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_reason_code.go b/models/create_reason_code.go index 78d0b3be..e6682725 100644 --- a/models/create_reason_code.go +++ b/models/create_reason_code.go @@ -1,53 +1,76 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateReasonCode represents a CreateReasonCode struct. type CreateReasonCode struct { - // The unique identifier for the ReasonCode - Code string `json:"code"` - // The friendly summary of what the code signifies - Description string `json:"description"` - // The order that code appears in lists - Position *int `json:"position,omitempty"` + // The unique identifier for the ReasonCode + Code string `json:"code"` + // The friendly summary of what the code signifies + Description string `json:"description"` + // The order that code appears in lists + Position *int `json:"position,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateReasonCode. +// MarshalJSON implements the json.Marshaler interface for CreateReasonCode. // It customizes the JSON marshaling process for CreateReasonCode objects. func (c *CreateReasonCode) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateReasonCode object to a map representation for JSON marshaling. func (c *CreateReasonCode) toMap() map[string]any { - structMap := make(map[string]any) - structMap["code"] = c.Code - structMap["description"] = c.Description - if c.Position != nil { - structMap["position"] = c.Position - } - return structMap + structMap := make(map[string]any) + structMap["code"] = c.Code + structMap["description"] = c.Description + if c.Position != nil { + structMap["position"] = c.Position + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateReasonCode. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateReasonCode. // It customizes the JSON unmarshaling process for CreateReasonCode objects. func (c *CreateReasonCode) UnmarshalJSON(input []byte) error { - temp := &struct { - Code string `json:"code"` - Description string `json:"description"` - Position *int `json:"position,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Code = temp.Code - c.Description = temp.Description - c.Position = temp.Position - return nil + var temp createReasonCode + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Code = *temp.Code + c.Description = *temp.Description + c.Position = temp.Position + return nil +} + +// TODO +type createReasonCode struct { + Code *string `json:"code"` + Description *string `json:"description"` + Position *int `json:"position,omitempty"` +} + +func (c *createReasonCode) validate() error { + var errs []string + if c.Code == nil { + errs = append(errs, "required field `code` is missing for type `Create Reason Code`") + } + if c.Description == nil { + errs = append(errs, "required field `description` is missing for type `Create Reason Code`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_reason_code_request.go b/models/create_reason_code_request.go index 52d4a11f..ed02b3d4 100644 --- a/models/create_reason_code_request.go +++ b/models/create_reason_code_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateReasonCodeRequest represents a CreateReasonCodeRequest struct. type CreateReasonCodeRequest struct { - ReasonCode CreateReasonCode `json:"reason_code"` + ReasonCode CreateReasonCode `json:"reason_code"` } -// MarshalJSON implements the json.Marshaler interface for CreateReasonCodeRequest. +// MarshalJSON implements the json.Marshaler interface for CreateReasonCodeRequest. // It customizes the JSON marshaling process for CreateReasonCodeRequest objects. func (c *CreateReasonCodeRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateReasonCodeRequest object to a map representation for JSON marshaling. func (c *CreateReasonCodeRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["reason_code"] = c.ReasonCode.toMap() - return structMap + structMap := make(map[string]any) + structMap["reason_code"] = c.ReasonCode.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateReasonCodeRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateReasonCodeRequest. // It customizes the JSON unmarshaling process for CreateReasonCodeRequest objects. func (c *CreateReasonCodeRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - ReasonCode CreateReasonCode `json:"reason_code"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ReasonCode = temp.ReasonCode - return nil + var temp createReasonCodeRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.ReasonCode = *temp.ReasonCode + return nil +} + +// TODO +type createReasonCodeRequest struct { + ReasonCode *CreateReasonCode `json:"reason_code"` +} + +func (c *createReasonCodeRequest) validate() error { + var errs []string + if c.ReasonCode == nil { + errs = append(errs, "required field `reason_code` is missing for type `Create Reason Code Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_segment.go b/models/create_segment.go index 8d6eadfa..c073c940 100644 --- a/models/create_segment.go +++ b/models/create_segment.go @@ -1,75 +1,95 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateSegment represents a CreateSegment struct. type CreateSegment struct { - // A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. - SegmentProperty1Value *interface{} `json:"segment_property_1_value,omitempty"` - // A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. - SegmentProperty2Value *interface{} `json:"segment_property_2_value,omitempty"` - // A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. - SegmentProperty3Value *interface{} `json:"segment_property_3_value,omitempty"` - // A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. - SegmentProperty4Value *interface{} `json:"segment_property_4_value,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme PricingScheme `json:"pricing_scheme"` - Prices []CreateOrUpdateSegmentPrice `json:"prices,omitempty"` + // A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. + SegmentProperty1Value *CreateSegmentSegmentProperty1Value `json:"segment_property_1_value,omitempty"` + // A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. + SegmentProperty2Value *CreateSegmentSegmentProperty2Value `json:"segment_property_2_value,omitempty"` + // A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. + SegmentProperty3Value *CreateSegmentSegmentProperty3Value `json:"segment_property_3_value,omitempty"` + // A value that will occur in your events that you want to bill upon. The type of the value depends on the property type in the related event based billing metric. + SegmentProperty4Value *CreateSegmentSegmentProperty4Value `json:"segment_property_4_value,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme PricingScheme `json:"pricing_scheme"` + Prices []CreateOrUpdateSegmentPrice `json:"prices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateSegment. +// MarshalJSON implements the json.Marshaler interface for CreateSegment. // It customizes the JSON marshaling process for CreateSegment objects. func (c *CreateSegment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateSegment object to a map representation for JSON marshaling. func (c *CreateSegment) toMap() map[string]any { - structMap := make(map[string]any) - if c.SegmentProperty1Value != nil { - structMap["segment_property_1_value"] = c.SegmentProperty1Value - } - if c.SegmentProperty2Value != nil { - structMap["segment_property_2_value"] = c.SegmentProperty2Value - } - if c.SegmentProperty3Value != nil { - structMap["segment_property_3_value"] = c.SegmentProperty3Value - } - if c.SegmentProperty4Value != nil { - structMap["segment_property_4_value"] = c.SegmentProperty4Value - } - structMap["pricing_scheme"] = c.PricingScheme - if c.Prices != nil { - structMap["prices"] = c.Prices - } - return structMap + structMap := make(map[string]any) + if c.SegmentProperty1Value != nil { + structMap["segment_property_1_value"] = c.SegmentProperty1Value.toMap() + } + if c.SegmentProperty2Value != nil { + structMap["segment_property_2_value"] = c.SegmentProperty2Value.toMap() + } + if c.SegmentProperty3Value != nil { + structMap["segment_property_3_value"] = c.SegmentProperty3Value.toMap() + } + if c.SegmentProperty4Value != nil { + structMap["segment_property_4_value"] = c.SegmentProperty4Value.toMap() + } + structMap["pricing_scheme"] = c.PricingScheme + if c.Prices != nil { + structMap["prices"] = c.Prices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateSegment. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSegment. // It customizes the JSON unmarshaling process for CreateSegment objects. func (c *CreateSegment) UnmarshalJSON(input []byte) error { - temp := &struct { - SegmentProperty1Value *interface{} `json:"segment_property_1_value,omitempty"` - SegmentProperty2Value *interface{} `json:"segment_property_2_value,omitempty"` - SegmentProperty3Value *interface{} `json:"segment_property_3_value,omitempty"` - SegmentProperty4Value *interface{} `json:"segment_property_4_value,omitempty"` - PricingScheme PricingScheme `json:"pricing_scheme"` - Prices []CreateOrUpdateSegmentPrice `json:"prices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.SegmentProperty1Value = temp.SegmentProperty1Value - c.SegmentProperty2Value = temp.SegmentProperty2Value - c.SegmentProperty3Value = temp.SegmentProperty3Value - c.SegmentProperty4Value = temp.SegmentProperty4Value - c.PricingScheme = temp.PricingScheme - c.Prices = temp.Prices - return nil + var temp createSegment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.SegmentProperty1Value = temp.SegmentProperty1Value + c.SegmentProperty2Value = temp.SegmentProperty2Value + c.SegmentProperty3Value = temp.SegmentProperty3Value + c.SegmentProperty4Value = temp.SegmentProperty4Value + c.PricingScheme = *temp.PricingScheme + c.Prices = temp.Prices + return nil +} + +// TODO +type createSegment struct { + SegmentProperty1Value *CreateSegmentSegmentProperty1Value `json:"segment_property_1_value,omitempty"` + SegmentProperty2Value *CreateSegmentSegmentProperty2Value `json:"segment_property_2_value,omitempty"` + SegmentProperty3Value *CreateSegmentSegmentProperty3Value `json:"segment_property_3_value,omitempty"` + SegmentProperty4Value *CreateSegmentSegmentProperty4Value `json:"segment_property_4_value,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme"` + Prices []CreateOrUpdateSegmentPrice `json:"prices,omitempty"` +} + +func (c *createSegment) validate() error { + var errs []string + if c.PricingScheme == nil { + errs = append(errs, "required field `pricing_scheme` is missing for type `Create Segment`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_segment_request.go b/models/create_segment_request.go index aadeadf4..01139627 100644 --- a/models/create_segment_request.go +++ b/models/create_segment_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateSegmentRequest represents a CreateSegmentRequest struct. type CreateSegmentRequest struct { - Segment CreateSegment `json:"segment"` + Segment CreateSegment `json:"segment"` } -// MarshalJSON implements the json.Marshaler interface for CreateSegmentRequest. +// MarshalJSON implements the json.Marshaler interface for CreateSegmentRequest. // It customizes the JSON marshaling process for CreateSegmentRequest objects. func (c *CreateSegmentRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateSegmentRequest object to a map representation for JSON marshaling. func (c *CreateSegmentRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["segment"] = c.Segment.toMap() - return structMap + structMap := make(map[string]any) + structMap["segment"] = c.Segment.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateSegmentRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSegmentRequest. // It customizes the JSON unmarshaling process for CreateSegmentRequest objects. func (c *CreateSegmentRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Segment CreateSegment `json:"segment"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Segment = temp.Segment - return nil + var temp createSegmentRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Segment = *temp.Segment + return nil +} + +// TODO +type createSegmentRequest struct { + Segment *CreateSegment `json:"segment"` +} + +func (c *createSegmentRequest) validate() error { + var errs []string + if c.Segment == nil { + errs = append(errs, "required field `segment` is missing for type `Create Segment Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_segment_segment_property_1_value.go b/models/create_segment_segment_property_1_value.go new file mode 100644 index 00000000..32eabbd2 --- /dev/null +++ b/models/create_segment_segment_property_1_value.go @@ -0,0 +1,128 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateSegmentSegmentProperty1Value represents a CreateSegmentSegmentProperty1Value struct. +// This is a container for one-of cases. +type CreateSegmentSegmentProperty1Value struct { + value any + isString bool + isPrecision bool + isNumber bool + isBoolean bool +} + +// String converts the CreateSegmentSegmentProperty1Value object to a string representation. +func (c CreateSegmentSegmentProperty1Value) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateSegmentSegmentProperty1Value. +// It customizes the JSON marshaling process for CreateSegmentSegmentProperty1Value objects. +func (c *CreateSegmentSegmentProperty1Value) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateSegmentSegmentProperty1ValueContainer.From*` functions to initialize the CreateSegmentSegmentProperty1Value object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateSegmentSegmentProperty1Value object to a map representation for JSON marshaling. +func (c *CreateSegmentSegmentProperty1Value) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *float64: + return *obj + case *int: + return *obj + case *bool: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSegmentSegmentProperty1Value. +// It customizes the JSON unmarshaling process for CreateSegmentSegmentProperty1Value objects. +func (c *CreateSegmentSegmentProperty1Value) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(float64), false, &c.isPrecision), + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(bool), false, &c.isBoolean), + ) + + c.value = result + return err +} + +func (c *CreateSegmentSegmentProperty1Value) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateSegmentSegmentProperty1Value) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +func (c *CreateSegmentSegmentProperty1Value) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CreateSegmentSegmentProperty1Value) AsBoolean() ( + *bool, + bool) { + if !c.isBoolean { + return nil, false + } + return c.value.(*bool), true +} + +// internalCreateSegmentSegmentProperty1Value represents a createSegmentSegmentProperty1Value struct. +// This is a container for one-of cases. +type internalCreateSegmentSegmentProperty1Value struct{} + +var CreateSegmentSegmentProperty1ValueContainer internalCreateSegmentSegmentProperty1Value + +func (c *internalCreateSegmentSegmentProperty1Value) FromString(val string) CreateSegmentSegmentProperty1Value { + return CreateSegmentSegmentProperty1Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty1Value) FromPrecision(val float64) CreateSegmentSegmentProperty1Value { + return CreateSegmentSegmentProperty1Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty1Value) FromNumber(val int) CreateSegmentSegmentProperty1Value { + return CreateSegmentSegmentProperty1Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty1Value) FromBoolean(val bool) CreateSegmentSegmentProperty1Value { + return CreateSegmentSegmentProperty1Value{value: &val} +} diff --git a/models/create_segment_segment_property_2_value.go b/models/create_segment_segment_property_2_value.go new file mode 100644 index 00000000..33f5e0af --- /dev/null +++ b/models/create_segment_segment_property_2_value.go @@ -0,0 +1,128 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateSegmentSegmentProperty2Value represents a CreateSegmentSegmentProperty2Value struct. +// This is a container for one-of cases. +type CreateSegmentSegmentProperty2Value struct { + value any + isString bool + isPrecision bool + isNumber bool + isBoolean bool +} + +// String converts the CreateSegmentSegmentProperty2Value object to a string representation. +func (c CreateSegmentSegmentProperty2Value) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateSegmentSegmentProperty2Value. +// It customizes the JSON marshaling process for CreateSegmentSegmentProperty2Value objects. +func (c *CreateSegmentSegmentProperty2Value) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateSegmentSegmentProperty2ValueContainer.From*` functions to initialize the CreateSegmentSegmentProperty2Value object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateSegmentSegmentProperty2Value object to a map representation for JSON marshaling. +func (c *CreateSegmentSegmentProperty2Value) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *float64: + return *obj + case *int: + return *obj + case *bool: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSegmentSegmentProperty2Value. +// It customizes the JSON unmarshaling process for CreateSegmentSegmentProperty2Value objects. +func (c *CreateSegmentSegmentProperty2Value) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(float64), false, &c.isPrecision), + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(bool), false, &c.isBoolean), + ) + + c.value = result + return err +} + +func (c *CreateSegmentSegmentProperty2Value) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateSegmentSegmentProperty2Value) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +func (c *CreateSegmentSegmentProperty2Value) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CreateSegmentSegmentProperty2Value) AsBoolean() ( + *bool, + bool) { + if !c.isBoolean { + return nil, false + } + return c.value.(*bool), true +} + +// internalCreateSegmentSegmentProperty2Value represents a createSegmentSegmentProperty2Value struct. +// This is a container for one-of cases. +type internalCreateSegmentSegmentProperty2Value struct{} + +var CreateSegmentSegmentProperty2ValueContainer internalCreateSegmentSegmentProperty2Value + +func (c *internalCreateSegmentSegmentProperty2Value) FromString(val string) CreateSegmentSegmentProperty2Value { + return CreateSegmentSegmentProperty2Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty2Value) FromPrecision(val float64) CreateSegmentSegmentProperty2Value { + return CreateSegmentSegmentProperty2Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty2Value) FromNumber(val int) CreateSegmentSegmentProperty2Value { + return CreateSegmentSegmentProperty2Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty2Value) FromBoolean(val bool) CreateSegmentSegmentProperty2Value { + return CreateSegmentSegmentProperty2Value{value: &val} +} diff --git a/models/create_segment_segment_property_3_value.go b/models/create_segment_segment_property_3_value.go new file mode 100644 index 00000000..c7efceca --- /dev/null +++ b/models/create_segment_segment_property_3_value.go @@ -0,0 +1,128 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateSegmentSegmentProperty3Value represents a CreateSegmentSegmentProperty3Value struct. +// This is a container for one-of cases. +type CreateSegmentSegmentProperty3Value struct { + value any + isString bool + isPrecision bool + isNumber bool + isBoolean bool +} + +// String converts the CreateSegmentSegmentProperty3Value object to a string representation. +func (c CreateSegmentSegmentProperty3Value) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateSegmentSegmentProperty3Value. +// It customizes the JSON marshaling process for CreateSegmentSegmentProperty3Value objects. +func (c *CreateSegmentSegmentProperty3Value) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateSegmentSegmentProperty3ValueContainer.From*` functions to initialize the CreateSegmentSegmentProperty3Value object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateSegmentSegmentProperty3Value object to a map representation for JSON marshaling. +func (c *CreateSegmentSegmentProperty3Value) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *float64: + return *obj + case *int: + return *obj + case *bool: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSegmentSegmentProperty3Value. +// It customizes the JSON unmarshaling process for CreateSegmentSegmentProperty3Value objects. +func (c *CreateSegmentSegmentProperty3Value) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(float64), false, &c.isPrecision), + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(bool), false, &c.isBoolean), + ) + + c.value = result + return err +} + +func (c *CreateSegmentSegmentProperty3Value) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateSegmentSegmentProperty3Value) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +func (c *CreateSegmentSegmentProperty3Value) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CreateSegmentSegmentProperty3Value) AsBoolean() ( + *bool, + bool) { + if !c.isBoolean { + return nil, false + } + return c.value.(*bool), true +} + +// internalCreateSegmentSegmentProperty3Value represents a createSegmentSegmentProperty3Value struct. +// This is a container for one-of cases. +type internalCreateSegmentSegmentProperty3Value struct{} + +var CreateSegmentSegmentProperty3ValueContainer internalCreateSegmentSegmentProperty3Value + +func (c *internalCreateSegmentSegmentProperty3Value) FromString(val string) CreateSegmentSegmentProperty3Value { + return CreateSegmentSegmentProperty3Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty3Value) FromPrecision(val float64) CreateSegmentSegmentProperty3Value { + return CreateSegmentSegmentProperty3Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty3Value) FromNumber(val int) CreateSegmentSegmentProperty3Value { + return CreateSegmentSegmentProperty3Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty3Value) FromBoolean(val bool) CreateSegmentSegmentProperty3Value { + return CreateSegmentSegmentProperty3Value{value: &val} +} diff --git a/models/create_segment_segment_property_4_value.go b/models/create_segment_segment_property_4_value.go new file mode 100644 index 00000000..8124d53b --- /dev/null +++ b/models/create_segment_segment_property_4_value.go @@ -0,0 +1,128 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateSegmentSegmentProperty4Value represents a CreateSegmentSegmentProperty4Value struct. +// This is a container for one-of cases. +type CreateSegmentSegmentProperty4Value struct { + value any + isString bool + isPrecision bool + isNumber bool + isBoolean bool +} + +// String converts the CreateSegmentSegmentProperty4Value object to a string representation. +func (c CreateSegmentSegmentProperty4Value) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateSegmentSegmentProperty4Value. +// It customizes the JSON marshaling process for CreateSegmentSegmentProperty4Value objects. +func (c *CreateSegmentSegmentProperty4Value) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateSegmentSegmentProperty4ValueContainer.From*` functions to initialize the CreateSegmentSegmentProperty4Value object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateSegmentSegmentProperty4Value object to a map representation for JSON marshaling. +func (c *CreateSegmentSegmentProperty4Value) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *float64: + return *obj + case *int: + return *obj + case *bool: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSegmentSegmentProperty4Value. +// It customizes the JSON unmarshaling process for CreateSegmentSegmentProperty4Value objects. +func (c *CreateSegmentSegmentProperty4Value) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(float64), false, &c.isPrecision), + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(bool), false, &c.isBoolean), + ) + + c.value = result + return err +} + +func (c *CreateSegmentSegmentProperty4Value) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateSegmentSegmentProperty4Value) AsPrecision() ( + *float64, + bool) { + if !c.isPrecision { + return nil, false + } + return c.value.(*float64), true +} + +func (c *CreateSegmentSegmentProperty4Value) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CreateSegmentSegmentProperty4Value) AsBoolean() ( + *bool, + bool) { + if !c.isBoolean { + return nil, false + } + return c.value.(*bool), true +} + +// internalCreateSegmentSegmentProperty4Value represents a createSegmentSegmentProperty4Value struct. +// This is a container for one-of cases. +type internalCreateSegmentSegmentProperty4Value struct{} + +var CreateSegmentSegmentProperty4ValueContainer internalCreateSegmentSegmentProperty4Value + +func (c *internalCreateSegmentSegmentProperty4Value) FromString(val string) CreateSegmentSegmentProperty4Value { + return CreateSegmentSegmentProperty4Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty4Value) FromPrecision(val float64) CreateSegmentSegmentProperty4Value { + return CreateSegmentSegmentProperty4Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty4Value) FromNumber(val int) CreateSegmentSegmentProperty4Value { + return CreateSegmentSegmentProperty4Value{value: &val} +} + +func (c *internalCreateSegmentSegmentProperty4Value) FromBoolean(val bool) CreateSegmentSegmentProperty4Value { + return CreateSegmentSegmentProperty4Value{value: &val} +} diff --git a/models/create_subscription.go b/models/create_subscription.go index 010caedf..490aca32 100644 --- a/models/create_subscription.go +++ b/models/create_subscription.go @@ -1,410 +1,420 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // CreateSubscription represents a CreateSubscription struct. type CreateSubscription struct { - // The API Handle of the product for which you are creating a subscription. Required, unless a `product_id` is given instead. - ProductHandle *string `json:"product_handle,omitempty"` - // The Product ID of the product for which you are creating a subscription. The product ID is not currently published, so we recommend using the API Handle instead. - ProductId *int `json:"product_id,omitempty"` - // The user-friendly API handle of a product's particular price point. - ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` - // The ID of the particular price point on the product. - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - // (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription - CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` - // (deprecated) The coupon code of the single coupon currently applied to the subscription. See coupon_codes instead as subscriptions can now have more than one coupon. - CouponCode *string `json:"coupon_code,omitempty"` - // An array for all the coupons attached to the subscription. - CouponCodes []string `json:"coupon_codes,omitempty"` - // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. - PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` - // (Optional) Default: True - Whether or not this subscription is set to receive emails related to this subscription. - ReceivesInvoiceEmails *string `json:"receives_invoice_emails,omitempty"` - // (Optional) Default: null The number of days after renewal (on invoice billing) that a subscription is due. A value between 0 (due immediately) and 180. - NetTerms *string `json:"net_terms,omitempty"` - // The ID of an existing customer within Chargify. Required, unless a `customer_reference` or a set of `customer_attributes` is given. - CustomerId *int `json:"customer_id,omitempty"` - // (Optional) Set this attribute to a future date/time to sync imported subscriptions to your existing renewal schedule. See the notes on “Date/Time Format” in our [subscription import documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#date-format). If you provide a next_billing_at timestamp that is in the future, no trial or initial charges will be applied when you create the subscription. In fact, no payment will be captured at all. The first payment will be captured, according to the prices defined by the product, near the time specified by next_billing_at. If you do not provide a value for next_billing_at, any trial and/or initial charges will be assessed and charged at the time of subscription creation. If the card cannot be successfully charged, the subscription will not be created. See further notes in the section on Importing Subscriptions. - NextBillingAt *time.Time `json:"next_billing_at,omitempty"` - // (Optional) Set this attribute to a future date/time to create a subscription in the "Awaiting Signup" state, rather than "Active" or "Trialing". See the notes on “Date/Time Format” in our [subscription import documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#date-format). In the "Awaiting Signup" state, a subscription behaves like any other. It can be canceled, allocated to, had its billing date changed. etc. When the initial_billing_at date hits, the subscription will transition to the expected state. If the product has a trial, the subscription will enter a trial, otherwise it will go active. Setup fees will be respected either before or after the trial, as configured on the price point. If the payment is due at the initial_billing_at and it fails the subscription will be immediately canceled. See further notes in the section on Delayed Signups. - InitialBillingAt *time.Time `json:"initial_billing_at,omitempty"` - // For European sites subject to PSD2 and using 3D Secure, this can be used to reference a previous transaction for the customer. This will ensure the card will be charged successfully at renewal. - StoredCredentialTransactionId *int `json:"stored_credential_transaction_id,omitempty"` - SalesRepId *int `json:"sales_rep_id,omitempty"` - // The Payment Profile ID of an existing card or bank account, which belongs to an existing customer to use for payment for this subscription. If the card, bank account, or customer does not exist already, or if you want to use a new (unstored) card or bank account for the subscription, use `payment_profile_attributes` instead to create a new payment profile along with the subscription. (This value is available on an existing subscription via the API as `credit_card` > id or `bank_account` > id) - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - // The reference value (provided by your app) for the subscription itelf. - Reference *string `json:"reference,omitempty"` - CustomerAttributes *CustomerAttributes `json:"customer_attributes,omitempty"` - // alias to credit_card_attributes - PaymentProfileAttributes *PaymentProfileAttributes `json:"payment_profile_attributes,omitempty"` - // Credit Card data to create a new Subscription. Interchangeable with `payment_profile_attributes` property. - CreditCardAttributes *PaymentProfileAttributes `json:"credit_card_attributes,omitempty"` - BankAccountAttributes *BankAccountAttributes `json:"bank_account_attributes,omitempty"` - // (Optional) An array of component ids and quantities to be added to the subscription. See [Components](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677) for more information. - Components []CreateSubscriptionComponent `json:"components,omitempty"` - // (Optional). Cannot be used when also specifying next_billing_at - CalendarBilling *CalendarBilling `json:"calendar_billing,omitempty"` - // (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. - Metafields map[string]string `json:"metafields,omitempty"` - // The reference value (provided by your app) of an existing customer within Chargify. Required, unless a `customer_id` or a set of `customer_attributes` is given. - CustomerReference *string `json:"customer_reference,omitempty"` - Group *GroupSettings `json:"group,omitempty"` - // A valid referral code. (optional, see [Referrals](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405420204045-Referrals-Reference#how-to-obtain-referral-codes) for more details). If supplied, must be valid, or else subscription creation will fail. - Ref *string `json:"ref,omitempty"` - // (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to make a note about the reason for cancellation. - CancellationMessage *string `json:"cancellation_message,omitempty"` - // (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to make a note about how the subscription was canceled. - CancellationMethod *string `json:"cancellation_method,omitempty"` - // (Optional) If Multi-Currency is enabled and the currency is configured in Chargify, pass it at signup to create a subscription on a non-default currency. Note that you cannot update the currency of an existing subscription. - Currency *string `json:"currency,omitempty"` - // Timestamp giving the expiration date of this subscription (if any). You may manually change the expiration date at any point during a subscription period. - ExpiresAt *time.Time `json:"expires_at,omitempty"` - // (Optional, default false) When set to true, and when next_billing_at is present, if the subscription expires, the expires_at will be shifted by the same amount of time as the difference between the old and new “next billing” dates. - ExpirationTracksNextBillingChange *string `json:"expiration_tracks_next_billing_change,omitempty"` - // (Optional) The ACH authorization agreement terms. If enabled, an email will be sent to the customer with a copy of the terms. - AgreementTerms *string `json:"agreement_terms,omitempty"` - // (Optional) The first name of the person authorizing the ACH agreement. - AuthorizerFirstName *string `json:"authorizer_first_name,omitempty"` - // (Optional) The last name of the person authorizing the ACH agreement. - AuthorizerLastName *string `json:"authorizer_last_name,omitempty"` - // (Optional) One of “prorated” (the default – the prorated product price will be charged immediately), “immediate” (the full product price will be charged immediately), or “delayed” (the full product price will be charged with the first scheduled renewal). - CalendarBillingFirstCharge *string `json:"calendar_billing_first_charge,omitempty"` - // (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to indicate why a subscription was canceled. - ReasonCode *string `json:"reason_code,omitempty"` - // (Optional, used only for Delayed Product Change When set to true, indicates that a changed value for product_handle should schedule the product change to the next subscription renewal. - ProductChangeDelayed *bool `json:"product_change_delayed,omitempty"` - // Use in place of passing product and component information to set up the subscription with an existing offer. May be either the Chargify id of the offer or its handle prefixed with `handle:`.er - OfferId *interface{} `json:"offer_id,omitempty"` - PrepaidConfiguration *UpsertPrepaidConfiguration `json:"prepaid_configuration,omitempty"` - // Providing a previous_billing_at that is in the past will set the current_period_starts_at when the subscription is created. It will also set activated_at if not explicitly passed during the subscription import. Can only be used if next_billing_at is also passed. Using this option will allow you to set the period start for the subscription so mid period component allocations have the correct prorated amount. - PreviousBillingAt *time.Time `json:"previous_billing_at,omitempty"` - // Setting this attribute to true will cause the subscription's MRR to be added to your MRR analytics immediately. For this value to be honored, a next_billing_at must be present and set to a future date. This key/value will not be returned in the subscription response body. - ImportMrr *bool `json:"import_mrr,omitempty"` - CanceledAt *time.Time `json:"canceled_at,omitempty"` - ActivatedAt *time.Time `json:"activated_at,omitempty"` - // Required when creating a subscription with Maxio Payments. - AgreementAcceptance *AgreementAcceptance `json:"agreement_acceptance,omitempty"` - // (Optional) If passed, the proof of the authorized ACH agreement terms will be persisted. - AchAgreement *ACHAgreement `json:"ach_agreement,omitempty"` - // Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute. - DunningCommunicationDelayEnabled Optional[bool] `json:"dunning_communication_delay_enabled"` - // Time zone for the Dunning Communication Delay feature. - DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` - // Valid only for the Subscription Preview endpoint. When set to `true` it skips calculating taxes for the current and next billing manifests. - SkipBillingManifestTaxes *bool `json:"skip_billing_manifest_taxes,omitempty"` + // The API Handle of the product for which you are creating a subscription. Required, unless a `product_id` is given instead. + ProductHandle *string `json:"product_handle,omitempty"` + // The Product ID of the product for which you are creating a subscription. The product ID is not currently published, so we recommend using the API Handle instead. + ProductId *int `json:"product_id,omitempty"` + // The user-friendly API handle of a product's particular price point. + ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` + // The ID of the particular price point on the product. + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + // (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription + CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` + // (deprecated) The coupon code of the single coupon currently applied to the subscription. See coupon_codes instead as subscriptions can now have more than one coupon. + CouponCode *string `json:"coupon_code,omitempty"` + // An array for all the coupons attached to the subscription. + CouponCodes []string `json:"coupon_codes,omitempty"` + // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` + // (Optional) Default: True - Whether or not this subscription is set to receive emails related to this subscription. + ReceivesInvoiceEmails *string `json:"receives_invoice_emails,omitempty"` + // (Optional) Default: null The number of days after renewal (on invoice billing) that a subscription is due. A value between 0 (due immediately) and 180. + NetTerms *string `json:"net_terms,omitempty"` + // The ID of an existing customer within Chargify. Required, unless a `customer_reference` or a set of `customer_attributes` is given. + CustomerId *int `json:"customer_id,omitempty"` + // (Optional) Set this attribute to a future date/time to sync imported subscriptions to your existing renewal schedule. See the notes on “Date/Time Format” in our [subscription import documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#date-format). If you provide a next_billing_at timestamp that is in the future, no trial or initial charges will be applied when you create the subscription. In fact, no payment will be captured at all. The first payment will be captured, according to the prices defined by the product, near the time specified by next_billing_at. If you do not provide a value for next_billing_at, any trial and/or initial charges will be assessed and charged at the time of subscription creation. If the card cannot be successfully charged, the subscription will not be created. See further notes in the section on Importing Subscriptions. + NextBillingAt *time.Time `json:"next_billing_at,omitempty"` + // (Optional) Set this attribute to a future date/time to create a subscription in the "Awaiting Signup" state, rather than "Active" or "Trialing". See the notes on “Date/Time Format” in our [subscription import documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#date-format). In the "Awaiting Signup" state, a subscription behaves like any other. It can be canceled, allocated to, had its billing date changed. etc. When the initial_billing_at date hits, the subscription will transition to the expected state. If the product has a trial, the subscription will enter a trial, otherwise it will go active. Setup fees will be respected either before or after the trial, as configured on the price point. If the payment is due at the initial_billing_at and it fails the subscription will be immediately canceled. See further notes in the section on Delayed Signups. + InitialBillingAt *time.Time `json:"initial_billing_at,omitempty"` + // For European sites subject to PSD2 and using 3D Secure, this can be used to reference a previous transaction for the customer. This will ensure the card will be charged successfully at renewal. + StoredCredentialTransactionId *int `json:"stored_credential_transaction_id,omitempty"` + SalesRepId *int `json:"sales_rep_id,omitempty"` + // The Payment Profile ID of an existing card or bank account, which belongs to an existing customer to use for payment for this subscription. If the card, bank account, or customer does not exist already, or if you want to use a new (unstored) card or bank account for the subscription, use `payment_profile_attributes` instead to create a new payment profile along with the subscription. (This value is available on an existing subscription via the API as `credit_card` > id or `bank_account` > id) + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + // The reference value (provided by your app) for the subscription itelf. + Reference *string `json:"reference,omitempty"` + CustomerAttributes *CustomerAttributes `json:"customer_attributes,omitempty"` + // alias to credit_card_attributes + PaymentProfileAttributes *PaymentProfileAttributes `json:"payment_profile_attributes,omitempty"` + // Credit Card data to create a new Subscription. Interchangeable with `payment_profile_attributes` property. + CreditCardAttributes *PaymentProfileAttributes `json:"credit_card_attributes,omitempty"` + BankAccountAttributes *BankAccountAttributes `json:"bank_account_attributes,omitempty"` + // (Optional) An array of component ids and quantities to be added to the subscription. See [Components](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677) for more information. + Components []CreateSubscriptionComponent `json:"components,omitempty"` + // (Optional). Cannot be used when also specifying next_billing_at + CalendarBilling *CalendarBilling `json:"calendar_billing,omitempty"` + // (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. + Metafields map[string]string `json:"metafields,omitempty"` + // The reference value (provided by your app) of an existing customer within Chargify. Required, unless a `customer_id` or a set of `customer_attributes` is given. + CustomerReference *string `json:"customer_reference,omitempty"` + Group *GroupSettings `json:"group,omitempty"` + // A valid referral code. (optional, see [Referrals](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405420204045-Referrals-Reference#how-to-obtain-referral-codes) for more details). If supplied, must be valid, or else subscription creation will fail. + Ref *string `json:"ref,omitempty"` + // (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to make a note about the reason for cancellation. + CancellationMessage *string `json:"cancellation_message,omitempty"` + // (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to make a note about how the subscription was canceled. + CancellationMethod *string `json:"cancellation_method,omitempty"` + // (Optional) If Multi-Currency is enabled and the currency is configured in Chargify, pass it at signup to create a subscription on a non-default currency. Note that you cannot update the currency of an existing subscription. + Currency *string `json:"currency,omitempty"` + // Timestamp giving the expiration date of this subscription (if any). You may manually change the expiration date at any point during a subscription period. + ExpiresAt *time.Time `json:"expires_at,omitempty"` + // (Optional, default false) When set to true, and when next_billing_at is present, if the subscription expires, the expires_at will be shifted by the same amount of time as the difference between the old and new “next billing” dates. + ExpirationTracksNextBillingChange *string `json:"expiration_tracks_next_billing_change,omitempty"` + // (Optional) The ACH authorization agreement terms. If enabled, an email will be sent to the customer with a copy of the terms. + AgreementTerms *string `json:"agreement_terms,omitempty"` + // (Optional) The first name of the person authorizing the ACH agreement. + AuthorizerFirstName *string `json:"authorizer_first_name,omitempty"` + // (Optional) The last name of the person authorizing the ACH agreement. + AuthorizerLastName *string `json:"authorizer_last_name,omitempty"` + // (Optional) One of “prorated” (the default – the prorated product price will be charged immediately), “immediate” (the full product price will be charged immediately), or “delayed” (the full product price will be charged with the first scheduled renewal). + CalendarBillingFirstCharge *string `json:"calendar_billing_first_charge,omitempty"` + // (Optional) Can be used when canceling a subscription (via the HTTP DELETE method) to indicate why a subscription was canceled. + ReasonCode *string `json:"reason_code,omitempty"` + // (Optional, used only for Delayed Product Change When set to true, indicates that a changed value for product_handle should schedule the product change to the next subscription renewal. + ProductChangeDelayed *bool `json:"product_change_delayed,omitempty"` + // Use in place of passing product and component information to set up the subscription with an existing offer. May be either the Chargify id of the offer or its handle prefixed with `handle:`.er + OfferId *CreateSubscriptionOfferId `json:"offer_id,omitempty"` + PrepaidConfiguration *UpsertPrepaidConfiguration `json:"prepaid_configuration,omitempty"` + // Providing a previous_billing_at that is in the past will set the current_period_starts_at when the subscription is created. It will also set activated_at if not explicitly passed during the subscription import. Can only be used if next_billing_at is also passed. Using this option will allow you to set the period start for the subscription so mid period component allocations have the correct prorated amount. + PreviousBillingAt *time.Time `json:"previous_billing_at,omitempty"` + // Setting this attribute to true will cause the subscription's MRR to be added to your MRR analytics immediately. For this value to be honored, a next_billing_at must be present and set to a future date. This key/value will not be returned in the subscription response body. + ImportMrr *bool `json:"import_mrr,omitempty"` + CanceledAt *time.Time `json:"canceled_at,omitempty"` + ActivatedAt *time.Time `json:"activated_at,omitempty"` + // Required when creating a subscription with Maxio Payments. + AgreementAcceptance *AgreementAcceptance `json:"agreement_acceptance,omitempty"` + // (Optional) If passed, the proof of the authorized ACH agreement terms will be persisted. + AchAgreement *ACHAgreement `json:"ach_agreement,omitempty"` + // Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute. + DunningCommunicationDelayEnabled Optional[bool] `json:"dunning_communication_delay_enabled"` + // Time zone for the Dunning Communication Delay feature. + DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` + // Valid only for the Subscription Preview endpoint. When set to `true` it skips calculating taxes for the current and next billing manifests. + SkipBillingManifestTaxes *bool `json:"skip_billing_manifest_taxes,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateSubscription. +// MarshalJSON implements the json.Marshaler interface for CreateSubscription. // It customizes the JSON marshaling process for CreateSubscription objects. func (c *CreateSubscription) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateSubscription object to a map representation for JSON marshaling. func (c *CreateSubscription) toMap() map[string]any { - structMap := make(map[string]any) - if c.ProductHandle != nil { - structMap["product_handle"] = c.ProductHandle - } - if c.ProductId != nil { - structMap["product_id"] = c.ProductId - } - if c.ProductPricePointHandle != nil { - structMap["product_price_point_handle"] = c.ProductPricePointHandle - } - if c.ProductPricePointId != nil { - structMap["product_price_point_id"] = c.ProductPricePointId - } - if c.CustomPrice != nil { - structMap["custom_price"] = c.CustomPrice.toMap() - } - if c.CouponCode != nil { - structMap["coupon_code"] = c.CouponCode - } - if c.CouponCodes != nil { - structMap["coupon_codes"] = c.CouponCodes - } - if c.PaymentCollectionMethod != nil { - structMap["payment_collection_method"] = c.PaymentCollectionMethod - } - if c.ReceivesInvoiceEmails != nil { - structMap["receives_invoice_emails"] = c.ReceivesInvoiceEmails - } - if c.NetTerms != nil { - structMap["net_terms"] = c.NetTerms - } - if c.CustomerId != nil { - structMap["customer_id"] = c.CustomerId - } - if c.NextBillingAt != nil { - structMap["next_billing_at"] = c.NextBillingAt.Format(time.RFC3339) - } - if c.InitialBillingAt != nil { - structMap["initial_billing_at"] = c.InitialBillingAt.Format(time.RFC3339) - } - if c.StoredCredentialTransactionId != nil { - structMap["stored_credential_transaction_id"] = c.StoredCredentialTransactionId - } - if c.SalesRepId != nil { - structMap["sales_rep_id"] = c.SalesRepId - } - if c.PaymentProfileId != nil { - structMap["payment_profile_id"] = c.PaymentProfileId - } - if c.Reference != nil { - structMap["reference"] = c.Reference - } - if c.CustomerAttributes != nil { - structMap["customer_attributes"] = c.CustomerAttributes.toMap() - } - if c.PaymentProfileAttributes != nil { - structMap["payment_profile_attributes"] = c.PaymentProfileAttributes.toMap() - } - if c.CreditCardAttributes != nil { - structMap["credit_card_attributes"] = c.CreditCardAttributes.toMap() - } - if c.BankAccountAttributes != nil { - structMap["bank_account_attributes"] = c.BankAccountAttributes.toMap() - } - if c.Components != nil { - structMap["components"] = c.Components - } - if c.CalendarBilling != nil { - structMap["calendar_billing"] = c.CalendarBilling.toMap() - } - if c.Metafields != nil { - structMap["metafields"] = c.Metafields - } - if c.CustomerReference != nil { - structMap["customer_reference"] = c.CustomerReference - } - if c.Group != nil { - structMap["group"] = c.Group.toMap() - } - if c.Ref != nil { - structMap["ref"] = c.Ref - } - if c.CancellationMessage != nil { - structMap["cancellation_message"] = c.CancellationMessage - } - if c.CancellationMethod != nil { - structMap["cancellation_method"] = c.CancellationMethod - } - if c.Currency != nil { - structMap["currency"] = c.Currency - } - if c.ExpiresAt != nil { - structMap["expires_at"] = c.ExpiresAt.Format(time.RFC3339) - } - if c.ExpirationTracksNextBillingChange != nil { - structMap["expiration_tracks_next_billing_change"] = c.ExpirationTracksNextBillingChange - } - if c.AgreementTerms != nil { - structMap["agreement_terms"] = c.AgreementTerms - } - if c.AuthorizerFirstName != nil { - structMap["authorizer_first_name"] = c.AuthorizerFirstName - } - if c.AuthorizerLastName != nil { - structMap["authorizer_last_name"] = c.AuthorizerLastName - } - if c.CalendarBillingFirstCharge != nil { - structMap["calendar_billing_first_charge"] = c.CalendarBillingFirstCharge - } - if c.ReasonCode != nil { - structMap["reason_code"] = c.ReasonCode - } - if c.ProductChangeDelayed != nil { - structMap["product_change_delayed"] = c.ProductChangeDelayed - } - if c.OfferId != nil { - structMap["offer_id"] = c.OfferId - } - if c.PrepaidConfiguration != nil { - structMap["prepaid_configuration"] = c.PrepaidConfiguration.toMap() - } - if c.PreviousBillingAt != nil { - structMap["previous_billing_at"] = c.PreviousBillingAt.Format(time.RFC3339) - } - if c.ImportMrr != nil { - structMap["import_mrr"] = c.ImportMrr - } - if c.CanceledAt != nil { - structMap["canceled_at"] = c.CanceledAt.Format(time.RFC3339) - } - if c.ActivatedAt != nil { - structMap["activated_at"] = c.ActivatedAt.Format(time.RFC3339) - } - if c.AgreementAcceptance != nil { - structMap["agreement_acceptance"] = c.AgreementAcceptance.toMap() - } - if c.AchAgreement != nil { - structMap["ach_agreement"] = c.AchAgreement.toMap() - } - if c.DunningCommunicationDelayEnabled.IsValueSet() { - structMap["dunning_communication_delay_enabled"] = c.DunningCommunicationDelayEnabled.Value() - } - if c.DunningCommunicationDelayTimeZone.IsValueSet() { - structMap["dunning_communication_delay_time_zone"] = c.DunningCommunicationDelayTimeZone.Value() - } - if c.SkipBillingManifestTaxes != nil { - structMap["skip_billing_manifest_taxes"] = c.SkipBillingManifestTaxes - } - return structMap + structMap := make(map[string]any) + if c.ProductHandle != nil { + structMap["product_handle"] = c.ProductHandle + } + if c.ProductId != nil { + structMap["product_id"] = c.ProductId + } + if c.ProductPricePointHandle != nil { + structMap["product_price_point_handle"] = c.ProductPricePointHandle + } + if c.ProductPricePointId != nil { + structMap["product_price_point_id"] = c.ProductPricePointId + } + if c.CustomPrice != nil { + structMap["custom_price"] = c.CustomPrice.toMap() + } + if c.CouponCode != nil { + structMap["coupon_code"] = c.CouponCode + } + if c.CouponCodes != nil { + structMap["coupon_codes"] = c.CouponCodes + } + if c.PaymentCollectionMethod != nil { + structMap["payment_collection_method"] = c.PaymentCollectionMethod + } + if c.ReceivesInvoiceEmails != nil { + structMap["receives_invoice_emails"] = c.ReceivesInvoiceEmails + } + if c.NetTerms != nil { + structMap["net_terms"] = c.NetTerms + } + if c.CustomerId != nil { + structMap["customer_id"] = c.CustomerId + } + if c.NextBillingAt != nil { + structMap["next_billing_at"] = c.NextBillingAt.Format(time.RFC3339) + } + if c.InitialBillingAt != nil { + structMap["initial_billing_at"] = c.InitialBillingAt.Format(time.RFC3339) + } + if c.StoredCredentialTransactionId != nil { + structMap["stored_credential_transaction_id"] = c.StoredCredentialTransactionId + } + if c.SalesRepId != nil { + structMap["sales_rep_id"] = c.SalesRepId + } + if c.PaymentProfileId != nil { + structMap["payment_profile_id"] = c.PaymentProfileId + } + if c.Reference != nil { + structMap["reference"] = c.Reference + } + if c.CustomerAttributes != nil { + structMap["customer_attributes"] = c.CustomerAttributes.toMap() + } + if c.PaymentProfileAttributes != nil { + structMap["payment_profile_attributes"] = c.PaymentProfileAttributes.toMap() + } + if c.CreditCardAttributes != nil { + structMap["credit_card_attributes"] = c.CreditCardAttributes.toMap() + } + if c.BankAccountAttributes != nil { + structMap["bank_account_attributes"] = c.BankAccountAttributes.toMap() + } + if c.Components != nil { + structMap["components"] = c.Components + } + if c.CalendarBilling != nil { + structMap["calendar_billing"] = c.CalendarBilling.toMap() + } + if c.Metafields != nil { + structMap["metafields"] = c.Metafields + } + if c.CustomerReference != nil { + structMap["customer_reference"] = c.CustomerReference + } + if c.Group != nil { + structMap["group"] = c.Group.toMap() + } + if c.Ref != nil { + structMap["ref"] = c.Ref + } + if c.CancellationMessage != nil { + structMap["cancellation_message"] = c.CancellationMessage + } + if c.CancellationMethod != nil { + structMap["cancellation_method"] = c.CancellationMethod + } + if c.Currency != nil { + structMap["currency"] = c.Currency + } + if c.ExpiresAt != nil { + structMap["expires_at"] = c.ExpiresAt.Format(time.RFC3339) + } + if c.ExpirationTracksNextBillingChange != nil { + structMap["expiration_tracks_next_billing_change"] = c.ExpirationTracksNextBillingChange + } + if c.AgreementTerms != nil { + structMap["agreement_terms"] = c.AgreementTerms + } + if c.AuthorizerFirstName != nil { + structMap["authorizer_first_name"] = c.AuthorizerFirstName + } + if c.AuthorizerLastName != nil { + structMap["authorizer_last_name"] = c.AuthorizerLastName + } + if c.CalendarBillingFirstCharge != nil { + structMap["calendar_billing_first_charge"] = c.CalendarBillingFirstCharge + } + if c.ReasonCode != nil { + structMap["reason_code"] = c.ReasonCode + } + if c.ProductChangeDelayed != nil { + structMap["product_change_delayed"] = c.ProductChangeDelayed + } + if c.OfferId != nil { + structMap["offer_id"] = c.OfferId.toMap() + } + if c.PrepaidConfiguration != nil { + structMap["prepaid_configuration"] = c.PrepaidConfiguration.toMap() + } + if c.PreviousBillingAt != nil { + structMap["previous_billing_at"] = c.PreviousBillingAt.Format(time.RFC3339) + } + if c.ImportMrr != nil { + structMap["import_mrr"] = c.ImportMrr + } + if c.CanceledAt != nil { + structMap["canceled_at"] = c.CanceledAt.Format(time.RFC3339) + } + if c.ActivatedAt != nil { + structMap["activated_at"] = c.ActivatedAt.Format(time.RFC3339) + } + if c.AgreementAcceptance != nil { + structMap["agreement_acceptance"] = c.AgreementAcceptance.toMap() + } + if c.AchAgreement != nil { + structMap["ach_agreement"] = c.AchAgreement.toMap() + } + if c.DunningCommunicationDelayEnabled.IsValueSet() { + if c.DunningCommunicationDelayEnabled.Value() != nil { + structMap["dunning_communication_delay_enabled"] = c.DunningCommunicationDelayEnabled.Value() + } else { + structMap["dunning_communication_delay_enabled"] = nil + } + } + if c.DunningCommunicationDelayTimeZone.IsValueSet() { + if c.DunningCommunicationDelayTimeZone.Value() != nil { + structMap["dunning_communication_delay_time_zone"] = c.DunningCommunicationDelayTimeZone.Value() + } else { + structMap["dunning_communication_delay_time_zone"] = nil + } + } + if c.SkipBillingManifestTaxes != nil { + structMap["skip_billing_manifest_taxes"] = c.SkipBillingManifestTaxes + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscription. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscription. // It customizes the JSON unmarshaling process for CreateSubscription objects. func (c *CreateSubscription) UnmarshalJSON(input []byte) error { - temp := &struct { - ProductHandle *string `json:"product_handle,omitempty"` - ProductId *int `json:"product_id,omitempty"` - ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` - CouponCode *string `json:"coupon_code,omitempty"` - CouponCodes []string `json:"coupon_codes,omitempty"` - PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` - ReceivesInvoiceEmails *string `json:"receives_invoice_emails,omitempty"` - NetTerms *string `json:"net_terms,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - NextBillingAt *string `json:"next_billing_at,omitempty"` - InitialBillingAt *string `json:"initial_billing_at,omitempty"` - StoredCredentialTransactionId *int `json:"stored_credential_transaction_id,omitempty"` - SalesRepId *int `json:"sales_rep_id,omitempty"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - Reference *string `json:"reference,omitempty"` - CustomerAttributes *CustomerAttributes `json:"customer_attributes,omitempty"` - PaymentProfileAttributes *PaymentProfileAttributes `json:"payment_profile_attributes,omitempty"` - CreditCardAttributes *PaymentProfileAttributes `json:"credit_card_attributes,omitempty"` - BankAccountAttributes *BankAccountAttributes `json:"bank_account_attributes,omitempty"` - Components []CreateSubscriptionComponent `json:"components,omitempty"` - CalendarBilling *CalendarBilling `json:"calendar_billing,omitempty"` - Metafields map[string]string `json:"metafields,omitempty"` - CustomerReference *string `json:"customer_reference,omitempty"` - Group *GroupSettings `json:"group,omitempty"` - Ref *string `json:"ref,omitempty"` - CancellationMessage *string `json:"cancellation_message,omitempty"` - CancellationMethod *string `json:"cancellation_method,omitempty"` - Currency *string `json:"currency,omitempty"` - ExpiresAt *string `json:"expires_at,omitempty"` - ExpirationTracksNextBillingChange *string `json:"expiration_tracks_next_billing_change,omitempty"` - AgreementTerms *string `json:"agreement_terms,omitempty"` - AuthorizerFirstName *string `json:"authorizer_first_name,omitempty"` - AuthorizerLastName *string `json:"authorizer_last_name,omitempty"` - CalendarBillingFirstCharge *string `json:"calendar_billing_first_charge,omitempty"` - ReasonCode *string `json:"reason_code,omitempty"` - ProductChangeDelayed *bool `json:"product_change_delayed,omitempty"` - OfferId *interface{} `json:"offer_id,omitempty"` - PrepaidConfiguration *UpsertPrepaidConfiguration `json:"prepaid_configuration,omitempty"` - PreviousBillingAt *string `json:"previous_billing_at,omitempty"` - ImportMrr *bool `json:"import_mrr,omitempty"` - CanceledAt *string `json:"canceled_at,omitempty"` - ActivatedAt *string `json:"activated_at,omitempty"` - AgreementAcceptance *AgreementAcceptance `json:"agreement_acceptance,omitempty"` - AchAgreement *ACHAgreement `json:"ach_agreement,omitempty"` - DunningCommunicationDelayEnabled Optional[bool] `json:"dunning_communication_delay_enabled"` - DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` - SkipBillingManifestTaxes *bool `json:"skip_billing_manifest_taxes,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ProductHandle = temp.ProductHandle - c.ProductId = temp.ProductId - c.ProductPricePointHandle = temp.ProductPricePointHandle - c.ProductPricePointId = temp.ProductPricePointId - c.CustomPrice = temp.CustomPrice - c.CouponCode = temp.CouponCode - c.CouponCodes = temp.CouponCodes - c.PaymentCollectionMethod = temp.PaymentCollectionMethod - c.ReceivesInvoiceEmails = temp.ReceivesInvoiceEmails - c.NetTerms = temp.NetTerms - c.CustomerId = temp.CustomerId - if temp.NextBillingAt != nil { - NextBillingAtVal, err := time.Parse(time.RFC3339, *temp.NextBillingAt) - if err != nil { - log.Fatalf("Cannot Parse next_billing_at as % s format.", time.RFC3339) - } - c.NextBillingAt = &NextBillingAtVal - } - if temp.InitialBillingAt != nil { - InitialBillingAtVal, err := time.Parse(time.RFC3339, *temp.InitialBillingAt) - if err != nil { - log.Fatalf("Cannot Parse initial_billing_at as % s format.", time.RFC3339) - } - c.InitialBillingAt = &InitialBillingAtVal - } - c.StoredCredentialTransactionId = temp.StoredCredentialTransactionId - c.SalesRepId = temp.SalesRepId - c.PaymentProfileId = temp.PaymentProfileId - c.Reference = temp.Reference - c.CustomerAttributes = temp.CustomerAttributes - c.PaymentProfileAttributes = temp.PaymentProfileAttributes - c.CreditCardAttributes = temp.CreditCardAttributes - c.BankAccountAttributes = temp.BankAccountAttributes - c.Components = temp.Components - c.CalendarBilling = temp.CalendarBilling - c.Metafields = temp.Metafields - c.CustomerReference = temp.CustomerReference - c.Group = temp.Group - c.Ref = temp.Ref - c.CancellationMessage = temp.CancellationMessage - c.CancellationMethod = temp.CancellationMethod - c.Currency = temp.Currency - if temp.ExpiresAt != nil { - ExpiresAtVal, err := time.Parse(time.RFC3339, *temp.ExpiresAt) - if err != nil { - log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) - } - c.ExpiresAt = &ExpiresAtVal - } - c.ExpirationTracksNextBillingChange = temp.ExpirationTracksNextBillingChange - c.AgreementTerms = temp.AgreementTerms - c.AuthorizerFirstName = temp.AuthorizerFirstName - c.AuthorizerLastName = temp.AuthorizerLastName - c.CalendarBillingFirstCharge = temp.CalendarBillingFirstCharge - c.ReasonCode = temp.ReasonCode - c.ProductChangeDelayed = temp.ProductChangeDelayed - c.OfferId = temp.OfferId - c.PrepaidConfiguration = temp.PrepaidConfiguration - if temp.PreviousBillingAt != nil { - PreviousBillingAtVal, err := time.Parse(time.RFC3339, *temp.PreviousBillingAt) - if err != nil { - log.Fatalf("Cannot Parse previous_billing_at as % s format.", time.RFC3339) - } - c.PreviousBillingAt = &PreviousBillingAtVal - } - c.ImportMrr = temp.ImportMrr - if temp.CanceledAt != nil { - CanceledAtVal, err := time.Parse(time.RFC3339, *temp.CanceledAt) - if err != nil { - log.Fatalf("Cannot Parse canceled_at as % s format.", time.RFC3339) - } - c.CanceledAt = &CanceledAtVal - } - if temp.ActivatedAt != nil { - ActivatedAtVal, err := time.Parse(time.RFC3339, *temp.ActivatedAt) - if err != nil { - log.Fatalf("Cannot Parse activated_at as % s format.", time.RFC3339) - } - c.ActivatedAt = &ActivatedAtVal - } - c.AgreementAcceptance = temp.AgreementAcceptance - c.AchAgreement = temp.AchAgreement - c.DunningCommunicationDelayEnabled = temp.DunningCommunicationDelayEnabled - c.DunningCommunicationDelayTimeZone = temp.DunningCommunicationDelayTimeZone - c.SkipBillingManifestTaxes = temp.SkipBillingManifestTaxes - return nil + var temp createSubscription + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.ProductHandle = temp.ProductHandle + c.ProductId = temp.ProductId + c.ProductPricePointHandle = temp.ProductPricePointHandle + c.ProductPricePointId = temp.ProductPricePointId + c.CustomPrice = temp.CustomPrice + c.CouponCode = temp.CouponCode + c.CouponCodes = temp.CouponCodes + c.PaymentCollectionMethod = temp.PaymentCollectionMethod + c.ReceivesInvoiceEmails = temp.ReceivesInvoiceEmails + c.NetTerms = temp.NetTerms + c.CustomerId = temp.CustomerId + if temp.NextBillingAt != nil { + NextBillingAtVal, err := time.Parse(time.RFC3339, *temp.NextBillingAt) + if err != nil { + log.Fatalf("Cannot Parse next_billing_at as % s format.", time.RFC3339) + } + c.NextBillingAt = &NextBillingAtVal + } + if temp.InitialBillingAt != nil { + InitialBillingAtVal, err := time.Parse(time.RFC3339, *temp.InitialBillingAt) + if err != nil { + log.Fatalf("Cannot Parse initial_billing_at as % s format.", time.RFC3339) + } + c.InitialBillingAt = &InitialBillingAtVal + } + c.StoredCredentialTransactionId = temp.StoredCredentialTransactionId + c.SalesRepId = temp.SalesRepId + c.PaymentProfileId = temp.PaymentProfileId + c.Reference = temp.Reference + c.CustomerAttributes = temp.CustomerAttributes + c.PaymentProfileAttributes = temp.PaymentProfileAttributes + c.CreditCardAttributes = temp.CreditCardAttributes + c.BankAccountAttributes = temp.BankAccountAttributes + c.Components = temp.Components + c.CalendarBilling = temp.CalendarBilling + c.Metafields = temp.Metafields + c.CustomerReference = temp.CustomerReference + c.Group = temp.Group + c.Ref = temp.Ref + c.CancellationMessage = temp.CancellationMessage + c.CancellationMethod = temp.CancellationMethod + c.Currency = temp.Currency + if temp.ExpiresAt != nil { + ExpiresAtVal, err := time.Parse(time.RFC3339, *temp.ExpiresAt) + if err != nil { + log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) + } + c.ExpiresAt = &ExpiresAtVal + } + c.ExpirationTracksNextBillingChange = temp.ExpirationTracksNextBillingChange + c.AgreementTerms = temp.AgreementTerms + c.AuthorizerFirstName = temp.AuthorizerFirstName + c.AuthorizerLastName = temp.AuthorizerLastName + c.CalendarBillingFirstCharge = temp.CalendarBillingFirstCharge + c.ReasonCode = temp.ReasonCode + c.ProductChangeDelayed = temp.ProductChangeDelayed + c.OfferId = temp.OfferId + c.PrepaidConfiguration = temp.PrepaidConfiguration + if temp.PreviousBillingAt != nil { + PreviousBillingAtVal, err := time.Parse(time.RFC3339, *temp.PreviousBillingAt) + if err != nil { + log.Fatalf("Cannot Parse previous_billing_at as % s format.", time.RFC3339) + } + c.PreviousBillingAt = &PreviousBillingAtVal + } + c.ImportMrr = temp.ImportMrr + if temp.CanceledAt != nil { + CanceledAtVal, err := time.Parse(time.RFC3339, *temp.CanceledAt) + if err != nil { + log.Fatalf("Cannot Parse canceled_at as % s format.", time.RFC3339) + } + c.CanceledAt = &CanceledAtVal + } + if temp.ActivatedAt != nil { + ActivatedAtVal, err := time.Parse(time.RFC3339, *temp.ActivatedAt) + if err != nil { + log.Fatalf("Cannot Parse activated_at as % s format.", time.RFC3339) + } + c.ActivatedAt = &ActivatedAtVal + } + c.AgreementAcceptance = temp.AgreementAcceptance + c.AchAgreement = temp.AchAgreement + c.DunningCommunicationDelayEnabled = temp.DunningCommunicationDelayEnabled + c.DunningCommunicationDelayTimeZone = temp.DunningCommunicationDelayTimeZone + c.SkipBillingManifestTaxes = temp.SkipBillingManifestTaxes + return nil +} + +// TODO +type createSubscription struct { + ProductHandle *string `json:"product_handle,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` + CouponCode *string `json:"coupon_code,omitempty"` + CouponCodes []string `json:"coupon_codes,omitempty"` + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` + ReceivesInvoiceEmails *string `json:"receives_invoice_emails,omitempty"` + NetTerms *string `json:"net_terms,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + NextBillingAt *string `json:"next_billing_at,omitempty"` + InitialBillingAt *string `json:"initial_billing_at,omitempty"` + StoredCredentialTransactionId *int `json:"stored_credential_transaction_id,omitempty"` + SalesRepId *int `json:"sales_rep_id,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + Reference *string `json:"reference,omitempty"` + CustomerAttributes *CustomerAttributes `json:"customer_attributes,omitempty"` + PaymentProfileAttributes *PaymentProfileAttributes `json:"payment_profile_attributes,omitempty"` + CreditCardAttributes *PaymentProfileAttributes `json:"credit_card_attributes,omitempty"` + BankAccountAttributes *BankAccountAttributes `json:"bank_account_attributes,omitempty"` + Components []CreateSubscriptionComponent `json:"components,omitempty"` + CalendarBilling *CalendarBilling `json:"calendar_billing,omitempty"` + Metafields map[string]string `json:"metafields,omitempty"` + CustomerReference *string `json:"customer_reference,omitempty"` + Group *GroupSettings `json:"group,omitempty"` + Ref *string `json:"ref,omitempty"` + CancellationMessage *string `json:"cancellation_message,omitempty"` + CancellationMethod *string `json:"cancellation_method,omitempty"` + Currency *string `json:"currency,omitempty"` + ExpiresAt *string `json:"expires_at,omitempty"` + ExpirationTracksNextBillingChange *string `json:"expiration_tracks_next_billing_change,omitempty"` + AgreementTerms *string `json:"agreement_terms,omitempty"` + AuthorizerFirstName *string `json:"authorizer_first_name,omitempty"` + AuthorizerLastName *string `json:"authorizer_last_name,omitempty"` + CalendarBillingFirstCharge *string `json:"calendar_billing_first_charge,omitempty"` + ReasonCode *string `json:"reason_code,omitempty"` + ProductChangeDelayed *bool `json:"product_change_delayed,omitempty"` + OfferId *CreateSubscriptionOfferId `json:"offer_id,omitempty"` + PrepaidConfiguration *UpsertPrepaidConfiguration `json:"prepaid_configuration,omitempty"` + PreviousBillingAt *string `json:"previous_billing_at,omitempty"` + ImportMrr *bool `json:"import_mrr,omitempty"` + CanceledAt *string `json:"canceled_at,omitempty"` + ActivatedAt *string `json:"activated_at,omitempty"` + AgreementAcceptance *AgreementAcceptance `json:"agreement_acceptance,omitempty"` + AchAgreement *ACHAgreement `json:"ach_agreement,omitempty"` + DunningCommunicationDelayEnabled Optional[bool] `json:"dunning_communication_delay_enabled"` + DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` + SkipBillingManifestTaxes *bool `json:"skip_billing_manifest_taxes,omitempty"` } diff --git a/models/create_subscription_component.go b/models/create_subscription_component.go index 689a1628..9b342ecd 100644 --- a/models/create_subscription_component.go +++ b/models/create_subscription_component.go @@ -1,83 +1,85 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreateSubscriptionComponent represents a CreateSubscriptionComponent struct. type CreateSubscriptionComponent struct { - ComponentId *interface{} `json:"component_id,omitempty"` - // Used for on/off components only. - Enabled *bool `json:"enabled,omitempty"` - // Used for metered and events based components. - UnitBalance *int `json:"unit_balance,omitempty"` - // Used for quantity based components. - AllocatedQuantity *interface{} `json:"allocated_quantity,omitempty"` - // Deprecated. Use `allocated_quantity` instead. - Quantity *int `json:"quantity,omitempty"` // Deprecated - PricePointId *interface{} `json:"price_point_id,omitempty"` - // Create or update custom pricing unique to the subscription. Used in place of `price_point_id`. - CustomPrice *ComponentCustomPrice `json:"custom_price,omitempty"` + ComponentId *CreateSubscriptionComponentComponentId `json:"component_id,omitempty"` + // Used for on/off components only. + Enabled *bool `json:"enabled,omitempty"` + // Used for metered and events based components. + UnitBalance *int `json:"unit_balance,omitempty"` + // Used for quantity based components. + AllocatedQuantity *CreateSubscriptionComponentAllocatedQuantity `json:"allocated_quantity,omitempty"` + // Deprecated. Use `allocated_quantity` instead. + Quantity *int `json:"quantity,omitempty"` // Deprecated + PricePointId *CreateSubscriptionComponentPricePointId `json:"price_point_id,omitempty"` + // Create or update custom pricing unique to the subscription. Used in place of `price_point_id`. + CustomPrice *ComponentCustomPrice `json:"custom_price,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionComponent. +// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionComponent. // It customizes the JSON marshaling process for CreateSubscriptionComponent objects. func (c *CreateSubscriptionComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateSubscriptionComponent object to a map representation for JSON marshaling. func (c *CreateSubscriptionComponent) toMap() map[string]any { - structMap := make(map[string]any) - if c.ComponentId != nil { - structMap["component_id"] = c.ComponentId - } - if c.Enabled != nil { - structMap["enabled"] = c.Enabled - } - if c.UnitBalance != nil { - structMap["unit_balance"] = c.UnitBalance - } - if c.AllocatedQuantity != nil { - structMap["allocated_quantity"] = c.AllocatedQuantity - } - if c.Quantity != nil { - structMap["quantity"] = c.Quantity - } - if c.PricePointId != nil { - structMap["price_point_id"] = c.PricePointId - } - if c.CustomPrice != nil { - structMap["custom_price"] = c.CustomPrice.toMap() - } - return structMap + structMap := make(map[string]any) + if c.ComponentId != nil { + structMap["component_id"] = c.ComponentId.toMap() + } + if c.Enabled != nil { + structMap["enabled"] = c.Enabled + } + if c.UnitBalance != nil { + structMap["unit_balance"] = c.UnitBalance + } + if c.AllocatedQuantity != nil { + structMap["allocated_quantity"] = c.AllocatedQuantity.toMap() + } + if c.Quantity != nil { + structMap["quantity"] = c.Quantity + } + if c.PricePointId != nil { + structMap["price_point_id"] = c.PricePointId.toMap() + } + if c.CustomPrice != nil { + structMap["custom_price"] = c.CustomPrice.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionComponent. // It customizes the JSON unmarshaling process for CreateSubscriptionComponent objects. func (c *CreateSubscriptionComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - ComponentId *interface{} `json:"component_id,omitempty"` - Enabled *bool `json:"enabled,omitempty"` - UnitBalance *int `json:"unit_balance,omitempty"` - AllocatedQuantity *interface{} `json:"allocated_quantity,omitempty"` - Quantity *int `json:"quantity,omitempty"` - PricePointId *interface{} `json:"price_point_id,omitempty"` - CustomPrice *ComponentCustomPrice `json:"custom_price,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ComponentId = temp.ComponentId - c.Enabled = temp.Enabled - c.UnitBalance = temp.UnitBalance - c.AllocatedQuantity = temp.AllocatedQuantity - c.Quantity = temp.Quantity - c.PricePointId = temp.PricePointId - c.CustomPrice = temp.CustomPrice - return nil + var temp createSubscriptionComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.ComponentId = temp.ComponentId + c.Enabled = temp.Enabled + c.UnitBalance = temp.UnitBalance + c.AllocatedQuantity = temp.AllocatedQuantity + c.Quantity = temp.Quantity + c.PricePointId = temp.PricePointId + c.CustomPrice = temp.CustomPrice + return nil +} + +// TODO +type createSubscriptionComponent struct { + ComponentId *CreateSubscriptionComponentComponentId `json:"component_id,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + UnitBalance *int `json:"unit_balance,omitempty"` + AllocatedQuantity *CreateSubscriptionComponentAllocatedQuantity `json:"allocated_quantity,omitempty"` + Quantity *int `json:"quantity,omitempty"` + PricePointId *CreateSubscriptionComponentPricePointId `json:"price_point_id,omitempty"` + CustomPrice *ComponentCustomPrice `json:"custom_price,omitempty"` } diff --git a/models/create_subscription_component_allocated_quantity.go b/models/create_subscription_component_allocated_quantity.go new file mode 100644 index 00000000..860f6950 --- /dev/null +++ b/models/create_subscription_component_allocated_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateSubscriptionComponentAllocatedQuantity represents a CreateSubscriptionComponentAllocatedQuantity struct. +// This is a container for one-of cases. +type CreateSubscriptionComponentAllocatedQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the CreateSubscriptionComponentAllocatedQuantity object to a string representation. +func (c CreateSubscriptionComponentAllocatedQuantity) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionComponentAllocatedQuantity. +// It customizes the JSON marshaling process for CreateSubscriptionComponentAllocatedQuantity objects. +func (c *CreateSubscriptionComponentAllocatedQuantity) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateSubscriptionComponentAllocatedQuantityContainer.From*` functions to initialize the CreateSubscriptionComponentAllocatedQuantity object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateSubscriptionComponentAllocatedQuantity object to a map representation for JSON marshaling. +func (c *CreateSubscriptionComponentAllocatedQuantity) toMap() any { + switch obj := c.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionComponentAllocatedQuantity. +// It customizes the JSON unmarshaling process for CreateSubscriptionComponentAllocatedQuantity objects. +func (c *CreateSubscriptionComponentAllocatedQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(string), false, &c.isString), + ) + + c.value = result + return err +} + +func (c *CreateSubscriptionComponentAllocatedQuantity) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CreateSubscriptionComponentAllocatedQuantity) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +// internalCreateSubscriptionComponentAllocatedQuantity represents a createSubscriptionComponentAllocatedQuantity struct. +// This is a container for one-of cases. +type internalCreateSubscriptionComponentAllocatedQuantity struct{} + +var CreateSubscriptionComponentAllocatedQuantityContainer internalCreateSubscriptionComponentAllocatedQuantity + +func (c *internalCreateSubscriptionComponentAllocatedQuantity) FromNumber(val int) CreateSubscriptionComponentAllocatedQuantity { + return CreateSubscriptionComponentAllocatedQuantity{value: &val} +} + +func (c *internalCreateSubscriptionComponentAllocatedQuantity) FromString(val string) CreateSubscriptionComponentAllocatedQuantity { + return CreateSubscriptionComponentAllocatedQuantity{value: &val} +} diff --git a/models/create_subscription_component_component_id.go b/models/create_subscription_component_component_id.go new file mode 100644 index 00000000..270a7270 --- /dev/null +++ b/models/create_subscription_component_component_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateSubscriptionComponentComponentId represents a CreateSubscriptionComponentComponentId struct. +// This is a container for one-of cases. +type CreateSubscriptionComponentComponentId struct { + value any + isNumber bool + isString bool +} + +// String converts the CreateSubscriptionComponentComponentId object to a string representation. +func (c CreateSubscriptionComponentComponentId) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionComponentComponentId. +// It customizes the JSON marshaling process for CreateSubscriptionComponentComponentId objects. +func (c *CreateSubscriptionComponentComponentId) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateSubscriptionComponentComponentIdContainer.From*` functions to initialize the CreateSubscriptionComponentComponentId object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateSubscriptionComponentComponentId object to a map representation for JSON marshaling. +func (c *CreateSubscriptionComponentComponentId) toMap() any { + switch obj := c.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionComponentComponentId. +// It customizes the JSON unmarshaling process for CreateSubscriptionComponentComponentId objects. +func (c *CreateSubscriptionComponentComponentId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(string), false, &c.isString), + ) + + c.value = result + return err +} + +func (c *CreateSubscriptionComponentComponentId) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CreateSubscriptionComponentComponentId) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +// internalCreateSubscriptionComponentComponentId represents a createSubscriptionComponentComponentId struct. +// This is a container for one-of cases. +type internalCreateSubscriptionComponentComponentId struct{} + +var CreateSubscriptionComponentComponentIdContainer internalCreateSubscriptionComponentComponentId + +func (c *internalCreateSubscriptionComponentComponentId) FromNumber(val int) CreateSubscriptionComponentComponentId { + return CreateSubscriptionComponentComponentId{value: &val} +} + +func (c *internalCreateSubscriptionComponentComponentId) FromString(val string) CreateSubscriptionComponentComponentId { + return CreateSubscriptionComponentComponentId{value: &val} +} diff --git a/models/create_subscription_component_price_point_id.go b/models/create_subscription_component_price_point_id.go new file mode 100644 index 00000000..ca45be43 --- /dev/null +++ b/models/create_subscription_component_price_point_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateSubscriptionComponentPricePointId represents a CreateSubscriptionComponentPricePointId struct. +// This is a container for one-of cases. +type CreateSubscriptionComponentPricePointId struct { + value any + isNumber bool + isString bool +} + +// String converts the CreateSubscriptionComponentPricePointId object to a string representation. +func (c CreateSubscriptionComponentPricePointId) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionComponentPricePointId. +// It customizes the JSON marshaling process for CreateSubscriptionComponentPricePointId objects. +func (c *CreateSubscriptionComponentPricePointId) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateSubscriptionComponentPricePointIdContainer.From*` functions to initialize the CreateSubscriptionComponentPricePointId object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateSubscriptionComponentPricePointId object to a map representation for JSON marshaling. +func (c *CreateSubscriptionComponentPricePointId) toMap() any { + switch obj := c.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionComponentPricePointId. +// It customizes the JSON unmarshaling process for CreateSubscriptionComponentPricePointId objects. +func (c *CreateSubscriptionComponentPricePointId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(string), false, &c.isString), + ) + + c.value = result + return err +} + +func (c *CreateSubscriptionComponentPricePointId) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CreateSubscriptionComponentPricePointId) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +// internalCreateSubscriptionComponentPricePointId represents a createSubscriptionComponentPricePointId struct. +// This is a container for one-of cases. +type internalCreateSubscriptionComponentPricePointId struct{} + +var CreateSubscriptionComponentPricePointIdContainer internalCreateSubscriptionComponentPricePointId + +func (c *internalCreateSubscriptionComponentPricePointId) FromNumber(val int) CreateSubscriptionComponentPricePointId { + return CreateSubscriptionComponentPricePointId{value: &val} +} + +func (c *internalCreateSubscriptionComponentPricePointId) FromString(val string) CreateSubscriptionComponentPricePointId { + return CreateSubscriptionComponentPricePointId{value: &val} +} diff --git a/models/create_subscription_group.go b/models/create_subscription_group.go index f7e11662..23ad46ed 100644 --- a/models/create_subscription_group.go +++ b/models/create_subscription_group.go @@ -1,46 +1,66 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateSubscriptionGroup represents a CreateSubscriptionGroup struct. type CreateSubscriptionGroup struct { - SubscriptionId interface{} `json:"subscription_id"` - MemberIds []int `json:"member_ids,omitempty"` + SubscriptionId int `json:"subscription_id"` + MemberIds []int `json:"member_ids,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionGroup. +// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionGroup. // It customizes the JSON marshaling process for CreateSubscriptionGroup objects. func (c *CreateSubscriptionGroup) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateSubscriptionGroup object to a map representation for JSON marshaling. func (c *CreateSubscriptionGroup) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscription_id"] = c.SubscriptionId - if c.MemberIds != nil { - structMap["member_ids"] = c.MemberIds - } - return structMap + structMap := make(map[string]any) + structMap["subscription_id"] = c.SubscriptionId + if c.MemberIds != nil { + structMap["member_ids"] = c.MemberIds + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionGroup. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionGroup. // It customizes the JSON unmarshaling process for CreateSubscriptionGroup objects. func (c *CreateSubscriptionGroup) UnmarshalJSON(input []byte) error { - temp := &struct { - SubscriptionId interface{} `json:"subscription_id"` - MemberIds []int `json:"member_ids,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.SubscriptionId = temp.SubscriptionId - c.MemberIds = temp.MemberIds - return nil + var temp createSubscriptionGroup + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.SubscriptionId = *temp.SubscriptionId + c.MemberIds = temp.MemberIds + return nil +} + +// TODO +type createSubscriptionGroup struct { + SubscriptionId *int `json:"subscription_id"` + MemberIds []int `json:"member_ids,omitempty"` +} + +func (c *createSubscriptionGroup) validate() error { + var errs []string + if c.SubscriptionId == nil { + errs = append(errs, "required field `subscription_id` is missing for type `Create Subscription Group`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_subscription_group_request.go b/models/create_subscription_group_request.go index 373b93fc..0293c4af 100644 --- a/models/create_subscription_group_request.go +++ b/models/create_subscription_group_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateSubscriptionGroupRequest represents a CreateSubscriptionGroupRequest struct. type CreateSubscriptionGroupRequest struct { - SubscriptionGroup CreateSubscriptionGroup `json:"subscription_group"` + SubscriptionGroup CreateSubscriptionGroup `json:"subscription_group"` } -// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionGroupRequest. +// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionGroupRequest. // It customizes the JSON marshaling process for CreateSubscriptionGroupRequest objects. func (c *CreateSubscriptionGroupRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateSubscriptionGroupRequest object to a map representation for JSON marshaling. func (c *CreateSubscriptionGroupRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscription_group"] = c.SubscriptionGroup.toMap() - return structMap + structMap := make(map[string]any) + structMap["subscription_group"] = c.SubscriptionGroup.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionGroupRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionGroupRequest. // It customizes the JSON unmarshaling process for CreateSubscriptionGroupRequest objects. func (c *CreateSubscriptionGroupRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - SubscriptionGroup CreateSubscriptionGroup `json:"subscription_group"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.SubscriptionGroup = temp.SubscriptionGroup - return nil + var temp createSubscriptionGroupRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.SubscriptionGroup = *temp.SubscriptionGroup + return nil +} + +// TODO +type createSubscriptionGroupRequest struct { + SubscriptionGroup *CreateSubscriptionGroup `json:"subscription_group"` +} + +func (c *createSubscriptionGroupRequest) validate() error { + var errs []string + if c.SubscriptionGroup == nil { + errs = append(errs, "required field `subscription_group` is missing for type `Create Subscription Group Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_subscription_offer_id.go b/models/create_subscription_offer_id.go new file mode 100644 index 00000000..d66ea3f9 --- /dev/null +++ b/models/create_subscription_offer_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateSubscriptionOfferId represents a CreateSubscriptionOfferId struct. +// This is a container for one-of cases. +type CreateSubscriptionOfferId struct { + value any + isString bool + isNumber bool +} + +// String converts the CreateSubscriptionOfferId object to a string representation. +func (c CreateSubscriptionOfferId) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionOfferId. +// It customizes the JSON marshaling process for CreateSubscriptionOfferId objects. +func (c *CreateSubscriptionOfferId) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateSubscriptionOfferIdContainer.From*` functions to initialize the CreateSubscriptionOfferId object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateSubscriptionOfferId object to a map representation for JSON marshaling. +func (c *CreateSubscriptionOfferId) toMap() any { + switch obj := c.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionOfferId. +// It customizes the JSON unmarshaling process for CreateSubscriptionOfferId objects. +func (c *CreateSubscriptionOfferId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &c.isString), + NewTypeHolder(new(int), false, &c.isNumber), + ) + + c.value = result + return err +} + +func (c *CreateSubscriptionOfferId) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +func (c *CreateSubscriptionOfferId) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +// internalCreateSubscriptionOfferId represents a createSubscriptionOfferId struct. +// This is a container for one-of cases. +type internalCreateSubscriptionOfferId struct{} + +var CreateSubscriptionOfferIdContainer internalCreateSubscriptionOfferId + +func (c *internalCreateSubscriptionOfferId) FromString(val string) CreateSubscriptionOfferId { + return CreateSubscriptionOfferId{value: &val} +} + +func (c *internalCreateSubscriptionOfferId) FromNumber(val int) CreateSubscriptionOfferId { + return CreateSubscriptionOfferId{value: &val} +} diff --git a/models/create_subscription_request.go b/models/create_subscription_request.go index 3dc42c7c..59f454b6 100644 --- a/models/create_subscription_request.go +++ b/models/create_subscription_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateSubscriptionRequest represents a CreateSubscriptionRequest struct. type CreateSubscriptionRequest struct { - Subscription CreateSubscription `json:"subscription"` + Subscription CreateSubscription `json:"subscription"` } -// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionRequest. +// MarshalJSON implements the json.Marshaler interface for CreateSubscriptionRequest. // It customizes the JSON marshaling process for CreateSubscriptionRequest objects. func (c *CreateSubscriptionRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateSubscriptionRequest object to a map representation for JSON marshaling. func (c *CreateSubscriptionRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscription"] = c.Subscription.toMap() - return structMap + structMap := make(map[string]any) + structMap["subscription"] = c.Subscription.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateSubscriptionRequest. // It customizes the JSON unmarshaling process for CreateSubscriptionRequest objects. func (c *CreateSubscriptionRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Subscription CreateSubscription `json:"subscription"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Subscription = temp.Subscription - return nil + var temp createSubscriptionRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Subscription = *temp.Subscription + return nil +} + +// TODO +type createSubscriptionRequest struct { + Subscription *CreateSubscription `json:"subscription"` +} + +func (c *createSubscriptionRequest) validate() error { + var errs []string + if c.Subscription == nil { + errs = append(errs, "required field `subscription` is missing for type `Create Subscription Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/create_usage.go b/models/create_usage.go index 3dc11922..6d44d55b 100644 --- a/models/create_usage.go +++ b/models/create_usage.go @@ -1,62 +1,64 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreateUsage represents a CreateUsage struct. type CreateUsage struct { - // integer by default or decimal number if fractional quantities are enabled for the component - Quantity *float64 `json:"quantity,omitempty"` - PricePointId *string `json:"price_point_id,omitempty"` - Memo *string `json:"memo,omitempty"` - // This attribute is particularly useful when you need to align billing events for different components on distinct schedules within a subscription. Please note this only works for site with Multifrequency enabled - BillingSchedule *BillingSchedule `json:"billing_schedule,omitempty"` + // integer by default or decimal number if fractional quantities are enabled for the component + Quantity *float64 `json:"quantity,omitempty"` + PricePointId *string `json:"price_point_id,omitempty"` + Memo *string `json:"memo,omitempty"` + // This attribute is particularly useful when you need to align billing events for different components on distinct schedules within a subscription. Please note this only works for site with Multifrequency enabled + BillingSchedule *BillingSchedule `json:"billing_schedule,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreateUsage. +// MarshalJSON implements the json.Marshaler interface for CreateUsage. // It customizes the JSON marshaling process for CreateUsage objects. func (c *CreateUsage) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateUsage object to a map representation for JSON marshaling. func (c *CreateUsage) toMap() map[string]any { - structMap := make(map[string]any) - if c.Quantity != nil { - structMap["quantity"] = c.Quantity - } - if c.PricePointId != nil { - structMap["price_point_id"] = c.PricePointId - } - if c.Memo != nil { - structMap["memo"] = c.Memo - } - if c.BillingSchedule != nil { - structMap["billing_schedule"] = c.BillingSchedule.toMap() - } - return structMap + structMap := make(map[string]any) + if c.Quantity != nil { + structMap["quantity"] = c.Quantity + } + if c.PricePointId != nil { + structMap["price_point_id"] = c.PricePointId + } + if c.Memo != nil { + structMap["memo"] = c.Memo + } + if c.BillingSchedule != nil { + structMap["billing_schedule"] = c.BillingSchedule.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateUsage. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateUsage. // It customizes the JSON unmarshaling process for CreateUsage objects. func (c *CreateUsage) UnmarshalJSON(input []byte) error { - temp := &struct { - Quantity *float64 `json:"quantity,omitempty"` - PricePointId *string `json:"price_point_id,omitempty"` - Memo *string `json:"memo,omitempty"` - BillingSchedule *BillingSchedule `json:"billing_schedule,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Quantity = temp.Quantity - c.PricePointId = temp.PricePointId - c.Memo = temp.Memo - c.BillingSchedule = temp.BillingSchedule - return nil + var temp createUsage + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Quantity = temp.Quantity + c.PricePointId = temp.PricePointId + c.Memo = temp.Memo + c.BillingSchedule = temp.BillingSchedule + return nil +} + +// TODO +type createUsage struct { + Quantity *float64 `json:"quantity,omitempty"` + PricePointId *string `json:"price_point_id,omitempty"` + Memo *string `json:"memo,omitempty"` + BillingSchedule *BillingSchedule `json:"billing_schedule,omitempty"` } diff --git a/models/create_usage_component_id.go b/models/create_usage_component_id.go new file mode 100644 index 00000000..6fdb7901 --- /dev/null +++ b/models/create_usage_component_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CreateUsageComponentId represents a CreateUsageComponentId struct. +// This is a container for one-of cases. +type CreateUsageComponentId struct { + value any + isNumber bool + isString bool +} + +// String converts the CreateUsageComponentId object to a string representation. +func (c CreateUsageComponentId) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CreateUsageComponentId. +// It customizes the JSON marshaling process for CreateUsageComponentId objects. +func (c *CreateUsageComponentId) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CreateUsageComponentIdContainer.From*` functions to initialize the CreateUsageComponentId object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CreateUsageComponentId object to a map representation for JSON marshaling. +func (c *CreateUsageComponentId) toMap() any { + switch obj := c.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreateUsageComponentId. +// It customizes the JSON unmarshaling process for CreateUsageComponentId objects. +func (c *CreateUsageComponentId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &c.isNumber), + NewTypeHolder(new(string), false, &c.isString), + ) + + c.value = result + return err +} + +func (c *CreateUsageComponentId) AsNumber() ( + *int, + bool) { + if !c.isNumber { + return nil, false + } + return c.value.(*int), true +} + +func (c *CreateUsageComponentId) AsString() ( + *string, + bool) { + if !c.isString { + return nil, false + } + return c.value.(*string), true +} + +// internalCreateUsageComponentId represents a createUsageComponentId struct. +// This is a container for one-of cases. +type internalCreateUsageComponentId struct{} + +var CreateUsageComponentIdContainer internalCreateUsageComponentId + +func (c *internalCreateUsageComponentId) FromNumber(val int) CreateUsageComponentId { + return CreateUsageComponentId{value: &val} +} + +func (c *internalCreateUsageComponentId) FromString(val string) CreateUsageComponentId { + return CreateUsageComponentId{value: &val} +} diff --git a/models/create_usage_request.go b/models/create_usage_request.go index 29b018dd..09e5bb6d 100644 --- a/models/create_usage_request.go +++ b/models/create_usage_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreateUsageRequest represents a CreateUsageRequest struct. type CreateUsageRequest struct { - Usage CreateUsage `json:"usage"` + Usage CreateUsage `json:"usage"` } -// MarshalJSON implements the json.Marshaler interface for CreateUsageRequest. +// MarshalJSON implements the json.Marshaler interface for CreateUsageRequest. // It customizes the JSON marshaling process for CreateUsageRequest objects. func (c *CreateUsageRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreateUsageRequest object to a map representation for JSON marshaling. func (c *CreateUsageRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["usage"] = c.Usage.toMap() - return structMap + structMap := make(map[string]any) + structMap["usage"] = c.Usage.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreateUsageRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreateUsageRequest. // It customizes the JSON unmarshaling process for CreateUsageRequest objects. func (c *CreateUsageRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Usage CreateUsage `json:"usage"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Usage = temp.Usage - return nil + var temp createUsageRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Usage = *temp.Usage + return nil +} + +// TODO +type createUsageRequest struct { + Usage *CreateUsage `json:"usage"` +} + +func (c *createUsageRequest) validate() error { + var errs []string + if c.Usage == nil { + errs = append(errs, "required field `usage` is missing for type `Create Usage Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/created_prepayment.go b/models/created_prepayment.go index c2f69b28..beba6e89 100644 --- a/models/created_prepayment.go +++ b/models/created_prepayment.go @@ -1,86 +1,88 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // CreatedPrepayment represents a CreatedPrepayment struct. type CreatedPrepayment struct { - Id *int `json:"id,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - Memo *string `json:"memo,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - StartingBalanceInCents *int64 `json:"starting_balance_in_cents,omitempty"` - EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` + Id *int64 `json:"id,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + Memo *string `json:"memo,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + StartingBalanceInCents *int64 `json:"starting_balance_in_cents,omitempty"` + EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreatedPrepayment. +// MarshalJSON implements the json.Marshaler interface for CreatedPrepayment. // It customizes the JSON marshaling process for CreatedPrepayment objects. func (c *CreatedPrepayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreatedPrepayment object to a map representation for JSON marshaling. func (c *CreatedPrepayment) toMap() map[string]any { - structMap := make(map[string]any) - if c.Id != nil { - structMap["id"] = c.Id - } - if c.SubscriptionId != nil { - structMap["subscription_id"] = c.SubscriptionId - } - if c.AmountInCents != nil { - structMap["amount_in_cents"] = c.AmountInCents - } - if c.Memo != nil { - structMap["memo"] = c.Memo - } - if c.CreatedAt != nil { - structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) - } - if c.StartingBalanceInCents != nil { - structMap["starting_balance_in_cents"] = c.StartingBalanceInCents - } - if c.EndingBalanceInCents != nil { - structMap["ending_balance_in_cents"] = c.EndingBalanceInCents - } - return structMap + structMap := make(map[string]any) + if c.Id != nil { + structMap["id"] = c.Id + } + if c.SubscriptionId != nil { + structMap["subscription_id"] = c.SubscriptionId + } + if c.AmountInCents != nil { + structMap["amount_in_cents"] = c.AmountInCents + } + if c.Memo != nil { + structMap["memo"] = c.Memo + } + if c.CreatedAt != nil { + structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) + } + if c.StartingBalanceInCents != nil { + structMap["starting_balance_in_cents"] = c.StartingBalanceInCents + } + if c.EndingBalanceInCents != nil { + structMap["ending_balance_in_cents"] = c.EndingBalanceInCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreatedPrepayment. +// UnmarshalJSON implements the json.Unmarshaler interface for CreatedPrepayment. // It customizes the JSON unmarshaling process for CreatedPrepayment objects. func (c *CreatedPrepayment) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - Memo *string `json:"memo,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - StartingBalanceInCents *int64 `json:"starting_balance_in_cents,omitempty"` - EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Id = temp.Id - c.SubscriptionId = temp.SubscriptionId - c.AmountInCents = temp.AmountInCents - c.Memo = temp.Memo - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - c.CreatedAt = &CreatedAtVal - } - c.StartingBalanceInCents = temp.StartingBalanceInCents - c.EndingBalanceInCents = temp.EndingBalanceInCents - return nil + var temp createdPrepayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Id = temp.Id + c.SubscriptionId = temp.SubscriptionId + c.AmountInCents = temp.AmountInCents + c.Memo = temp.Memo + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + c.CreatedAt = &CreatedAtVal + } + c.StartingBalanceInCents = temp.StartingBalanceInCents + c.EndingBalanceInCents = temp.EndingBalanceInCents + return nil +} + +// TODO +type createdPrepayment struct { + Id *int64 `json:"id,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + Memo *string `json:"memo,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + StartingBalanceInCents *int64 `json:"starting_balance_in_cents,omitempty"` + EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` } diff --git a/models/credit_account_balance_changed.go b/models/credit_account_balance_changed.go new file mode 100644 index 00000000..2c4642ad --- /dev/null +++ b/models/credit_account_balance_changed.go @@ -0,0 +1,94 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// CreditAccountBalanceChanged represents a CreditAccountBalanceChanged struct. +type CreditAccountBalanceChanged struct { + Reason string `json:"reason"` + ServiceCreditAccountBalanceInCents int64 `json:"service_credit_account_balance_in_cents"` + ServiceCreditBalanceChangeInCents int64 `json:"service_credit_balance_change_in_cents"` + CurrencyCode string `json:"currency_code"` + AtTime time.Time `json:"at_time"` +} + +// MarshalJSON implements the json.Marshaler interface for CreditAccountBalanceChanged. +// It customizes the JSON marshaling process for CreditAccountBalanceChanged objects. +func (c *CreditAccountBalanceChanged) MarshalJSON() ( + []byte, + error) { + return json.Marshal(c.toMap()) +} + +// toMap converts the CreditAccountBalanceChanged object to a map representation for JSON marshaling. +func (c *CreditAccountBalanceChanged) toMap() map[string]any { + structMap := make(map[string]any) + structMap["reason"] = c.Reason + structMap["service_credit_account_balance_in_cents"] = c.ServiceCreditAccountBalanceInCents + structMap["service_credit_balance_change_in_cents"] = c.ServiceCreditBalanceChangeInCents + structMap["currency_code"] = c.CurrencyCode + structMap["at_time"] = c.AtTime.Format(time.RFC3339) + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CreditAccountBalanceChanged. +// It customizes the JSON unmarshaling process for CreditAccountBalanceChanged objects. +func (c *CreditAccountBalanceChanged) UnmarshalJSON(input []byte) error { + var temp creditAccountBalanceChanged + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Reason = *temp.Reason + c.ServiceCreditAccountBalanceInCents = *temp.ServiceCreditAccountBalanceInCents + c.ServiceCreditBalanceChangeInCents = *temp.ServiceCreditBalanceChangeInCents + c.CurrencyCode = *temp.CurrencyCode + AtTimeVal, err := time.Parse(time.RFC3339, *temp.AtTime) + if err != nil { + log.Fatalf("Cannot Parse at_time as % s format.", time.RFC3339) + } + c.AtTime = AtTimeVal + return nil +} + +// TODO +type creditAccountBalanceChanged struct { + Reason *string `json:"reason"` + ServiceCreditAccountBalanceInCents *int64 `json:"service_credit_account_balance_in_cents"` + ServiceCreditBalanceChangeInCents *int64 `json:"service_credit_balance_change_in_cents"` + CurrencyCode *string `json:"currency_code"` + AtTime *string `json:"at_time"` +} + +func (c *creditAccountBalanceChanged) validate() error { + var errs []string + if c.Reason == nil { + errs = append(errs, "required field `reason` is missing for type `Credit Account Balance Changed`") + } + if c.ServiceCreditAccountBalanceInCents == nil { + errs = append(errs, "required field `service_credit_account_balance_in_cents` is missing for type `Credit Account Balance Changed`") + } + if c.ServiceCreditBalanceChangeInCents == nil { + errs = append(errs, "required field `service_credit_balance_change_in_cents` is missing for type `Credit Account Balance Changed`") + } + if c.CurrencyCode == nil { + errs = append(errs, "required field `currency_code` is missing for type `Credit Account Balance Changed`") + } + if c.AtTime == nil { + errs = append(errs, "required field `at_time` is missing for type `Credit Account Balance Changed`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/credit_card_attributes.go b/models/credit_card_attributes.go index e565abbc..2915bb6b 100644 --- a/models/credit_card_attributes.go +++ b/models/credit_card_attributes.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // CreditCardAttributes represents a CreditCardAttributes struct. type CreditCardAttributes struct { - FullNumber *string `json:"full_number,omitempty"` - ExpirationMonth *string `json:"expiration_month,omitempty"` - ExpirationYear *string `json:"expiration_year,omitempty"` + FullNumber *string `json:"full_number,omitempty"` + ExpirationMonth *string `json:"expiration_month,omitempty"` + ExpirationYear *string `json:"expiration_year,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreditCardAttributes. +// MarshalJSON implements the json.Marshaler interface for CreditCardAttributes. // It customizes the JSON marshaling process for CreditCardAttributes objects. func (c *CreditCardAttributes) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreditCardAttributes object to a map representation for JSON marshaling. func (c *CreditCardAttributes) toMap() map[string]any { - structMap := make(map[string]any) - if c.FullNumber != nil { - structMap["full_number"] = c.FullNumber - } - if c.ExpirationMonth != nil { - structMap["expiration_month"] = c.ExpirationMonth - } - if c.ExpirationYear != nil { - structMap["expiration_year"] = c.ExpirationYear - } - return structMap + structMap := make(map[string]any) + if c.FullNumber != nil { + structMap["full_number"] = c.FullNumber + } + if c.ExpirationMonth != nil { + structMap["expiration_month"] = c.ExpirationMonth + } + if c.ExpirationYear != nil { + structMap["expiration_year"] = c.ExpirationYear + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreditCardAttributes. +// UnmarshalJSON implements the json.Unmarshaler interface for CreditCardAttributes. // It customizes the JSON unmarshaling process for CreditCardAttributes objects. func (c *CreditCardAttributes) UnmarshalJSON(input []byte) error { - temp := &struct { - FullNumber *string `json:"full_number,omitempty"` - ExpirationMonth *string `json:"expiration_month,omitempty"` - ExpirationYear *string `json:"expiration_year,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.FullNumber = temp.FullNumber - c.ExpirationMonth = temp.ExpirationMonth - c.ExpirationYear = temp.ExpirationYear - return nil + var temp creditCardAttributes + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.FullNumber = temp.FullNumber + c.ExpirationMonth = temp.ExpirationMonth + c.ExpirationYear = temp.ExpirationYear + return nil +} + +// TODO +type creditCardAttributes struct { + FullNumber *string `json:"full_number,omitempty"` + ExpirationMonth *string `json:"expiration_month,omitempty"` + ExpirationYear *string `json:"expiration_year,omitempty"` } diff --git a/models/credit_card_payment_profile.go b/models/credit_card_payment_profile.go index a3698f17..f414601c 100644 --- a/models/credit_card_payment_profile.go +++ b/models/credit_card_payment_profile.go @@ -1,185 +1,245 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreditCardPaymentProfile represents a CreditCardPaymentProfile struct. type CreditCardPaymentProfile struct { - // The Chargify-assigned ID of the stored card. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer. - Id *int `json:"id,omitempty"` - // The first name of the card holder. - FirstName *string `json:"first_name,omitempty"` - // The last name of the card holder. - LastName *string `json:"last_name,omitempty"` - // A string representation of the credit card number with all but the last 4 digits masked with X’s (i.e. ‘XXXX-XXXX-XXXX-1234’). - MaskedCardNumber string `json:"masked_card_number"` - // The type of card used. - CardType *CardType `json:"card_type,omitempty"` - // An integer representing the expiration month of the card(1 – 12). - ExpirationMonth *int `json:"expiration_month,omitempty"` - // An integer representing the 4-digit expiration year of the card(i.e. ‘2012’). - ExpirationYear *int `json:"expiration_year,omitempty"` - // The Chargify-assigned id for the customer record to which the card belongs. - CustomerId *int `json:"customer_id,omitempty"` - // The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. - CurrentVault *CurrentVault `json:"current_vault,omitempty"` - // The “token” provided by your vault storage for an already stored payment profile. - VaultToken Optional[string] `json:"vault_token"` - // The current billing street address for the card. - BillingAddress Optional[string] `json:"billing_address"` - // The current billing address city for the card. - BillingCity Optional[string] `json:"billing_city"` - // The current billing address state for the card. - BillingState Optional[string] `json:"billing_state"` - // The current billing address zip code for the card. - BillingZip Optional[string] `json:"billing_zip"` - // The current billing address country for the card. - BillingCountry Optional[string] `json:"billing_country"` - // (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. - CustomerVaultToken Optional[string] `json:"customer_vault_token"` - // The current billing street address, second line, for the card. - BillingAddress2 Optional[string] `json:"billing_address_2"` - PaymentType *PaymentType `json:"payment_type,omitempty"` - Disabled *bool `json:"disabled,omitempty"` - // Token received after sending billing information using chargify.js. This token will only be received if passed as a sole attribute of credit_card_attributes (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) - ChargifyToken *string `json:"chargify_token,omitempty"` - SiteGatewaySettingId Optional[int] `json:"site_gateway_setting_id"` - // An identifier of connected gateway. - GatewayHandle Optional[string] `json:"gateway_handle"` + // The Chargify-assigned ID of the stored card. This value can be used as an input to payment_profile_id when creating a subscription, in order to re-use a stored payment profile for the same customer. + Id *int `json:"id,omitempty"` + // The first name of the card holder. + FirstName *string `json:"first_name,omitempty"` + // The last name of the card holder. + LastName *string `json:"last_name,omitempty"` + // A string representation of the credit card number with all but the last 4 digits masked with X’s (i.e. ‘XXXX-XXXX-XXXX-1234’). + MaskedCardNumber string `json:"masked_card_number"` + // The type of card used. + CardType *CardType `json:"card_type,omitempty"` + // An integer representing the expiration month of the card(1 – 12). + ExpirationMonth *int `json:"expiration_month,omitempty"` + // An integer representing the 4-digit expiration year of the card(i.e. ‘2012’). + ExpirationYear *int `json:"expiration_year,omitempty"` + // The Chargify-assigned id for the customer record to which the card belongs. + CustomerId *int `json:"customer_id,omitempty"` + // The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. + CurrentVault *CurrentVault `json:"current_vault,omitempty"` + // The “token” provided by your vault storage for an already stored payment profile. + VaultToken Optional[string] `json:"vault_token"` + // The current billing street address for the card. + BillingAddress Optional[string] `json:"billing_address"` + // The current billing address city for the card. + BillingCity Optional[string] `json:"billing_city"` + // The current billing address state for the card. + BillingState Optional[string] `json:"billing_state"` + // The current billing address zip code for the card. + BillingZip Optional[string] `json:"billing_zip"` + // The current billing address country for the card. + BillingCountry Optional[string] `json:"billing_country"` + // (only for Authorize.Net CIM storage): the customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token. + CustomerVaultToken Optional[string] `json:"customer_vault_token"` + // The current billing street address, second line, for the card. + BillingAddress2 Optional[string] `json:"billing_address_2"` + PaymentType *PaymentType `json:"payment_type,omitempty"` + Disabled *bool `json:"disabled,omitempty"` + // Token received after sending billing information using chargify.js. This token will only be received if passed as a sole attribute of credit_card_attributes (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) + ChargifyToken *string `json:"chargify_token,omitempty"` + SiteGatewaySettingId Optional[int] `json:"site_gateway_setting_id"` + // An identifier of connected gateway. + GatewayHandle Optional[string] `json:"gateway_handle"` } -// MarshalJSON implements the json.Marshaler interface for CreditCardPaymentProfile. +// MarshalJSON implements the json.Marshaler interface for CreditCardPaymentProfile. // It customizes the JSON marshaling process for CreditCardPaymentProfile objects. func (c *CreditCardPaymentProfile) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreditCardPaymentProfile object to a map representation for JSON marshaling. func (c *CreditCardPaymentProfile) toMap() map[string]any { - structMap := make(map[string]any) - if c.Id != nil { - structMap["id"] = c.Id - } - if c.FirstName != nil { - structMap["first_name"] = c.FirstName - } - if c.LastName != nil { - structMap["last_name"] = c.LastName - } - structMap["masked_card_number"] = c.MaskedCardNumber - if c.CardType != nil { - structMap["card_type"] = c.CardType - } - if c.ExpirationMonth != nil { - structMap["expiration_month"] = c.ExpirationMonth - } - if c.ExpirationYear != nil { - structMap["expiration_year"] = c.ExpirationYear - } - if c.CustomerId != nil { - structMap["customer_id"] = c.CustomerId - } - if c.CurrentVault != nil { - structMap["current_vault"] = c.CurrentVault - } - if c.VaultToken.IsValueSet() { - structMap["vault_token"] = c.VaultToken.Value() - } - if c.BillingAddress.IsValueSet() { - structMap["billing_address"] = c.BillingAddress.Value() - } - if c.BillingCity.IsValueSet() { - structMap["billing_city"] = c.BillingCity.Value() - } - if c.BillingState.IsValueSet() { - structMap["billing_state"] = c.BillingState.Value() - } - if c.BillingZip.IsValueSet() { - structMap["billing_zip"] = c.BillingZip.Value() - } - if c.BillingCountry.IsValueSet() { - structMap["billing_country"] = c.BillingCountry.Value() - } - if c.CustomerVaultToken.IsValueSet() { - structMap["customer_vault_token"] = c.CustomerVaultToken.Value() - } - if c.BillingAddress2.IsValueSet() { - structMap["billing_address_2"] = c.BillingAddress2.Value() - } - if c.PaymentType != nil { - structMap["payment_type"] = c.PaymentType - } - if c.Disabled != nil { - structMap["disabled"] = c.Disabled - } - if c.ChargifyToken != nil { - structMap["chargify_token"] = c.ChargifyToken - } - if c.SiteGatewaySettingId.IsValueSet() { - structMap["site_gateway_setting_id"] = c.SiteGatewaySettingId.Value() - } - if c.GatewayHandle.IsValueSet() { - structMap["gateway_handle"] = c.GatewayHandle.Value() - } - return structMap + structMap := make(map[string]any) + if c.Id != nil { + structMap["id"] = c.Id + } + if c.FirstName != nil { + structMap["first_name"] = c.FirstName + } + if c.LastName != nil { + structMap["last_name"] = c.LastName + } + structMap["masked_card_number"] = c.MaskedCardNumber + if c.CardType != nil { + structMap["card_type"] = c.CardType + } + if c.ExpirationMonth != nil { + structMap["expiration_month"] = c.ExpirationMonth + } + if c.ExpirationYear != nil { + structMap["expiration_year"] = c.ExpirationYear + } + if c.CustomerId != nil { + structMap["customer_id"] = c.CustomerId + } + if c.CurrentVault != nil { + structMap["current_vault"] = c.CurrentVault + } + if c.VaultToken.IsValueSet() { + if c.VaultToken.Value() != nil { + structMap["vault_token"] = c.VaultToken.Value() + } else { + structMap["vault_token"] = nil + } + } + if c.BillingAddress.IsValueSet() { + if c.BillingAddress.Value() != nil { + structMap["billing_address"] = c.BillingAddress.Value() + } else { + structMap["billing_address"] = nil + } + } + if c.BillingCity.IsValueSet() { + if c.BillingCity.Value() != nil { + structMap["billing_city"] = c.BillingCity.Value() + } else { + structMap["billing_city"] = nil + } + } + if c.BillingState.IsValueSet() { + if c.BillingState.Value() != nil { + structMap["billing_state"] = c.BillingState.Value() + } else { + structMap["billing_state"] = nil + } + } + if c.BillingZip.IsValueSet() { + if c.BillingZip.Value() != nil { + structMap["billing_zip"] = c.BillingZip.Value() + } else { + structMap["billing_zip"] = nil + } + } + if c.BillingCountry.IsValueSet() { + if c.BillingCountry.Value() != nil { + structMap["billing_country"] = c.BillingCountry.Value() + } else { + structMap["billing_country"] = nil + } + } + if c.CustomerVaultToken.IsValueSet() { + if c.CustomerVaultToken.Value() != nil { + structMap["customer_vault_token"] = c.CustomerVaultToken.Value() + } else { + structMap["customer_vault_token"] = nil + } + } + if c.BillingAddress2.IsValueSet() { + if c.BillingAddress2.Value() != nil { + structMap["billing_address_2"] = c.BillingAddress2.Value() + } else { + structMap["billing_address_2"] = nil + } + } + if c.PaymentType != nil { + structMap["payment_type"] = c.PaymentType + } + if c.Disabled != nil { + structMap["disabled"] = c.Disabled + } + if c.ChargifyToken != nil { + structMap["chargify_token"] = c.ChargifyToken + } + if c.SiteGatewaySettingId.IsValueSet() { + if c.SiteGatewaySettingId.Value() != nil { + structMap["site_gateway_setting_id"] = c.SiteGatewaySettingId.Value() + } else { + structMap["site_gateway_setting_id"] = nil + } + } + if c.GatewayHandle.IsValueSet() { + if c.GatewayHandle.Value() != nil { + structMap["gateway_handle"] = c.GatewayHandle.Value() + } else { + structMap["gateway_handle"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreditCardPaymentProfile. +// UnmarshalJSON implements the json.Unmarshaler interface for CreditCardPaymentProfile. // It customizes the JSON unmarshaling process for CreditCardPaymentProfile objects. func (c *CreditCardPaymentProfile) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - MaskedCardNumber string `json:"masked_card_number"` - CardType *CardType `json:"card_type,omitempty"` - ExpirationMonth *int `json:"expiration_month,omitempty"` - ExpirationYear *int `json:"expiration_year,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - CurrentVault *CurrentVault `json:"current_vault,omitempty"` - VaultToken Optional[string] `json:"vault_token"` - BillingAddress Optional[string] `json:"billing_address"` - BillingCity Optional[string] `json:"billing_city"` - BillingState Optional[string] `json:"billing_state"` - BillingZip Optional[string] `json:"billing_zip"` - BillingCountry Optional[string] `json:"billing_country"` - CustomerVaultToken Optional[string] `json:"customer_vault_token"` - BillingAddress2 Optional[string] `json:"billing_address_2"` - PaymentType *PaymentType `json:"payment_type,omitempty"` - Disabled *bool `json:"disabled,omitempty"` - ChargifyToken *string `json:"chargify_token,omitempty"` - SiteGatewaySettingId Optional[int] `json:"site_gateway_setting_id"` - GatewayHandle Optional[string] `json:"gateway_handle"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Id = temp.Id - c.FirstName = temp.FirstName - c.LastName = temp.LastName - c.MaskedCardNumber = temp.MaskedCardNumber - c.CardType = temp.CardType - c.ExpirationMonth = temp.ExpirationMonth - c.ExpirationYear = temp.ExpirationYear - c.CustomerId = temp.CustomerId - c.CurrentVault = temp.CurrentVault - c.VaultToken = temp.VaultToken - c.BillingAddress = temp.BillingAddress - c.BillingCity = temp.BillingCity - c.BillingState = temp.BillingState - c.BillingZip = temp.BillingZip - c.BillingCountry = temp.BillingCountry - c.CustomerVaultToken = temp.CustomerVaultToken - c.BillingAddress2 = temp.BillingAddress2 - c.PaymentType = temp.PaymentType - c.Disabled = temp.Disabled - c.ChargifyToken = temp.ChargifyToken - c.SiteGatewaySettingId = temp.SiteGatewaySettingId - c.GatewayHandle = temp.GatewayHandle - return nil + var temp creditCardPaymentProfile + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Id = temp.Id + c.FirstName = temp.FirstName + c.LastName = temp.LastName + c.MaskedCardNumber = *temp.MaskedCardNumber + c.CardType = temp.CardType + c.ExpirationMonth = temp.ExpirationMonth + c.ExpirationYear = temp.ExpirationYear + c.CustomerId = temp.CustomerId + c.CurrentVault = temp.CurrentVault + c.VaultToken = temp.VaultToken + c.BillingAddress = temp.BillingAddress + c.BillingCity = temp.BillingCity + c.BillingState = temp.BillingState + c.BillingZip = temp.BillingZip + c.BillingCountry = temp.BillingCountry + c.CustomerVaultToken = temp.CustomerVaultToken + c.BillingAddress2 = temp.BillingAddress2 + c.PaymentType = temp.PaymentType + c.Disabled = temp.Disabled + c.ChargifyToken = temp.ChargifyToken + c.SiteGatewaySettingId = temp.SiteGatewaySettingId + c.GatewayHandle = temp.GatewayHandle + return nil +} + +// TODO +type creditCardPaymentProfile struct { + Id *int `json:"id,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + MaskedCardNumber *string `json:"masked_card_number"` + CardType *CardType `json:"card_type,omitempty"` + ExpirationMonth *int `json:"expiration_month,omitempty"` + ExpirationYear *int `json:"expiration_year,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + CurrentVault *CurrentVault `json:"current_vault,omitempty"` + VaultToken Optional[string] `json:"vault_token"` + BillingAddress Optional[string] `json:"billing_address"` + BillingCity Optional[string] `json:"billing_city"` + BillingState Optional[string] `json:"billing_state"` + BillingZip Optional[string] `json:"billing_zip"` + BillingCountry Optional[string] `json:"billing_country"` + CustomerVaultToken Optional[string] `json:"customer_vault_token"` + BillingAddress2 Optional[string] `json:"billing_address_2"` + PaymentType *PaymentType `json:"payment_type,omitempty"` + Disabled *bool `json:"disabled,omitempty"` + ChargifyToken *string `json:"chargify_token,omitempty"` + SiteGatewaySettingId Optional[int] `json:"site_gateway_setting_id"` + GatewayHandle Optional[string] `json:"gateway_handle"` +} + +func (c *creditCardPaymentProfile) validate() error { + var errs []string + if c.MaskedCardNumber == nil { + errs = append(errs, "required field `masked_card_number` is missing for type `Credit Card Payment Profile`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/credit_note.go b/models/credit_note.go index 2619d636..8c00d3e4 100644 --- a/models/credit_note.go +++ b/models/credit_note.go @@ -1,239 +1,241 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // CreditNote represents a CreditNote struct. type CreditNote struct { - // Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. - Uid *string `json:"uid,omitempty"` - // ID of the site to which the credit note belongs. - SiteId *int `json:"site_id,omitempty"` - // ID of the customer to which the credit note belongs. - CustomerId *int `json:"customer_id,omitempty"` - // ID of the subscription that generated the credit note. - SubscriptionId *int `json:"subscription_id,omitempty"` - // A unique, identifying string that appears on the credit note and in places it is referenced. - // While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. - Number *string `json:"number,omitempty"` - // A monotonically increasing number assigned to credit notes as they are created. This number is unique within a site and can be used to sort and order credit notes. - SequenceNumber *int `json:"sequence_number,omitempty"` - // Date the credit note was issued to the customer. This is the date that the credit was made available for application, and may come before it is fully applied. - // The format is `"YYYY-MM-DD"`. - IssueDate *time.Time `json:"issue_date,omitempty"` - // Credit notes are applied to invoices to offset invoiced amounts - they reduce the amount due. This field is the date the credit note became fully applied to invoices. - // If the credit note has been partially applied, this field will not have a value until it has been fully applied. - // The format is `"YYYY-MM-DD"`. - AppliedDate *time.Time `json:"applied_date,omitempty"` - // Current status of the credit note. - Status *CreditNoteStatus `json:"status,omitempty"` - // The ISO 4217 currency code (3 character string) representing the currency of the credit note amount fields. - Currency *string `json:"currency,omitempty"` - // The memo printed on credit note, which is a description of the reason for the credit. - Memo *string `json:"memo,omitempty"` - // Information about the seller (merchant) listed on the masthead of the credit note. - Seller *InvoiceSeller `json:"seller,omitempty"` - // Information about the customer who is owner or recipient the credited subscription. - Customer *InvoiceCustomer `json:"customer,omitempty"` - // The billing address of the credit subscription. - BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` - // The shipping address of the credited subscription. - ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` - // Subtotal of the credit note, which is the sum of all line items before discounts or taxes. Note that this is a positive amount representing the credit back to the customer. - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - // Total discount applied to the credit note. Note that this is a positive amount representing the discount amount being credited back to the customer (i.e. a credit on an earlier discount). For example, if the original purchase was $1.00 and the original discount was $0.10, a credit of $0.50 of the original purchase (half) would have a discount credit of $0.05 (also half). - DiscountAmount *string `json:"discount_amount,omitempty"` - // Total tax of the credit note. Note that this is a positive amount representing a previously taxex amount being credited back to the customer (i.e. a credit of an earlier tax). For example, if the original purchase was $1.00 and the original tax was $0.10, a credit of $0.50 of the original purchase (half) would also have a tax credit of $0.05 (also half). - TaxAmount *string `json:"tax_amount,omitempty"` - // The credit note total, which is `subtotal_amount - discount_amount + tax_amount`.' - TotalAmount *string `json:"total_amount,omitempty"` - // The amount of the credit note that has already been applied to invoices. - AppliedAmount *string `json:"applied_amount,omitempty"` - // The amount of the credit note remaining to be applied to invoices, which is `total_amount - applied_amount`. - RemainingAmount *string `json:"remaining_amount,omitempty"` - // Line items on the credit note. - LineItems []CreditNoteLineItem `json:"line_items,omitempty"` - Discounts []InvoiceDiscount `json:"discounts,omitempty"` - Taxes []InvoiceTax `json:"taxes,omitempty"` - Applications []CreditNoteApplication `json:"applications,omitempty"` - Refunds []InvoiceRefund `json:"refunds,omitempty"` - // An array of origin invoices for the credit note. Learn more about [Origin Invoice from our docs](https://chargify.zendesk.com/hc/en-us/articles/4407753036699#origin-invoices) - OriginInvoices []OriginInvoice `json:"origin_invoices,omitempty"` + // Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. + Uid *string `json:"uid,omitempty"` + // ID of the site to which the credit note belongs. + SiteId *int `json:"site_id,omitempty"` + // ID of the customer to which the credit note belongs. + CustomerId *int `json:"customer_id,omitempty"` + // ID of the subscription that generated the credit note. + SubscriptionId *int `json:"subscription_id,omitempty"` + // A unique, identifying string that appears on the credit note and in places it is referenced. + // While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. + Number *string `json:"number,omitempty"` + // A monotonically increasing number assigned to credit notes as they are created. This number is unique within a site and can be used to sort and order credit notes. + SequenceNumber *int `json:"sequence_number,omitempty"` + // Date the credit note was issued to the customer. This is the date that the credit was made available for application, and may come before it is fully applied. + // The format is `"YYYY-MM-DD"`. + IssueDate *time.Time `json:"issue_date,omitempty"` + // Credit notes are applied to invoices to offset invoiced amounts - they reduce the amount due. This field is the date the credit note became fully applied to invoices. + // If the credit note has been partially applied, this field will not have a value until it has been fully applied. + // The format is `"YYYY-MM-DD"`. + AppliedDate *time.Time `json:"applied_date,omitempty"` + // Current status of the credit note. + Status *CreditNoteStatus `json:"status,omitempty"` + // The ISO 4217 currency code (3 character string) representing the currency of the credit note amount fields. + Currency *string `json:"currency,omitempty"` + // The memo printed on credit note, which is a description of the reason for the credit. + Memo *string `json:"memo,omitempty"` + // Information about the seller (merchant) listed on the masthead of the credit note. + Seller *InvoiceSeller `json:"seller,omitempty"` + // Information about the customer who is owner or recipient the credited subscription. + Customer *InvoiceCustomer `json:"customer,omitempty"` + // The billing address of the credit subscription. + BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` + // The shipping address of the credited subscription. + ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` + // Subtotal of the credit note, which is the sum of all line items before discounts or taxes. Note that this is a positive amount representing the credit back to the customer. + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + // Total discount applied to the credit note. Note that this is a positive amount representing the discount amount being credited back to the customer (i.e. a credit on an earlier discount). For example, if the original purchase was $1.00 and the original discount was $0.10, a credit of $0.50 of the original purchase (half) would have a discount credit of $0.05 (also half). + DiscountAmount *string `json:"discount_amount,omitempty"` + // Total tax of the credit note. Note that this is a positive amount representing a previously taxex amount being credited back to the customer (i.e. a credit of an earlier tax). For example, if the original purchase was $1.00 and the original tax was $0.10, a credit of $0.50 of the original purchase (half) would also have a tax credit of $0.05 (also half). + TaxAmount *string `json:"tax_amount,omitempty"` + // The credit note total, which is `subtotal_amount - discount_amount + tax_amount`.' + TotalAmount *string `json:"total_amount,omitempty"` + // The amount of the credit note that has already been applied to invoices. + AppliedAmount *string `json:"applied_amount,omitempty"` + // The amount of the credit note remaining to be applied to invoices, which is `total_amount - applied_amount`. + RemainingAmount *string `json:"remaining_amount,omitempty"` + // Line items on the credit note. + LineItems []CreditNoteLineItem `json:"line_items,omitempty"` + Discounts []InvoiceDiscount `json:"discounts,omitempty"` + Taxes []InvoiceTax `json:"taxes,omitempty"` + Applications []CreditNoteApplication `json:"applications,omitempty"` + Refunds []InvoiceRefund `json:"refunds,omitempty"` + // An array of origin invoices for the credit note. Learn more about [Origin Invoice from our docs](https://chargify.zendesk.com/hc/en-us/articles/4407753036699#origin-invoices) + OriginInvoices []OriginInvoice `json:"origin_invoices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreditNote. +// MarshalJSON implements the json.Marshaler interface for CreditNote. // It customizes the JSON marshaling process for CreditNote objects. func (c *CreditNote) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreditNote object to a map representation for JSON marshaling. func (c *CreditNote) toMap() map[string]any { - structMap := make(map[string]any) - if c.Uid != nil { - structMap["uid"] = c.Uid - } - if c.SiteId != nil { - structMap["site_id"] = c.SiteId - } - if c.CustomerId != nil { - structMap["customer_id"] = c.CustomerId - } - if c.SubscriptionId != nil { - structMap["subscription_id"] = c.SubscriptionId - } - if c.Number != nil { - structMap["number"] = c.Number - } - if c.SequenceNumber != nil { - structMap["sequence_number"] = c.SequenceNumber - } - if c.IssueDate != nil { - structMap["issue_date"] = c.IssueDate.Format(DEFAULT_DATE) - } - if c.AppliedDate != nil { - structMap["applied_date"] = c.AppliedDate.Format(DEFAULT_DATE) - } - if c.Status != nil { - structMap["status"] = c.Status - } - if c.Currency != nil { - structMap["currency"] = c.Currency - } - if c.Memo != nil { - structMap["memo"] = c.Memo - } - if c.Seller != nil { - structMap["seller"] = c.Seller.toMap() - } - if c.Customer != nil { - structMap["customer"] = c.Customer.toMap() - } - if c.BillingAddress != nil { - structMap["billing_address"] = c.BillingAddress.toMap() - } - if c.ShippingAddress != nil { - structMap["shipping_address"] = c.ShippingAddress.toMap() - } - if c.SubtotalAmount != nil { - structMap["subtotal_amount"] = c.SubtotalAmount - } - if c.DiscountAmount != nil { - structMap["discount_amount"] = c.DiscountAmount - } - if c.TaxAmount != nil { - structMap["tax_amount"] = c.TaxAmount - } - if c.TotalAmount != nil { - structMap["total_amount"] = c.TotalAmount - } - if c.AppliedAmount != nil { - structMap["applied_amount"] = c.AppliedAmount - } - if c.RemainingAmount != nil { - structMap["remaining_amount"] = c.RemainingAmount - } - if c.LineItems != nil { - structMap["line_items"] = c.LineItems - } - if c.Discounts != nil { - structMap["discounts"] = c.Discounts - } - if c.Taxes != nil { - structMap["taxes"] = c.Taxes - } - if c.Applications != nil { - structMap["applications"] = c.Applications - } - if c.Refunds != nil { - structMap["refunds"] = c.Refunds - } - if c.OriginInvoices != nil { - structMap["origin_invoices"] = c.OriginInvoices - } - return structMap + structMap := make(map[string]any) + if c.Uid != nil { + structMap["uid"] = c.Uid + } + if c.SiteId != nil { + structMap["site_id"] = c.SiteId + } + if c.CustomerId != nil { + structMap["customer_id"] = c.CustomerId + } + if c.SubscriptionId != nil { + structMap["subscription_id"] = c.SubscriptionId + } + if c.Number != nil { + structMap["number"] = c.Number + } + if c.SequenceNumber != nil { + structMap["sequence_number"] = c.SequenceNumber + } + if c.IssueDate != nil { + structMap["issue_date"] = c.IssueDate.Format(DEFAULT_DATE) + } + if c.AppliedDate != nil { + structMap["applied_date"] = c.AppliedDate.Format(DEFAULT_DATE) + } + if c.Status != nil { + structMap["status"] = c.Status + } + if c.Currency != nil { + structMap["currency"] = c.Currency + } + if c.Memo != nil { + structMap["memo"] = c.Memo + } + if c.Seller != nil { + structMap["seller"] = c.Seller.toMap() + } + if c.Customer != nil { + structMap["customer"] = c.Customer.toMap() + } + if c.BillingAddress != nil { + structMap["billing_address"] = c.BillingAddress.toMap() + } + if c.ShippingAddress != nil { + structMap["shipping_address"] = c.ShippingAddress.toMap() + } + if c.SubtotalAmount != nil { + structMap["subtotal_amount"] = c.SubtotalAmount + } + if c.DiscountAmount != nil { + structMap["discount_amount"] = c.DiscountAmount + } + if c.TaxAmount != nil { + structMap["tax_amount"] = c.TaxAmount + } + if c.TotalAmount != nil { + structMap["total_amount"] = c.TotalAmount + } + if c.AppliedAmount != nil { + structMap["applied_amount"] = c.AppliedAmount + } + if c.RemainingAmount != nil { + structMap["remaining_amount"] = c.RemainingAmount + } + if c.LineItems != nil { + structMap["line_items"] = c.LineItems + } + if c.Discounts != nil { + structMap["discounts"] = c.Discounts + } + if c.Taxes != nil { + structMap["taxes"] = c.Taxes + } + if c.Applications != nil { + structMap["applications"] = c.Applications + } + if c.Refunds != nil { + structMap["refunds"] = c.Refunds + } + if c.OriginInvoices != nil { + structMap["origin_invoices"] = c.OriginInvoices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreditNote. +// UnmarshalJSON implements the json.Unmarshaler interface for CreditNote. // It customizes the JSON unmarshaling process for CreditNote objects. func (c *CreditNote) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - SiteId *int `json:"site_id,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - Number *string `json:"number,omitempty"` - SequenceNumber *int `json:"sequence_number,omitempty"` - IssueDate *string `json:"issue_date,omitempty"` - AppliedDate *string `json:"applied_date,omitempty"` - Status *CreditNoteStatus `json:"status,omitempty"` - Currency *string `json:"currency,omitempty"` - Memo *string `json:"memo,omitempty"` - Seller *InvoiceSeller `json:"seller,omitempty"` - Customer *InvoiceCustomer `json:"customer,omitempty"` - BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` - ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - TotalAmount *string `json:"total_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - RemainingAmount *string `json:"remaining_amount,omitempty"` - LineItems []CreditNoteLineItem `json:"line_items,omitempty"` - Discounts []InvoiceDiscount `json:"discounts,omitempty"` - Taxes []InvoiceTax `json:"taxes,omitempty"` - Applications []CreditNoteApplication `json:"applications,omitempty"` - Refunds []InvoiceRefund `json:"refunds,omitempty"` - OriginInvoices []OriginInvoice `json:"origin_invoices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Uid = temp.Uid - c.SiteId = temp.SiteId - c.CustomerId = temp.CustomerId - c.SubscriptionId = temp.SubscriptionId - c.Number = temp.Number - c.SequenceNumber = temp.SequenceNumber - if temp.IssueDate != nil { - IssueDateVal, err := time.Parse(DEFAULT_DATE, *temp.IssueDate) - if err != nil { - log.Fatalf("Cannot Parse issue_date as % s format.", DEFAULT_DATE) - } - c.IssueDate = &IssueDateVal - } - if temp.AppliedDate != nil { - AppliedDateVal, err := time.Parse(DEFAULT_DATE, *temp.AppliedDate) - if err != nil { - log.Fatalf("Cannot Parse applied_date as % s format.", DEFAULT_DATE) - } - c.AppliedDate = &AppliedDateVal - } - c.Status = temp.Status - c.Currency = temp.Currency - c.Memo = temp.Memo - c.Seller = temp.Seller - c.Customer = temp.Customer - c.BillingAddress = temp.BillingAddress - c.ShippingAddress = temp.ShippingAddress - c.SubtotalAmount = temp.SubtotalAmount - c.DiscountAmount = temp.DiscountAmount - c.TaxAmount = temp.TaxAmount - c.TotalAmount = temp.TotalAmount - c.AppliedAmount = temp.AppliedAmount - c.RemainingAmount = temp.RemainingAmount - c.LineItems = temp.LineItems - c.Discounts = temp.Discounts - c.Taxes = temp.Taxes - c.Applications = temp.Applications - c.Refunds = temp.Refunds - c.OriginInvoices = temp.OriginInvoices - return nil + var temp creditNote + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Uid = temp.Uid + c.SiteId = temp.SiteId + c.CustomerId = temp.CustomerId + c.SubscriptionId = temp.SubscriptionId + c.Number = temp.Number + c.SequenceNumber = temp.SequenceNumber + if temp.IssueDate != nil { + IssueDateVal, err := time.Parse(DEFAULT_DATE, *temp.IssueDate) + if err != nil { + log.Fatalf("Cannot Parse issue_date as % s format.", DEFAULT_DATE) + } + c.IssueDate = &IssueDateVal + } + if temp.AppliedDate != nil { + AppliedDateVal, err := time.Parse(DEFAULT_DATE, *temp.AppliedDate) + if err != nil { + log.Fatalf("Cannot Parse applied_date as % s format.", DEFAULT_DATE) + } + c.AppliedDate = &AppliedDateVal + } + c.Status = temp.Status + c.Currency = temp.Currency + c.Memo = temp.Memo + c.Seller = temp.Seller + c.Customer = temp.Customer + c.BillingAddress = temp.BillingAddress + c.ShippingAddress = temp.ShippingAddress + c.SubtotalAmount = temp.SubtotalAmount + c.DiscountAmount = temp.DiscountAmount + c.TaxAmount = temp.TaxAmount + c.TotalAmount = temp.TotalAmount + c.AppliedAmount = temp.AppliedAmount + c.RemainingAmount = temp.RemainingAmount + c.LineItems = temp.LineItems + c.Discounts = temp.Discounts + c.Taxes = temp.Taxes + c.Applications = temp.Applications + c.Refunds = temp.Refunds + c.OriginInvoices = temp.OriginInvoices + return nil +} + +// TODO +type creditNote struct { + Uid *string `json:"uid,omitempty"` + SiteId *int `json:"site_id,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + Number *string `json:"number,omitempty"` + SequenceNumber *int `json:"sequence_number,omitempty"` + IssueDate *string `json:"issue_date,omitempty"` + AppliedDate *string `json:"applied_date,omitempty"` + Status *CreditNoteStatus `json:"status,omitempty"` + Currency *string `json:"currency,omitempty"` + Memo *string `json:"memo,omitempty"` + Seller *InvoiceSeller `json:"seller,omitempty"` + Customer *InvoiceCustomer `json:"customer,omitempty"` + BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` + ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + TotalAmount *string `json:"total_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` + RemainingAmount *string `json:"remaining_amount,omitempty"` + LineItems []CreditNoteLineItem `json:"line_items,omitempty"` + Discounts []InvoiceDiscount `json:"discounts,omitempty"` + Taxes []InvoiceTax `json:"taxes,omitempty"` + Applications []CreditNoteApplication `json:"applications,omitempty"` + Refunds []InvoiceRefund `json:"refunds,omitempty"` + OriginInvoices []OriginInvoice `json:"origin_invoices,omitempty"` } diff --git a/models/credit_note_1.go b/models/credit_note_1.go index 5a9be55a..a92cbd17 100644 --- a/models/credit_note_1.go +++ b/models/credit_note_1.go @@ -1,235 +1,237 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // CreditNote1 represents a CreditNote1 struct. type CreditNote1 struct { - // Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. - Uid *string `json:"uid,omitempty"` - // ID of the site to which the credit note belongs. - SiteId *int `json:"site_id,omitempty"` - // ID of the customer to which the credit note belongs. - CustomerId *int `json:"customer_id,omitempty"` - // ID of the subscription that generated the credit note. - SubscriptionId *int `json:"subscription_id,omitempty"` - // A unique, identifying string that appears on the credit note and in places it is referenced. - // While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. - Number *string `json:"number,omitempty"` - // A monotonically increasing number assigned to credit notes as they are created. This number is unique within a site and can be used to sort and order credit notes. - SequenceNumber *int `json:"sequence_number,omitempty"` - // Date the credit note was issued to the customer. This is the date that the credit was made available for application, and may come before it is fully applied. - // The format is `"YYYY-MM-DD"`. - IssueDate *time.Time `json:"issue_date,omitempty"` - // Credit notes are applied to invoices to offset invoiced amounts - they reduce the amount due. This field is the date the credit note became fully applied to invoices. - // If the credit note has been partially applied, this field will not have a value until it has been fully applied. - // The format is `"YYYY-MM-DD"`. - AppliedDate *time.Time `json:"applied_date,omitempty"` - // Current status of the credit note. - Status *CreditNoteStatus `json:"status,omitempty"` - // The ISO 4217 currency code (3 character string) representing the currency of the credit note amount fields. - Currency *string `json:"currency,omitempty"` - // The memo printed on credit note, which is a description of the reason for the credit. - Memo *string `json:"memo,omitempty"` - Seller *Seller `json:"seller,omitempty"` - Customer *Customer1 `json:"customer,omitempty"` - BillingAddress *BillingAddress `json:"billing_address,omitempty"` - ShippingAddress *ShippingAddress `json:"shipping_address,omitempty"` - // Subtotal of the credit note, which is the sum of all line items before discounts or taxes. Note that this is a positive amount representing the credit back to the customer. - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - // Total discount applied to the credit note. Note that this is a positive amount representing the discount amount being credited back to the customer (i.e. a credit on an earlier discount). For example, if the original purchase was $1.00 and the original discount was $0.10, a credit of $0.50 of the original purchase (half) would have a discount credit of $0.05 (also half). - DiscountAmount *string `json:"discount_amount,omitempty"` - // Total tax of the credit note. Note that this is a positive amount representing a previously taxex amount being credited back to the customer (i.e. a credit of an earlier tax). For example, if the original purchase was $1.00 and the original tax was $0.10, a credit of $0.50 of the original purchase (half) would also have a tax credit of $0.05 (also half). - TaxAmount *string `json:"tax_amount,omitempty"` - // The credit note total, which is `subtotal_amount - discount_amount + tax_amount`.' - TotalAmount *string `json:"total_amount,omitempty"` - // The amount of the credit note that has already been applied to invoices. - AppliedAmount *string `json:"applied_amount,omitempty"` - // The amount of the credit note remaining to be applied to invoices, which is `total_amount - applied_amount`. - RemainingAmount *string `json:"remaining_amount,omitempty"` - // Line items on the credit note. - LineItems []CreditNoteLineItem `json:"line_items,omitempty"` - Discounts []InvoiceDiscount `json:"discounts,omitempty"` - Taxes []InvoiceTax `json:"taxes,omitempty"` - Applications []CreditNoteApplication `json:"applications,omitempty"` - Refunds []InvoiceRefund `json:"refunds,omitempty"` - // An array of origin invoices for the credit note. Learn more about [Origin Invoice from our docs](https://chargify.zendesk.com/hc/en-us/articles/4407753036699#origin-invoices) - OriginInvoices []OriginInvoice `json:"origin_invoices,omitempty"` + // Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. + Uid *string `json:"uid,omitempty"` + // ID of the site to which the credit note belongs. + SiteId *int `json:"site_id,omitempty"` + // ID of the customer to which the credit note belongs. + CustomerId *int `json:"customer_id,omitempty"` + // ID of the subscription that generated the credit note. + SubscriptionId *int `json:"subscription_id,omitempty"` + // A unique, identifying string that appears on the credit note and in places it is referenced. + // While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. + Number *string `json:"number,omitempty"` + // A monotonically increasing number assigned to credit notes as they are created. This number is unique within a site and can be used to sort and order credit notes. + SequenceNumber *int `json:"sequence_number,omitempty"` + // Date the credit note was issued to the customer. This is the date that the credit was made available for application, and may come before it is fully applied. + // The format is `"YYYY-MM-DD"`. + IssueDate *time.Time `json:"issue_date,omitempty"` + // Credit notes are applied to invoices to offset invoiced amounts - they reduce the amount due. This field is the date the credit note became fully applied to invoices. + // If the credit note has been partially applied, this field will not have a value until it has been fully applied. + // The format is `"YYYY-MM-DD"`. + AppliedDate *time.Time `json:"applied_date,omitempty"` + // Current status of the credit note. + Status *CreditNoteStatus `json:"status,omitempty"` + // The ISO 4217 currency code (3 character string) representing the currency of the credit note amount fields. + Currency *string `json:"currency,omitempty"` + // The memo printed on credit note, which is a description of the reason for the credit. + Memo *string `json:"memo,omitempty"` + Seller *Seller `json:"seller,omitempty"` + Customer *Customer1 `json:"customer,omitempty"` + BillingAddress *BillingAddress `json:"billing_address,omitempty"` + ShippingAddress *ShippingAddress `json:"shipping_address,omitempty"` + // Subtotal of the credit note, which is the sum of all line items before discounts or taxes. Note that this is a positive amount representing the credit back to the customer. + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + // Total discount applied to the credit note. Note that this is a positive amount representing the discount amount being credited back to the customer (i.e. a credit on an earlier discount). For example, if the original purchase was $1.00 and the original discount was $0.10, a credit of $0.50 of the original purchase (half) would have a discount credit of $0.05 (also half). + DiscountAmount *string `json:"discount_amount,omitempty"` + // Total tax of the credit note. Note that this is a positive amount representing a previously taxex amount being credited back to the customer (i.e. a credit of an earlier tax). For example, if the original purchase was $1.00 and the original tax was $0.10, a credit of $0.50 of the original purchase (half) would also have a tax credit of $0.05 (also half). + TaxAmount *string `json:"tax_amount,omitempty"` + // The credit note total, which is `subtotal_amount - discount_amount + tax_amount`.' + TotalAmount *string `json:"total_amount,omitempty"` + // The amount of the credit note that has already been applied to invoices. + AppliedAmount *string `json:"applied_amount,omitempty"` + // The amount of the credit note remaining to be applied to invoices, which is `total_amount - applied_amount`. + RemainingAmount *string `json:"remaining_amount,omitempty"` + // Line items on the credit note. + LineItems []CreditNoteLineItem `json:"line_items,omitempty"` + Discounts []InvoiceDiscount `json:"discounts,omitempty"` + Taxes []InvoiceTax `json:"taxes,omitempty"` + Applications []CreditNoteApplication `json:"applications,omitempty"` + Refunds []InvoiceRefund `json:"refunds,omitempty"` + // An array of origin invoices for the credit note. Learn more about [Origin Invoice from our docs](https://chargify.zendesk.com/hc/en-us/articles/4407753036699#origin-invoices) + OriginInvoices []OriginInvoice `json:"origin_invoices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreditNote1. +// MarshalJSON implements the json.Marshaler interface for CreditNote1. // It customizes the JSON marshaling process for CreditNote1 objects. func (c *CreditNote1) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreditNote1 object to a map representation for JSON marshaling. func (c *CreditNote1) toMap() map[string]any { - structMap := make(map[string]any) - if c.Uid != nil { - structMap["uid"] = c.Uid - } - if c.SiteId != nil { - structMap["site_id"] = c.SiteId - } - if c.CustomerId != nil { - structMap["customer_id"] = c.CustomerId - } - if c.SubscriptionId != nil { - structMap["subscription_id"] = c.SubscriptionId - } - if c.Number != nil { - structMap["number"] = c.Number - } - if c.SequenceNumber != nil { - structMap["sequence_number"] = c.SequenceNumber - } - if c.IssueDate != nil { - structMap["issue_date"] = c.IssueDate.Format(DEFAULT_DATE) - } - if c.AppliedDate != nil { - structMap["applied_date"] = c.AppliedDate.Format(DEFAULT_DATE) - } - if c.Status != nil { - structMap["status"] = c.Status - } - if c.Currency != nil { - structMap["currency"] = c.Currency - } - if c.Memo != nil { - structMap["memo"] = c.Memo - } - if c.Seller != nil { - structMap["seller"] = c.Seller.toMap() - } - if c.Customer != nil { - structMap["customer"] = c.Customer.toMap() - } - if c.BillingAddress != nil { - structMap["billing_address"] = c.BillingAddress.toMap() - } - if c.ShippingAddress != nil { - structMap["shipping_address"] = c.ShippingAddress.toMap() - } - if c.SubtotalAmount != nil { - structMap["subtotal_amount"] = c.SubtotalAmount - } - if c.DiscountAmount != nil { - structMap["discount_amount"] = c.DiscountAmount - } - if c.TaxAmount != nil { - structMap["tax_amount"] = c.TaxAmount - } - if c.TotalAmount != nil { - structMap["total_amount"] = c.TotalAmount - } - if c.AppliedAmount != nil { - structMap["applied_amount"] = c.AppliedAmount - } - if c.RemainingAmount != nil { - structMap["remaining_amount"] = c.RemainingAmount - } - if c.LineItems != nil { - structMap["line_items"] = c.LineItems - } - if c.Discounts != nil { - structMap["discounts"] = c.Discounts - } - if c.Taxes != nil { - structMap["taxes"] = c.Taxes - } - if c.Applications != nil { - structMap["applications"] = c.Applications - } - if c.Refunds != nil { - structMap["refunds"] = c.Refunds - } - if c.OriginInvoices != nil { - structMap["origin_invoices"] = c.OriginInvoices - } - return structMap + structMap := make(map[string]any) + if c.Uid != nil { + structMap["uid"] = c.Uid + } + if c.SiteId != nil { + structMap["site_id"] = c.SiteId + } + if c.CustomerId != nil { + structMap["customer_id"] = c.CustomerId + } + if c.SubscriptionId != nil { + structMap["subscription_id"] = c.SubscriptionId + } + if c.Number != nil { + structMap["number"] = c.Number + } + if c.SequenceNumber != nil { + structMap["sequence_number"] = c.SequenceNumber + } + if c.IssueDate != nil { + structMap["issue_date"] = c.IssueDate.Format(DEFAULT_DATE) + } + if c.AppliedDate != nil { + structMap["applied_date"] = c.AppliedDate.Format(DEFAULT_DATE) + } + if c.Status != nil { + structMap["status"] = c.Status + } + if c.Currency != nil { + structMap["currency"] = c.Currency + } + if c.Memo != nil { + structMap["memo"] = c.Memo + } + if c.Seller != nil { + structMap["seller"] = c.Seller.toMap() + } + if c.Customer != nil { + structMap["customer"] = c.Customer.toMap() + } + if c.BillingAddress != nil { + structMap["billing_address"] = c.BillingAddress.toMap() + } + if c.ShippingAddress != nil { + structMap["shipping_address"] = c.ShippingAddress.toMap() + } + if c.SubtotalAmount != nil { + structMap["subtotal_amount"] = c.SubtotalAmount + } + if c.DiscountAmount != nil { + structMap["discount_amount"] = c.DiscountAmount + } + if c.TaxAmount != nil { + structMap["tax_amount"] = c.TaxAmount + } + if c.TotalAmount != nil { + structMap["total_amount"] = c.TotalAmount + } + if c.AppliedAmount != nil { + structMap["applied_amount"] = c.AppliedAmount + } + if c.RemainingAmount != nil { + structMap["remaining_amount"] = c.RemainingAmount + } + if c.LineItems != nil { + structMap["line_items"] = c.LineItems + } + if c.Discounts != nil { + structMap["discounts"] = c.Discounts + } + if c.Taxes != nil { + structMap["taxes"] = c.Taxes + } + if c.Applications != nil { + structMap["applications"] = c.Applications + } + if c.Refunds != nil { + structMap["refunds"] = c.Refunds + } + if c.OriginInvoices != nil { + structMap["origin_invoices"] = c.OriginInvoices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreditNote1. +// UnmarshalJSON implements the json.Unmarshaler interface for CreditNote1. // It customizes the JSON unmarshaling process for CreditNote1 objects. func (c *CreditNote1) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - SiteId *int `json:"site_id,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - Number *string `json:"number,omitempty"` - SequenceNumber *int `json:"sequence_number,omitempty"` - IssueDate *string `json:"issue_date,omitempty"` - AppliedDate *string `json:"applied_date,omitempty"` - Status *CreditNoteStatus `json:"status,omitempty"` - Currency *string `json:"currency,omitempty"` - Memo *string `json:"memo,omitempty"` - Seller *Seller `json:"seller,omitempty"` - Customer *Customer1 `json:"customer,omitempty"` - BillingAddress *BillingAddress `json:"billing_address,omitempty"` - ShippingAddress *ShippingAddress `json:"shipping_address,omitempty"` - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - TotalAmount *string `json:"total_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - RemainingAmount *string `json:"remaining_amount,omitempty"` - LineItems []CreditNoteLineItem `json:"line_items,omitempty"` - Discounts []InvoiceDiscount `json:"discounts,omitempty"` - Taxes []InvoiceTax `json:"taxes,omitempty"` - Applications []CreditNoteApplication `json:"applications,omitempty"` - Refunds []InvoiceRefund `json:"refunds,omitempty"` - OriginInvoices []OriginInvoice `json:"origin_invoices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Uid = temp.Uid - c.SiteId = temp.SiteId - c.CustomerId = temp.CustomerId - c.SubscriptionId = temp.SubscriptionId - c.Number = temp.Number - c.SequenceNumber = temp.SequenceNumber - if temp.IssueDate != nil { - IssueDateVal, err := time.Parse(DEFAULT_DATE, *temp.IssueDate) - if err != nil { - log.Fatalf("Cannot Parse issue_date as % s format.", DEFAULT_DATE) - } - c.IssueDate = &IssueDateVal - } - if temp.AppliedDate != nil { - AppliedDateVal, err := time.Parse(DEFAULT_DATE, *temp.AppliedDate) - if err != nil { - log.Fatalf("Cannot Parse applied_date as % s format.", DEFAULT_DATE) - } - c.AppliedDate = &AppliedDateVal - } - c.Status = temp.Status - c.Currency = temp.Currency - c.Memo = temp.Memo - c.Seller = temp.Seller - c.Customer = temp.Customer - c.BillingAddress = temp.BillingAddress - c.ShippingAddress = temp.ShippingAddress - c.SubtotalAmount = temp.SubtotalAmount - c.DiscountAmount = temp.DiscountAmount - c.TaxAmount = temp.TaxAmount - c.TotalAmount = temp.TotalAmount - c.AppliedAmount = temp.AppliedAmount - c.RemainingAmount = temp.RemainingAmount - c.LineItems = temp.LineItems - c.Discounts = temp.Discounts - c.Taxes = temp.Taxes - c.Applications = temp.Applications - c.Refunds = temp.Refunds - c.OriginInvoices = temp.OriginInvoices - return nil + var temp creditNote1 + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Uid = temp.Uid + c.SiteId = temp.SiteId + c.CustomerId = temp.CustomerId + c.SubscriptionId = temp.SubscriptionId + c.Number = temp.Number + c.SequenceNumber = temp.SequenceNumber + if temp.IssueDate != nil { + IssueDateVal, err := time.Parse(DEFAULT_DATE, *temp.IssueDate) + if err != nil { + log.Fatalf("Cannot Parse issue_date as % s format.", DEFAULT_DATE) + } + c.IssueDate = &IssueDateVal + } + if temp.AppliedDate != nil { + AppliedDateVal, err := time.Parse(DEFAULT_DATE, *temp.AppliedDate) + if err != nil { + log.Fatalf("Cannot Parse applied_date as % s format.", DEFAULT_DATE) + } + c.AppliedDate = &AppliedDateVal + } + c.Status = temp.Status + c.Currency = temp.Currency + c.Memo = temp.Memo + c.Seller = temp.Seller + c.Customer = temp.Customer + c.BillingAddress = temp.BillingAddress + c.ShippingAddress = temp.ShippingAddress + c.SubtotalAmount = temp.SubtotalAmount + c.DiscountAmount = temp.DiscountAmount + c.TaxAmount = temp.TaxAmount + c.TotalAmount = temp.TotalAmount + c.AppliedAmount = temp.AppliedAmount + c.RemainingAmount = temp.RemainingAmount + c.LineItems = temp.LineItems + c.Discounts = temp.Discounts + c.Taxes = temp.Taxes + c.Applications = temp.Applications + c.Refunds = temp.Refunds + c.OriginInvoices = temp.OriginInvoices + return nil +} + +// TODO +type creditNote1 struct { + Uid *string `json:"uid,omitempty"` + SiteId *int `json:"site_id,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + Number *string `json:"number,omitempty"` + SequenceNumber *int `json:"sequence_number,omitempty"` + IssueDate *string `json:"issue_date,omitempty"` + AppliedDate *string `json:"applied_date,omitempty"` + Status *CreditNoteStatus `json:"status,omitempty"` + Currency *string `json:"currency,omitempty"` + Memo *string `json:"memo,omitempty"` + Seller *Seller `json:"seller,omitempty"` + Customer *Customer1 `json:"customer,omitempty"` + BillingAddress *BillingAddress `json:"billing_address,omitempty"` + ShippingAddress *ShippingAddress `json:"shipping_address,omitempty"` + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + TotalAmount *string `json:"total_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` + RemainingAmount *string `json:"remaining_amount,omitempty"` + LineItems []CreditNoteLineItem `json:"line_items,omitempty"` + Discounts []InvoiceDiscount `json:"discounts,omitempty"` + Taxes []InvoiceTax `json:"taxes,omitempty"` + Applications []CreditNoteApplication `json:"applications,omitempty"` + Refunds []InvoiceRefund `json:"refunds,omitempty"` + OriginInvoices []OriginInvoice `json:"origin_invoices,omitempty"` } diff --git a/models/credit_note_application.go b/models/credit_note_application.go index 6f6936c7..7a926fce 100644 --- a/models/credit_note_application.go +++ b/models/credit_note_application.go @@ -1,74 +1,76 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // CreditNoteApplication represents a CreditNoteApplication struct. type CreditNoteApplication struct { - Uid *string `json:"uid,omitempty"` - TransactionTime *time.Time `json:"transaction_time,omitempty"` - InvoiceUid *string `json:"invoice_uid,omitempty"` - Memo *string `json:"memo,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` + Uid *string `json:"uid,omitempty"` + TransactionTime *time.Time `json:"transaction_time,omitempty"` + InvoiceUid *string `json:"invoice_uid,omitempty"` + Memo *string `json:"memo,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreditNoteApplication. +// MarshalJSON implements the json.Marshaler interface for CreditNoteApplication. // It customizes the JSON marshaling process for CreditNoteApplication objects. func (c *CreditNoteApplication) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreditNoteApplication object to a map representation for JSON marshaling. func (c *CreditNoteApplication) toMap() map[string]any { - structMap := make(map[string]any) - if c.Uid != nil { - structMap["uid"] = c.Uid - } - if c.TransactionTime != nil { - structMap["transaction_time"] = c.TransactionTime.Format(time.RFC3339) - } - if c.InvoiceUid != nil { - structMap["invoice_uid"] = c.InvoiceUid - } - if c.Memo != nil { - structMap["memo"] = c.Memo - } - if c.AppliedAmount != nil { - structMap["applied_amount"] = c.AppliedAmount - } - return structMap + structMap := make(map[string]any) + if c.Uid != nil { + structMap["uid"] = c.Uid + } + if c.TransactionTime != nil { + structMap["transaction_time"] = c.TransactionTime.Format(time.RFC3339) + } + if c.InvoiceUid != nil { + structMap["invoice_uid"] = c.InvoiceUid + } + if c.Memo != nil { + structMap["memo"] = c.Memo + } + if c.AppliedAmount != nil { + structMap["applied_amount"] = c.AppliedAmount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreditNoteApplication. +// UnmarshalJSON implements the json.Unmarshaler interface for CreditNoteApplication. // It customizes the JSON unmarshaling process for CreditNoteApplication objects. func (c *CreditNoteApplication) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - TransactionTime *string `json:"transaction_time,omitempty"` - InvoiceUid *string `json:"invoice_uid,omitempty"` - Memo *string `json:"memo,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Uid = temp.Uid - if temp.TransactionTime != nil { - TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) - if err != nil { - log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) - } - c.TransactionTime = &TransactionTimeVal - } - c.InvoiceUid = temp.InvoiceUid - c.Memo = temp.Memo - c.AppliedAmount = temp.AppliedAmount - return nil + var temp creditNoteApplication + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Uid = temp.Uid + if temp.TransactionTime != nil { + TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) + if err != nil { + log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) + } + c.TransactionTime = &TransactionTimeVal + } + c.InvoiceUid = temp.InvoiceUid + c.Memo = temp.Memo + c.AppliedAmount = temp.AppliedAmount + return nil +} + +// TODO +type creditNoteApplication struct { + Uid *string `json:"uid,omitempty"` + TransactionTime *string `json:"transaction_time,omitempty"` + InvoiceUid *string `json:"invoice_uid,omitempty"` + Memo *string `json:"memo,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` } diff --git a/models/credit_note_line_item.go b/models/credit_note_line_item.go index 84ddc1e9..87a74209 100644 --- a/models/credit_note_line_item.go +++ b/models/credit_note_line_item.go @@ -1,181 +1,195 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // CreditNoteLineItem represents a CreditNoteLineItem struct. type CreditNoteLineItem struct { - // Unique identifier for the line item. Useful when cross-referencing the line against individual discounts in the `discounts` or `taxes` lists. - Uid *string `json:"uid,omitempty"` - // A short descriptor for the credit given by this line. - Title *string `json:"title,omitempty"` - // Detailed description for the credit given by this line. May include proration details in plain text. - // Note: this string may contain line breaks that are hints for the best display format on the credit note. - Description *string `json:"description,omitempty"` - // The quantity or count of units credited by the line item. - // This is a decimal number represented as a string. (See "About Decimal Numbers".) - Quantity *string `json:"quantity,omitempty"` - // The price per unit for the line item. - // When tiered pricing was used (i.e. not every unit was actually priced at the same price) this will be the blended average cost per unit and the `tiered_unit_price` field will be set to `true`. - UnitPrice *string `json:"unit_price,omitempty"` - // The line subtotal, generally calculated as `quantity * unit_price`. This is the canonical amount of record for the line - when rounding differences are in play, `subtotal_amount` takes precedence over the value derived from `quantity * unit_price` (which may not have the proper precision to exactly equal this amount). - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - // The approximate discount of just this line. - // The value is approximated in cases where rounding errors make it difficult to apportion exactly a total discount among many lines. Several lines may have been summed prior to applying the discount to arrive at `discount_amount` for the invoice - backing that out to the discount on a single line may introduce rounding or precision errors. - DiscountAmount *string `json:"discount_amount,omitempty"` - // The approximate tax of just this line. - // The value is approximated in cases where rounding errors make it difficult to apportion exactly a total tax among many lines. Several lines may have been summed prior to applying the tax rate to arrive at `tax_amount` for the invoice - backing that out to the tax on a single line may introduce rounding or precision errors. - TaxAmount *string `json:"tax_amount,omitempty"` - // The non-canonical total amount for the line. - // `subtotal_amount` is the canonical amount for a line. The invoice `total_amount` is derived from the sum of the line `subtotal_amount`s and discounts or taxes applied thereafter. Therefore, due to rounding or precision errors, the sum of line `total_amount`s may not equal the invoice `total_amount`. - TotalAmount *string `json:"total_amount,omitempty"` - // When `true`, indicates that the actual pricing scheme for the line was tiered, so the `unit_price` shown is the blended average for all units. - TieredUnitPrice *bool `json:"tiered_unit_price,omitempty"` - // Start date for the period credited by this line. The format is `"YYYY-MM-DD"`. - PeriodRangeStart *time.Time `json:"period_range_start,omitempty"` - // End date for the period credited by this line. The format is `"YYYY-MM-DD"`. - PeriodRangeEnd *time.Time `json:"period_range_end,omitempty"` - // The ID of the product being credited. - // This may be set even for component credits, so true product-only (non-component) credits will also have a nil `component_id`. - ProductId *int `json:"product_id,omitempty"` - // The version of the product being credited. - ProductVersion *int `json:"product_version,omitempty"` - // The ID of the component being credited. Will be `nil` for non-component credits. - ComponentId Optional[int] `json:"component_id"` - // The price point ID of the component being credited. Will be `nil` for non-component credits. - PricePointId Optional[int] `json:"price_point_id"` - BillingScheduleItemId Optional[int] `json:"billing_schedule_item_id"` - CustomItem *bool `json:"custom_item,omitempty"` + // Unique identifier for the line item. Useful when cross-referencing the line against individual discounts in the `discounts` or `taxes` lists. + Uid *string `json:"uid,omitempty"` + // A short descriptor for the credit given by this line. + Title *string `json:"title,omitempty"` + // Detailed description for the credit given by this line. May include proration details in plain text. + // Note: this string may contain line breaks that are hints for the best display format on the credit note. + Description *string `json:"description,omitempty"` + // The quantity or count of units credited by the line item. + // This is a decimal number represented as a string. (See "About Decimal Numbers".) + Quantity *string `json:"quantity,omitempty"` + // The price per unit for the line item. + // When tiered pricing was used (i.e. not every unit was actually priced at the same price) this will be the blended average cost per unit and the `tiered_unit_price` field will be set to `true`. + UnitPrice *string `json:"unit_price,omitempty"` + // The line subtotal, generally calculated as `quantity * unit_price`. This is the canonical amount of record for the line - when rounding differences are in play, `subtotal_amount` takes precedence over the value derived from `quantity * unit_price` (which may not have the proper precision to exactly equal this amount). + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + // The approximate discount of just this line. + // The value is approximated in cases where rounding errors make it difficult to apportion exactly a total discount among many lines. Several lines may have been summed prior to applying the discount to arrive at `discount_amount` for the invoice - backing that out to the discount on a single line may introduce rounding or precision errors. + DiscountAmount *string `json:"discount_amount,omitempty"` + // The approximate tax of just this line. + // The value is approximated in cases where rounding errors make it difficult to apportion exactly a total tax among many lines. Several lines may have been summed prior to applying the tax rate to arrive at `tax_amount` for the invoice - backing that out to the tax on a single line may introduce rounding or precision errors. + TaxAmount *string `json:"tax_amount,omitempty"` + // The non-canonical total amount for the line. + // `subtotal_amount` is the canonical amount for a line. The invoice `total_amount` is derived from the sum of the line `subtotal_amount`s and discounts or taxes applied thereafter. Therefore, due to rounding or precision errors, the sum of line `total_amount`s may not equal the invoice `total_amount`. + TotalAmount *string `json:"total_amount,omitempty"` + // When `true`, indicates that the actual pricing scheme for the line was tiered, so the `unit_price` shown is the blended average for all units. + TieredUnitPrice *bool `json:"tiered_unit_price,omitempty"` + // Start date for the period credited by this line. The format is `"YYYY-MM-DD"`. + PeriodRangeStart *time.Time `json:"period_range_start,omitempty"` + // End date for the period credited by this line. The format is `"YYYY-MM-DD"`. + PeriodRangeEnd *time.Time `json:"period_range_end,omitempty"` + // The ID of the product being credited. + // This may be set even for component credits, so true product-only (non-component) credits will also have a nil `component_id`. + ProductId *int `json:"product_id,omitempty"` + // The version of the product being credited. + ProductVersion *int `json:"product_version,omitempty"` + // The ID of the component being credited. Will be `nil` for non-component credits. + ComponentId Optional[int] `json:"component_id"` + // The price point ID of the component being credited. Will be `nil` for non-component credits. + PricePointId Optional[int] `json:"price_point_id"` + BillingScheduleItemId Optional[int] `json:"billing_schedule_item_id"` + CustomItem *bool `json:"custom_item,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CreditNoteLineItem. +// MarshalJSON implements the json.Marshaler interface for CreditNoteLineItem. // It customizes the JSON marshaling process for CreditNoteLineItem objects. func (c *CreditNoteLineItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreditNoteLineItem object to a map representation for JSON marshaling. func (c *CreditNoteLineItem) toMap() map[string]any { - structMap := make(map[string]any) - if c.Uid != nil { - structMap["uid"] = c.Uid - } - if c.Title != nil { - structMap["title"] = c.Title - } - if c.Description != nil { - structMap["description"] = c.Description - } - if c.Quantity != nil { - structMap["quantity"] = c.Quantity - } - if c.UnitPrice != nil { - structMap["unit_price"] = c.UnitPrice - } - if c.SubtotalAmount != nil { - structMap["subtotal_amount"] = c.SubtotalAmount - } - if c.DiscountAmount != nil { - structMap["discount_amount"] = c.DiscountAmount - } - if c.TaxAmount != nil { - structMap["tax_amount"] = c.TaxAmount - } - if c.TotalAmount != nil { - structMap["total_amount"] = c.TotalAmount - } - if c.TieredUnitPrice != nil { - structMap["tiered_unit_price"] = c.TieredUnitPrice - } - if c.PeriodRangeStart != nil { - structMap["period_range_start"] = c.PeriodRangeStart.Format(DEFAULT_DATE) - } - if c.PeriodRangeEnd != nil { - structMap["period_range_end"] = c.PeriodRangeEnd.Format(DEFAULT_DATE) - } - if c.ProductId != nil { - structMap["product_id"] = c.ProductId - } - if c.ProductVersion != nil { - structMap["product_version"] = c.ProductVersion - } - if c.ComponentId.IsValueSet() { - structMap["component_id"] = c.ComponentId.Value() - } - if c.PricePointId.IsValueSet() { - structMap["price_point_id"] = c.PricePointId.Value() - } - if c.BillingScheduleItemId.IsValueSet() { - structMap["billing_schedule_item_id"] = c.BillingScheduleItemId.Value() - } - if c.CustomItem != nil { - structMap["custom_item"] = c.CustomItem - } - return structMap + structMap := make(map[string]any) + if c.Uid != nil { + structMap["uid"] = c.Uid + } + if c.Title != nil { + structMap["title"] = c.Title + } + if c.Description != nil { + structMap["description"] = c.Description + } + if c.Quantity != nil { + structMap["quantity"] = c.Quantity + } + if c.UnitPrice != nil { + structMap["unit_price"] = c.UnitPrice + } + if c.SubtotalAmount != nil { + structMap["subtotal_amount"] = c.SubtotalAmount + } + if c.DiscountAmount != nil { + structMap["discount_amount"] = c.DiscountAmount + } + if c.TaxAmount != nil { + structMap["tax_amount"] = c.TaxAmount + } + if c.TotalAmount != nil { + structMap["total_amount"] = c.TotalAmount + } + if c.TieredUnitPrice != nil { + structMap["tiered_unit_price"] = c.TieredUnitPrice + } + if c.PeriodRangeStart != nil { + structMap["period_range_start"] = c.PeriodRangeStart.Format(DEFAULT_DATE) + } + if c.PeriodRangeEnd != nil { + structMap["period_range_end"] = c.PeriodRangeEnd.Format(DEFAULT_DATE) + } + if c.ProductId != nil { + structMap["product_id"] = c.ProductId + } + if c.ProductVersion != nil { + structMap["product_version"] = c.ProductVersion + } + if c.ComponentId.IsValueSet() { + if c.ComponentId.Value() != nil { + structMap["component_id"] = c.ComponentId.Value() + } else { + structMap["component_id"] = nil + } + } + if c.PricePointId.IsValueSet() { + if c.PricePointId.Value() != nil { + structMap["price_point_id"] = c.PricePointId.Value() + } else { + structMap["price_point_id"] = nil + } + } + if c.BillingScheduleItemId.IsValueSet() { + if c.BillingScheduleItemId.Value() != nil { + structMap["billing_schedule_item_id"] = c.BillingScheduleItemId.Value() + } else { + structMap["billing_schedule_item_id"] = nil + } + } + if c.CustomItem != nil { + structMap["custom_item"] = c.CustomItem + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreditNoteLineItem. +// UnmarshalJSON implements the json.Unmarshaler interface for CreditNoteLineItem. // It customizes the JSON unmarshaling process for CreditNoteLineItem objects. func (c *CreditNoteLineItem) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Title *string `json:"title,omitempty"` - Description *string `json:"description,omitempty"` - Quantity *string `json:"quantity,omitempty"` - UnitPrice *string `json:"unit_price,omitempty"` - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - TotalAmount *string `json:"total_amount,omitempty"` - TieredUnitPrice *bool `json:"tiered_unit_price,omitempty"` - PeriodRangeStart *string `json:"period_range_start,omitempty"` - PeriodRangeEnd *string `json:"period_range_end,omitempty"` - ProductId *int `json:"product_id,omitempty"` - ProductVersion *int `json:"product_version,omitempty"` - ComponentId Optional[int] `json:"component_id"` - PricePointId Optional[int] `json:"price_point_id"` - BillingScheduleItemId Optional[int] `json:"billing_schedule_item_id"` - CustomItem *bool `json:"custom_item,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Uid = temp.Uid - c.Title = temp.Title - c.Description = temp.Description - c.Quantity = temp.Quantity - c.UnitPrice = temp.UnitPrice - c.SubtotalAmount = temp.SubtotalAmount - c.DiscountAmount = temp.DiscountAmount - c.TaxAmount = temp.TaxAmount - c.TotalAmount = temp.TotalAmount - c.TieredUnitPrice = temp.TieredUnitPrice - if temp.PeriodRangeStart != nil { - PeriodRangeStartVal, err := time.Parse(DEFAULT_DATE, *temp.PeriodRangeStart) - if err != nil { - log.Fatalf("Cannot Parse period_range_start as % s format.", DEFAULT_DATE) - } - c.PeriodRangeStart = &PeriodRangeStartVal - } - if temp.PeriodRangeEnd != nil { - PeriodRangeEndVal, err := time.Parse(DEFAULT_DATE, *temp.PeriodRangeEnd) - if err != nil { - log.Fatalf("Cannot Parse period_range_end as % s format.", DEFAULT_DATE) - } - c.PeriodRangeEnd = &PeriodRangeEndVal - } - c.ProductId = temp.ProductId - c.ProductVersion = temp.ProductVersion - c.ComponentId = temp.ComponentId - c.PricePointId = temp.PricePointId - c.BillingScheduleItemId = temp.BillingScheduleItemId - c.CustomItem = temp.CustomItem - return nil + var temp creditNoteLineItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Uid = temp.Uid + c.Title = temp.Title + c.Description = temp.Description + c.Quantity = temp.Quantity + c.UnitPrice = temp.UnitPrice + c.SubtotalAmount = temp.SubtotalAmount + c.DiscountAmount = temp.DiscountAmount + c.TaxAmount = temp.TaxAmount + c.TotalAmount = temp.TotalAmount + c.TieredUnitPrice = temp.TieredUnitPrice + if temp.PeriodRangeStart != nil { + PeriodRangeStartVal, err := time.Parse(DEFAULT_DATE, *temp.PeriodRangeStart) + if err != nil { + log.Fatalf("Cannot Parse period_range_start as % s format.", DEFAULT_DATE) + } + c.PeriodRangeStart = &PeriodRangeStartVal + } + if temp.PeriodRangeEnd != nil { + PeriodRangeEndVal, err := time.Parse(DEFAULT_DATE, *temp.PeriodRangeEnd) + if err != nil { + log.Fatalf("Cannot Parse period_range_end as % s format.", DEFAULT_DATE) + } + c.PeriodRangeEnd = &PeriodRangeEndVal + } + c.ProductId = temp.ProductId + c.ProductVersion = temp.ProductVersion + c.ComponentId = temp.ComponentId + c.PricePointId = temp.PricePointId + c.BillingScheduleItemId = temp.BillingScheduleItemId + c.CustomItem = temp.CustomItem + return nil +} + +// TODO +type creditNoteLineItem struct { + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + Description *string `json:"description,omitempty"` + Quantity *string `json:"quantity,omitempty"` + UnitPrice *string `json:"unit_price,omitempty"` + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + TotalAmount *string `json:"total_amount,omitempty"` + TieredUnitPrice *bool `json:"tiered_unit_price,omitempty"` + PeriodRangeStart *string `json:"period_range_start,omitempty"` + PeriodRangeEnd *string `json:"period_range_end,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductVersion *int `json:"product_version,omitempty"` + ComponentId Optional[int] `json:"component_id"` + PricePointId Optional[int] `json:"price_point_id"` + BillingScheduleItemId Optional[int] `json:"billing_schedule_item_id"` + CustomItem *bool `json:"custom_item,omitempty"` } diff --git a/models/credit_scheme_request.go b/models/credit_scheme_request.go index 5484f2a4..69aace8e 100644 --- a/models/credit_scheme_request.go +++ b/models/credit_scheme_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CreditSchemeRequest represents a CreditSchemeRequest struct. type CreditSchemeRequest struct { - CreditScheme CreditScheme `json:"credit_scheme"` + CreditScheme CreditScheme `json:"credit_scheme"` } -// MarshalJSON implements the json.Marshaler interface for CreditSchemeRequest. +// MarshalJSON implements the json.Marshaler interface for CreditSchemeRequest. // It customizes the JSON marshaling process for CreditSchemeRequest objects. func (c *CreditSchemeRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CreditSchemeRequest object to a map representation for JSON marshaling. func (c *CreditSchemeRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["credit_scheme"] = c.CreditScheme - return structMap + structMap := make(map[string]any) + structMap["credit_scheme"] = c.CreditScheme + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CreditSchemeRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for CreditSchemeRequest. // It customizes the JSON unmarshaling process for CreditSchemeRequest objects. func (c *CreditSchemeRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - CreditScheme CreditScheme `json:"credit_scheme"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.CreditScheme = temp.CreditScheme - return nil + var temp creditSchemeRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.CreditScheme = *temp.CreditScheme + return nil +} + +// TODO +type creditSchemeRequest struct { + CreditScheme *CreditScheme `json:"credit_scheme"` +} + +func (c *creditSchemeRequest) validate() error { + var errs []string + if c.CreditScheme == nil { + errs = append(errs, "required field `credit_scheme` is missing for type `Credit Scheme Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/currency_price.go b/models/currency_price.go index 89b4305d..f35c1ba4 100644 --- a/models/currency_price.go +++ b/models/currency_price.go @@ -1,73 +1,75 @@ package models import ( - "encoding/json" + "encoding/json" ) // CurrencyPrice represents a CurrencyPrice struct. type CurrencyPrice struct { - Id *int `json:"id,omitempty"` - Currency *string `json:"currency,omitempty"` - Price *float64 `json:"price,omitempty"` - FormattedPrice *string `json:"formatted_price,omitempty"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - // Role for the price. - Role *CurrencyPriceRole `json:"role,omitempty"` + Id *int `json:"id,omitempty"` + Currency *string `json:"currency,omitempty"` + Price *float64 `json:"price,omitempty"` + FormattedPrice *string `json:"formatted_price,omitempty"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + // Role for the price. + Role *CurrencyPriceRole `json:"role,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for CurrencyPrice. +// MarshalJSON implements the json.Marshaler interface for CurrencyPrice. // It customizes the JSON marshaling process for CurrencyPrice objects. func (c *CurrencyPrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CurrencyPrice object to a map representation for JSON marshaling. func (c *CurrencyPrice) toMap() map[string]any { - structMap := make(map[string]any) - if c.Id != nil { - structMap["id"] = c.Id - } - if c.Currency != nil { - structMap["currency"] = c.Currency - } - if c.Price != nil { - structMap["price"] = c.Price - } - if c.FormattedPrice != nil { - structMap["formatted_price"] = c.FormattedPrice - } - if c.ProductPricePointId != nil { - structMap["product_price_point_id"] = c.ProductPricePointId - } - if c.Role != nil { - structMap["role"] = c.Role - } - return structMap + structMap := make(map[string]any) + if c.Id != nil { + structMap["id"] = c.Id + } + if c.Currency != nil { + structMap["currency"] = c.Currency + } + if c.Price != nil { + structMap["price"] = c.Price + } + if c.FormattedPrice != nil { + structMap["formatted_price"] = c.FormattedPrice + } + if c.ProductPricePointId != nil { + structMap["product_price_point_id"] = c.ProductPricePointId + } + if c.Role != nil { + structMap["role"] = c.Role + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CurrencyPrice. +// UnmarshalJSON implements the json.Unmarshaler interface for CurrencyPrice. // It customizes the JSON unmarshaling process for CurrencyPrice objects. func (c *CurrencyPrice) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Currency *string `json:"currency,omitempty"` - Price *float64 `json:"price,omitempty"` - FormattedPrice *string `json:"formatted_price,omitempty"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - Role *CurrencyPriceRole `json:"role,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Id = temp.Id - c.Currency = temp.Currency - c.Price = temp.Price - c.FormattedPrice = temp.FormattedPrice - c.ProductPricePointId = temp.ProductPricePointId - c.Role = temp.Role - return nil + var temp currencyPrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Id = temp.Id + c.Currency = temp.Currency + c.Price = temp.Price + c.FormattedPrice = temp.FormattedPrice + c.ProductPricePointId = temp.ProductPricePointId + c.Role = temp.Role + return nil +} + +// TODO +type currencyPrice struct { + Id *int `json:"id,omitempty"` + Currency *string `json:"currency,omitempty"` + Price *float64 `json:"price,omitempty"` + FormattedPrice *string `json:"formatted_price,omitempty"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + Role *CurrencyPriceRole `json:"role,omitempty"` } diff --git a/models/currency_prices_response.go b/models/currency_prices_response.go index 147fccb3..26641a86 100644 --- a/models/currency_prices_response.go +++ b/models/currency_prices_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CurrencyPricesResponse represents a CurrencyPricesResponse struct. type CurrencyPricesResponse struct { - CurrencyPrices []CurrencyPrice `json:"currency_prices"` + CurrencyPrices []CurrencyPrice `json:"currency_prices"` } -// MarshalJSON implements the json.Marshaler interface for CurrencyPricesResponse. +// MarshalJSON implements the json.Marshaler interface for CurrencyPricesResponse. // It customizes the JSON marshaling process for CurrencyPricesResponse objects. func (c *CurrencyPricesResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CurrencyPricesResponse object to a map representation for JSON marshaling. func (c *CurrencyPricesResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["currency_prices"] = c.CurrencyPrices - return structMap + structMap := make(map[string]any) + structMap["currency_prices"] = c.CurrencyPrices + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CurrencyPricesResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for CurrencyPricesResponse. // It customizes the JSON unmarshaling process for CurrencyPricesResponse objects. func (c *CurrencyPricesResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - CurrencyPrices []CurrencyPrice `json:"currency_prices"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.CurrencyPrices = temp.CurrencyPrices - return nil + var temp currencyPricesResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.CurrencyPrices = *temp.CurrencyPrices + return nil +} + +// TODO +type currencyPricesResponse struct { + CurrencyPrices *[]CurrencyPrice `json:"currency_prices"` +} + +func (c *currencyPricesResponse) validate() error { + var errs []string + if c.CurrencyPrices == nil { + errs = append(errs, "required field `currency_prices` is missing for type `Currency Prices Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/custom_field_value_change.go b/models/custom_field_value_change.go new file mode 100644 index 00000000..2b6d01e4 --- /dev/null +++ b/models/custom_field_value_change.go @@ -0,0 +1,104 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CustomFieldValueChange represents a CustomFieldValueChange struct. +type CustomFieldValueChange struct { + EventType string `json:"event_type"` + MetafieldName string `json:"metafield_name"` + MetafieldId int `json:"metafield_id"` + OldValue *string `json:"old_value"` + NewValue *string `json:"new_value"` + ResourceType string `json:"resource_type"` + ResourceId int `json:"resource_id"` +} + +// MarshalJSON implements the json.Marshaler interface for CustomFieldValueChange. +// It customizes the JSON marshaling process for CustomFieldValueChange objects. +func (c *CustomFieldValueChange) MarshalJSON() ( + []byte, + error) { + return json.Marshal(c.toMap()) +} + +// toMap converts the CustomFieldValueChange object to a map representation for JSON marshaling. +func (c *CustomFieldValueChange) toMap() map[string]any { + structMap := make(map[string]any) + structMap["event_type"] = c.EventType + structMap["metafield_name"] = c.MetafieldName + structMap["metafield_id"] = c.MetafieldId + if c.OldValue != nil { + structMap["old_value"] = c.OldValue + } else { + structMap["old_value"] = nil + } + if c.NewValue != nil { + structMap["new_value"] = c.NewValue + } else { + structMap["new_value"] = nil + } + structMap["resource_type"] = c.ResourceType + structMap["resource_id"] = c.ResourceId + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CustomFieldValueChange. +// It customizes the JSON unmarshaling process for CustomFieldValueChange objects. +func (c *CustomFieldValueChange) UnmarshalJSON(input []byte) error { + var temp customFieldValueChange + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.EventType = *temp.EventType + c.MetafieldName = *temp.MetafieldName + c.MetafieldId = *temp.MetafieldId + c.OldValue = temp.OldValue + c.NewValue = temp.NewValue + c.ResourceType = *temp.ResourceType + c.ResourceId = *temp.ResourceId + return nil +} + +// TODO +type customFieldValueChange struct { + EventType *string `json:"event_type"` + MetafieldName *string `json:"metafield_name"` + MetafieldId *int `json:"metafield_id"` + OldValue *string `json:"old_value"` + NewValue *string `json:"new_value"` + ResourceType *string `json:"resource_type"` + ResourceId *int `json:"resource_id"` +} + +func (c *customFieldValueChange) validate() error { + var errs []string + if c.EventType == nil { + errs = append(errs, "required field `event_type` is missing for type `Custom Field Value Change`") + } + if c.MetafieldName == nil { + errs = append(errs, "required field `metafield_name` is missing for type `Custom Field Value Change`") + } + if c.MetafieldId == nil { + errs = append(errs, "required field `metafield_id` is missing for type `Custom Field Value Change`") + } + if c.ResourceType == nil { + errs = append(errs, "required field `resource_type` is missing for type `Custom Field Value Change`") + } + if c.ResourceId == nil { + errs = append(errs, "required field `resource_id` is missing for type `Custom Field Value Change`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/customer.go b/models/customer.go index 54c03056..e203cc76 100644 --- a/models/customer.go +++ b/models/customer.go @@ -1,274 +1,356 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Customer represents a Customer struct. type Customer struct { - // The first name of the customer - FirstName *string `json:"first_name,omitempty"` - // The last name of the customer - LastName *string `json:"last_name,omitempty"` - // The email address of the customer - Email *string `json:"email,omitempty"` - // A comma-separated list of emails that should be cc’d on all customer communications (i.e. “joe@example.com, sue@example.com”) - CcEmails Optional[string] `json:"cc_emails"` - // The organization of the customer - Organization Optional[string] `json:"organization"` - // The unique identifier used within your own application for this customer - Reference Optional[string] `json:"reference"` - // The customer ID in Chargify - Id *int `json:"id,omitempty"` - // The timestamp in which the customer object was created in Chargify - CreatedAt *time.Time `json:"created_at,omitempty"` - // The timestamp in which the customer object was last edited - UpdatedAt *time.Time `json:"updated_at,omitempty"` - // The customer’s shipping street address (i.e. “123 Main St.”) - Address Optional[string] `json:"address"` - // Second line of the customer’s shipping address i.e. “Apt. 100” - Address2 Optional[string] `json:"address_2"` - // The customer’s shipping address city (i.e. “Boston”) - City Optional[string] `json:"city"` - // The customer’s shipping address state (i.e. “MA”) - State Optional[string] `json:"state"` - // The customer's full name of state - StateName Optional[string] `json:"state_name"` - // The customer’s shipping address zip code (i.e. “12345”) - Zip Optional[string] `json:"zip"` - // The customer shipping address country - Country Optional[string] `json:"country"` - // The customer's full name of country - CountryName Optional[string] `json:"country_name"` - // The phone number of the customer - Phone Optional[string] `json:"phone"` - // Is the customer verified to use ACH as a payment method. Available only on Authorize.Net gateway - Verified Optional[bool] `json:"verified"` - // The timestamp of when the Billing Portal entry was created at for the customer - PortalCustomerCreatedAt Optional[time.Time] `json:"portal_customer_created_at"` - // The timestamp of when the Billing Portal invite was last sent at - PortalInviteLastSentAt Optional[time.Time] `json:"portal_invite_last_sent_at"` - // The timestamp of when the Billing Portal invite was last accepted - PortalInviteLastAcceptedAt Optional[time.Time] `json:"portal_invite_last_accepted_at"` - // The tax exempt status for the customer. Acceptable values are true or 1 for true and false or 0 for false. - TaxExempt *bool `json:"tax_exempt,omitempty"` - // The VAT business identification number for the customer. This number is used to determine VAT tax opt out rules. It is not validated when added or updated on a customer record. Instead, it is validated via VIES before calculating taxes. Only valid business identification numbers will allow for VAT opt out. - VatNumber Optional[string] `json:"vat_number"` - // The parent ID in Chargify if applicable. Parent is another Customer object. - ParentId Optional[int] `json:"parent_id"` - // The locale for the customer to identify language-region - Locale Optional[string] `json:"locale"` - DefaultSubscriptionGroupUid Optional[string] `json:"default_subscription_group_uid"` + // The first name of the customer + FirstName *string `json:"first_name,omitempty"` + // The last name of the customer + LastName *string `json:"last_name,omitempty"` + // The email address of the customer + Email *string `json:"email,omitempty"` + // A comma-separated list of emails that should be cc’d on all customer communications (i.e. “joe@example.com, sue@example.com”) + CcEmails Optional[string] `json:"cc_emails"` + // The organization of the customer + Organization Optional[string] `json:"organization"` + // The unique identifier used within your own application for this customer + Reference Optional[string] `json:"reference"` + // The customer ID in Chargify + Id *int `json:"id,omitempty"` + // The timestamp in which the customer object was created in Chargify + CreatedAt *time.Time `json:"created_at,omitempty"` + // The timestamp in which the customer object was last edited + UpdatedAt *time.Time `json:"updated_at,omitempty"` + // The customer’s shipping street address (i.e. “123 Main St.”) + Address Optional[string] `json:"address"` + // Second line of the customer’s shipping address i.e. “Apt. 100” + Address2 Optional[string] `json:"address_2"` + // The customer’s shipping address city (i.e. “Boston”) + City Optional[string] `json:"city"` + // The customer’s shipping address state (i.e. “MA”) + State Optional[string] `json:"state"` + // The customer's full name of state + StateName Optional[string] `json:"state_name"` + // The customer’s shipping address zip code (i.e. “12345”) + Zip Optional[string] `json:"zip"` + // The customer shipping address country + Country Optional[string] `json:"country"` + // The customer's full name of country + CountryName Optional[string] `json:"country_name"` + // The phone number of the customer + Phone Optional[string] `json:"phone"` + // Is the customer verified to use ACH as a payment method. Available only on Authorize.Net gateway + Verified Optional[bool] `json:"verified"` + // The timestamp of when the Billing Portal entry was created at for the customer + PortalCustomerCreatedAt Optional[time.Time] `json:"portal_customer_created_at"` + // The timestamp of when the Billing Portal invite was last sent at + PortalInviteLastSentAt Optional[time.Time] `json:"portal_invite_last_sent_at"` + // The timestamp of when the Billing Portal invite was last accepted + PortalInviteLastAcceptedAt Optional[time.Time] `json:"portal_invite_last_accepted_at"` + // The tax exempt status for the customer. Acceptable values are true or 1 for true and false or 0 for false. + TaxExempt *bool `json:"tax_exempt,omitempty"` + // The VAT business identification number for the customer. This number is used to determine VAT tax opt out rules. It is not validated when added or updated on a customer record. Instead, it is validated via VIES before calculating taxes. Only valid business identification numbers will allow for VAT opt out. + VatNumber Optional[string] `json:"vat_number"` + // The parent ID in Chargify if applicable. Parent is another Customer object. + ParentId Optional[int] `json:"parent_id"` + // The locale for the customer to identify language-region + Locale Optional[string] `json:"locale"` + DefaultSubscriptionGroupUid Optional[string] `json:"default_subscription_group_uid"` } -// MarshalJSON implements the json.Marshaler interface for Customer. +// MarshalJSON implements the json.Marshaler interface for Customer. // It customizes the JSON marshaling process for Customer objects. func (c *Customer) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the Customer object to a map representation for JSON marshaling. func (c *Customer) toMap() map[string]any { - structMap := make(map[string]any) - if c.FirstName != nil { - structMap["first_name"] = c.FirstName - } - if c.LastName != nil { - structMap["last_name"] = c.LastName - } - if c.Email != nil { - structMap["email"] = c.Email - } - if c.CcEmails.IsValueSet() { - structMap["cc_emails"] = c.CcEmails.Value() - } - if c.Organization.IsValueSet() { - structMap["organization"] = c.Organization.Value() - } - if c.Reference.IsValueSet() { - structMap["reference"] = c.Reference.Value() - } - if c.Id != nil { - structMap["id"] = c.Id - } - if c.CreatedAt != nil { - structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) - } - if c.UpdatedAt != nil { - structMap["updated_at"] = c.UpdatedAt.Format(time.RFC3339) - } - if c.Address.IsValueSet() { - structMap["address"] = c.Address.Value() - } - if c.Address2.IsValueSet() { - structMap["address_2"] = c.Address2.Value() - } - if c.City.IsValueSet() { - structMap["city"] = c.City.Value() - } - if c.State.IsValueSet() { - structMap["state"] = c.State.Value() - } - if c.StateName.IsValueSet() { - structMap["state_name"] = c.StateName.Value() - } - if c.Zip.IsValueSet() { - structMap["zip"] = c.Zip.Value() - } - if c.Country.IsValueSet() { - structMap["country"] = c.Country.Value() - } - if c.CountryName.IsValueSet() { - structMap["country_name"] = c.CountryName.Value() - } - if c.Phone.IsValueSet() { - structMap["phone"] = c.Phone.Value() - } - if c.Verified.IsValueSet() { - structMap["verified"] = c.Verified.Value() - } - if c.PortalCustomerCreatedAt.IsValueSet() { - var PortalCustomerCreatedAtVal *string = nil - if c.PortalCustomerCreatedAt.Value() != nil { - val := c.PortalCustomerCreatedAt.Value().Format(time.RFC3339) - PortalCustomerCreatedAtVal = &val - } - structMap["portal_customer_created_at"] = PortalCustomerCreatedAtVal - } - if c.PortalInviteLastSentAt.IsValueSet() { - var PortalInviteLastSentAtVal *string = nil - if c.PortalInviteLastSentAt.Value() != nil { - val := c.PortalInviteLastSentAt.Value().Format(time.RFC3339) - PortalInviteLastSentAtVal = &val - } - structMap["portal_invite_last_sent_at"] = PortalInviteLastSentAtVal - } - if c.PortalInviteLastAcceptedAt.IsValueSet() { - var PortalInviteLastAcceptedAtVal *string = nil - if c.PortalInviteLastAcceptedAt.Value() != nil { - val := c.PortalInviteLastAcceptedAt.Value().Format(time.RFC3339) - PortalInviteLastAcceptedAtVal = &val - } - structMap["portal_invite_last_accepted_at"] = PortalInviteLastAcceptedAtVal - } - if c.TaxExempt != nil { - structMap["tax_exempt"] = c.TaxExempt - } - if c.VatNumber.IsValueSet() { - structMap["vat_number"] = c.VatNumber.Value() - } - if c.ParentId.IsValueSet() { - structMap["parent_id"] = c.ParentId.Value() - } - if c.Locale.IsValueSet() { - structMap["locale"] = c.Locale.Value() - } - if c.DefaultSubscriptionGroupUid.IsValueSet() { - structMap["default_subscription_group_uid"] = c.DefaultSubscriptionGroupUid.Value() - } - return structMap + structMap := make(map[string]any) + if c.FirstName != nil { + structMap["first_name"] = c.FirstName + } + if c.LastName != nil { + structMap["last_name"] = c.LastName + } + if c.Email != nil { + structMap["email"] = c.Email + } + if c.CcEmails.IsValueSet() { + if c.CcEmails.Value() != nil { + structMap["cc_emails"] = c.CcEmails.Value() + } else { + structMap["cc_emails"] = nil + } + } + if c.Organization.IsValueSet() { + if c.Organization.Value() != nil { + structMap["organization"] = c.Organization.Value() + } else { + structMap["organization"] = nil + } + } + if c.Reference.IsValueSet() { + if c.Reference.Value() != nil { + structMap["reference"] = c.Reference.Value() + } else { + structMap["reference"] = nil + } + } + if c.Id != nil { + structMap["id"] = c.Id + } + if c.CreatedAt != nil { + structMap["created_at"] = c.CreatedAt.Format(time.RFC3339) + } + if c.UpdatedAt != nil { + structMap["updated_at"] = c.UpdatedAt.Format(time.RFC3339) + } + if c.Address.IsValueSet() { + if c.Address.Value() != nil { + structMap["address"] = c.Address.Value() + } else { + structMap["address"] = nil + } + } + if c.Address2.IsValueSet() { + if c.Address2.Value() != nil { + structMap["address_2"] = c.Address2.Value() + } else { + structMap["address_2"] = nil + } + } + if c.City.IsValueSet() { + if c.City.Value() != nil { + structMap["city"] = c.City.Value() + } else { + structMap["city"] = nil + } + } + if c.State.IsValueSet() { + if c.State.Value() != nil { + structMap["state"] = c.State.Value() + } else { + structMap["state"] = nil + } + } + if c.StateName.IsValueSet() { + if c.StateName.Value() != nil { + structMap["state_name"] = c.StateName.Value() + } else { + structMap["state_name"] = nil + } + } + if c.Zip.IsValueSet() { + if c.Zip.Value() != nil { + structMap["zip"] = c.Zip.Value() + } else { + structMap["zip"] = nil + } + } + if c.Country.IsValueSet() { + if c.Country.Value() != nil { + structMap["country"] = c.Country.Value() + } else { + structMap["country"] = nil + } + } + if c.CountryName.IsValueSet() { + if c.CountryName.Value() != nil { + structMap["country_name"] = c.CountryName.Value() + } else { + structMap["country_name"] = nil + } + } + if c.Phone.IsValueSet() { + if c.Phone.Value() != nil { + structMap["phone"] = c.Phone.Value() + } else { + structMap["phone"] = nil + } + } + if c.Verified.IsValueSet() { + if c.Verified.Value() != nil { + structMap["verified"] = c.Verified.Value() + } else { + structMap["verified"] = nil + } + } + if c.PortalCustomerCreatedAt.IsValueSet() { + var PortalCustomerCreatedAtVal *string = nil + if c.PortalCustomerCreatedAt.Value() != nil { + val := c.PortalCustomerCreatedAt.Value().Format(time.RFC3339) + PortalCustomerCreatedAtVal = &val + } + if c.PortalCustomerCreatedAt.Value() != nil { + structMap["portal_customer_created_at"] = PortalCustomerCreatedAtVal + } else { + structMap["portal_customer_created_at"] = nil + } + } + if c.PortalInviteLastSentAt.IsValueSet() { + var PortalInviteLastSentAtVal *string = nil + if c.PortalInviteLastSentAt.Value() != nil { + val := c.PortalInviteLastSentAt.Value().Format(time.RFC3339) + PortalInviteLastSentAtVal = &val + } + if c.PortalInviteLastSentAt.Value() != nil { + structMap["portal_invite_last_sent_at"] = PortalInviteLastSentAtVal + } else { + structMap["portal_invite_last_sent_at"] = nil + } + } + if c.PortalInviteLastAcceptedAt.IsValueSet() { + var PortalInviteLastAcceptedAtVal *string = nil + if c.PortalInviteLastAcceptedAt.Value() != nil { + val := c.PortalInviteLastAcceptedAt.Value().Format(time.RFC3339) + PortalInviteLastAcceptedAtVal = &val + } + if c.PortalInviteLastAcceptedAt.Value() != nil { + structMap["portal_invite_last_accepted_at"] = PortalInviteLastAcceptedAtVal + } else { + structMap["portal_invite_last_accepted_at"] = nil + } + } + if c.TaxExempt != nil { + structMap["tax_exempt"] = c.TaxExempt + } + if c.VatNumber.IsValueSet() { + if c.VatNumber.Value() != nil { + structMap["vat_number"] = c.VatNumber.Value() + } else { + structMap["vat_number"] = nil + } + } + if c.ParentId.IsValueSet() { + if c.ParentId.Value() != nil { + structMap["parent_id"] = c.ParentId.Value() + } else { + structMap["parent_id"] = nil + } + } + if c.Locale.IsValueSet() { + if c.Locale.Value() != nil { + structMap["locale"] = c.Locale.Value() + } else { + structMap["locale"] = nil + } + } + if c.DefaultSubscriptionGroupUid.IsValueSet() { + if c.DefaultSubscriptionGroupUid.Value() != nil { + structMap["default_subscription_group_uid"] = c.DefaultSubscriptionGroupUid.Value() + } else { + structMap["default_subscription_group_uid"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Customer. +// UnmarshalJSON implements the json.Unmarshaler interface for Customer. // It customizes the JSON unmarshaling process for Customer objects. func (c *Customer) UnmarshalJSON(input []byte) error { - temp := &struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Email *string `json:"email,omitempty"` - CcEmails Optional[string] `json:"cc_emails"` - Organization Optional[string] `json:"organization"` - Reference Optional[string] `json:"reference"` - Id *int `json:"id,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - Address Optional[string] `json:"address"` - Address2 Optional[string] `json:"address_2"` - City Optional[string] `json:"city"` - State Optional[string] `json:"state"` - StateName Optional[string] `json:"state_name"` - Zip Optional[string] `json:"zip"` - Country Optional[string] `json:"country"` - CountryName Optional[string] `json:"country_name"` - Phone Optional[string] `json:"phone"` - Verified Optional[bool] `json:"verified"` - PortalCustomerCreatedAt Optional[string] `json:"portal_customer_created_at"` - PortalInviteLastSentAt Optional[string] `json:"portal_invite_last_sent_at"` - PortalInviteLastAcceptedAt Optional[string] `json:"portal_invite_last_accepted_at"` - TaxExempt *bool `json:"tax_exempt,omitempty"` - VatNumber Optional[string] `json:"vat_number"` - ParentId Optional[int] `json:"parent_id"` - Locale Optional[string] `json:"locale"` - DefaultSubscriptionGroupUid Optional[string] `json:"default_subscription_group_uid"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.FirstName = temp.FirstName - c.LastName = temp.LastName - c.Email = temp.Email - c.CcEmails = temp.CcEmails - c.Organization = temp.Organization - c.Reference = temp.Reference - c.Id = temp.Id - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - c.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - c.UpdatedAt = &UpdatedAtVal - } - c.Address = temp.Address - c.Address2 = temp.Address2 - c.City = temp.City - c.State = temp.State - c.StateName = temp.StateName - c.Zip = temp.Zip - c.Country = temp.Country - c.CountryName = temp.CountryName - c.Phone = temp.Phone - c.Verified = temp.Verified - c.PortalCustomerCreatedAt.ShouldSetValue(temp.PortalCustomerCreatedAt.IsValueSet()) - if temp.PortalCustomerCreatedAt.Value() != nil { - PortalCustomerCreatedAtVal, err := time.Parse(time.RFC3339, (*temp.PortalCustomerCreatedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse portal_customer_created_at as % s format.", time.RFC3339) - } - c.PortalCustomerCreatedAt.SetValue(&PortalCustomerCreatedAtVal) - } - c.PortalInviteLastSentAt.ShouldSetValue(temp.PortalInviteLastSentAt.IsValueSet()) - if temp.PortalInviteLastSentAt.Value() != nil { - PortalInviteLastSentAtVal, err := time.Parse(time.RFC3339, (*temp.PortalInviteLastSentAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse portal_invite_last_sent_at as % s format.", time.RFC3339) - } - c.PortalInviteLastSentAt.SetValue(&PortalInviteLastSentAtVal) - } - c.PortalInviteLastAcceptedAt.ShouldSetValue(temp.PortalInviteLastAcceptedAt.IsValueSet()) - if temp.PortalInviteLastAcceptedAt.Value() != nil { - PortalInviteLastAcceptedAtVal, err := time.Parse(time.RFC3339, (*temp.PortalInviteLastAcceptedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse portal_invite_last_accepted_at as % s format.", time.RFC3339) - } - c.PortalInviteLastAcceptedAt.SetValue(&PortalInviteLastAcceptedAtVal) - } - c.TaxExempt = temp.TaxExempt - c.VatNumber = temp.VatNumber - c.ParentId = temp.ParentId - c.Locale = temp.Locale - c.DefaultSubscriptionGroupUid = temp.DefaultSubscriptionGroupUid - return nil + var temp customer + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.FirstName = temp.FirstName + c.LastName = temp.LastName + c.Email = temp.Email + c.CcEmails = temp.CcEmails + c.Organization = temp.Organization + c.Reference = temp.Reference + c.Id = temp.Id + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + c.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + c.UpdatedAt = &UpdatedAtVal + } + c.Address = temp.Address + c.Address2 = temp.Address2 + c.City = temp.City + c.State = temp.State + c.StateName = temp.StateName + c.Zip = temp.Zip + c.Country = temp.Country + c.CountryName = temp.CountryName + c.Phone = temp.Phone + c.Verified = temp.Verified + c.PortalCustomerCreatedAt.ShouldSetValue(temp.PortalCustomerCreatedAt.IsValueSet()) + if temp.PortalCustomerCreatedAt.Value() != nil { + PortalCustomerCreatedAtVal, err := time.Parse(time.RFC3339, (*temp.PortalCustomerCreatedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse portal_customer_created_at as % s format.", time.RFC3339) + } + c.PortalCustomerCreatedAt.SetValue(&PortalCustomerCreatedAtVal) + } + c.PortalInviteLastSentAt.ShouldSetValue(temp.PortalInviteLastSentAt.IsValueSet()) + if temp.PortalInviteLastSentAt.Value() != nil { + PortalInviteLastSentAtVal, err := time.Parse(time.RFC3339, (*temp.PortalInviteLastSentAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse portal_invite_last_sent_at as % s format.", time.RFC3339) + } + c.PortalInviteLastSentAt.SetValue(&PortalInviteLastSentAtVal) + } + c.PortalInviteLastAcceptedAt.ShouldSetValue(temp.PortalInviteLastAcceptedAt.IsValueSet()) + if temp.PortalInviteLastAcceptedAt.Value() != nil { + PortalInviteLastAcceptedAtVal, err := time.Parse(time.RFC3339, (*temp.PortalInviteLastAcceptedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse portal_invite_last_accepted_at as % s format.", time.RFC3339) + } + c.PortalInviteLastAcceptedAt.SetValue(&PortalInviteLastAcceptedAtVal) + } + c.TaxExempt = temp.TaxExempt + c.VatNumber = temp.VatNumber + c.ParentId = temp.ParentId + c.Locale = temp.Locale + c.DefaultSubscriptionGroupUid = temp.DefaultSubscriptionGroupUid + return nil +} + +// TODO +type customer struct { + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Email *string `json:"email,omitempty"` + CcEmails Optional[string] `json:"cc_emails"` + Organization Optional[string] `json:"organization"` + Reference Optional[string] `json:"reference"` + Id *int `json:"id,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + Address Optional[string] `json:"address"` + Address2 Optional[string] `json:"address_2"` + City Optional[string] `json:"city"` + State Optional[string] `json:"state"` + StateName Optional[string] `json:"state_name"` + Zip Optional[string] `json:"zip"` + Country Optional[string] `json:"country"` + CountryName Optional[string] `json:"country_name"` + Phone Optional[string] `json:"phone"` + Verified Optional[bool] `json:"verified"` + PortalCustomerCreatedAt Optional[string] `json:"portal_customer_created_at"` + PortalInviteLastSentAt Optional[string] `json:"portal_invite_last_sent_at"` + PortalInviteLastAcceptedAt Optional[string] `json:"portal_invite_last_accepted_at"` + TaxExempt *bool `json:"tax_exempt,omitempty"` + VatNumber Optional[string] `json:"vat_number"` + ParentId Optional[int] `json:"parent_id"` + Locale Optional[string] `json:"locale"` + DefaultSubscriptionGroupUid Optional[string] `json:"default_subscription_group_uid"` } diff --git a/models/customer_1.go b/models/customer_1.go index 429cfe37..50613aca 100644 --- a/models/customer_1.go +++ b/models/customer_1.go @@ -1,78 +1,96 @@ package models import ( - "encoding/json" + "encoding/json" ) // Customer1 represents a Customer1 struct. type Customer1 struct { - ChargifyId Optional[int] `json:"chargify_id"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Organization Optional[string] `json:"organization"` - Email *string `json:"email,omitempty"` - VatNumber Optional[string] `json:"vat_number"` - Reference Optional[string] `json:"reference"` + ChargifyId Optional[int] `json:"chargify_id"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Organization Optional[string] `json:"organization"` + Email *string `json:"email,omitempty"` + VatNumber Optional[string] `json:"vat_number"` + Reference Optional[string] `json:"reference"` } -// MarshalJSON implements the json.Marshaler interface for Customer1. +// MarshalJSON implements the json.Marshaler interface for Customer1. // It customizes the JSON marshaling process for Customer1 objects. func (c *Customer1) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the Customer1 object to a map representation for JSON marshaling. func (c *Customer1) toMap() map[string]any { - structMap := make(map[string]any) - if c.ChargifyId.IsValueSet() { - structMap["chargify_id"] = c.ChargifyId.Value() - } - if c.FirstName != nil { - structMap["first_name"] = c.FirstName - } - if c.LastName != nil { - structMap["last_name"] = c.LastName - } - if c.Organization.IsValueSet() { - structMap["organization"] = c.Organization.Value() - } - if c.Email != nil { - structMap["email"] = c.Email - } - if c.VatNumber.IsValueSet() { - structMap["vat_number"] = c.VatNumber.Value() - } - if c.Reference.IsValueSet() { - structMap["reference"] = c.Reference.Value() - } - return structMap + structMap := make(map[string]any) + if c.ChargifyId.IsValueSet() { + if c.ChargifyId.Value() != nil { + structMap["chargify_id"] = c.ChargifyId.Value() + } else { + structMap["chargify_id"] = nil + } + } + if c.FirstName != nil { + structMap["first_name"] = c.FirstName + } + if c.LastName != nil { + structMap["last_name"] = c.LastName + } + if c.Organization.IsValueSet() { + if c.Organization.Value() != nil { + structMap["organization"] = c.Organization.Value() + } else { + structMap["organization"] = nil + } + } + if c.Email != nil { + structMap["email"] = c.Email + } + if c.VatNumber.IsValueSet() { + if c.VatNumber.Value() != nil { + structMap["vat_number"] = c.VatNumber.Value() + } else { + structMap["vat_number"] = nil + } + } + if c.Reference.IsValueSet() { + if c.Reference.Value() != nil { + structMap["reference"] = c.Reference.Value() + } else { + structMap["reference"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Customer1. +// UnmarshalJSON implements the json.Unmarshaler interface for Customer1. // It customizes the JSON unmarshaling process for Customer1 objects. func (c *Customer1) UnmarshalJSON(input []byte) error { - temp := &struct { - ChargifyId Optional[int] `json:"chargify_id"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Organization Optional[string] `json:"organization"` - Email *string `json:"email,omitempty"` - VatNumber Optional[string] `json:"vat_number"` - Reference Optional[string] `json:"reference"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.ChargifyId = temp.ChargifyId - c.FirstName = temp.FirstName - c.LastName = temp.LastName - c.Organization = temp.Organization - c.Email = temp.Email - c.VatNumber = temp.VatNumber - c.Reference = temp.Reference - return nil + var temp customer1 + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.ChargifyId = temp.ChargifyId + c.FirstName = temp.FirstName + c.LastName = temp.LastName + c.Organization = temp.Organization + c.Email = temp.Email + c.VatNumber = temp.VatNumber + c.Reference = temp.Reference + return nil +} + +// TODO +type customer1 struct { + ChargifyId Optional[int] `json:"chargify_id"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Organization Optional[string] `json:"organization"` + Email *string `json:"email,omitempty"` + VatNumber Optional[string] `json:"vat_number"` + Reference Optional[string] `json:"reference"` } diff --git a/models/customer_attributes.go b/models/customer_attributes.go index 191dca7b..a489a4ae 100644 --- a/models/customer_attributes.go +++ b/models/customer_attributes.go @@ -1,161 +1,171 @@ package models import ( - "encoding/json" + "encoding/json" ) // CustomerAttributes represents a CustomerAttributes struct. type CustomerAttributes struct { - // The first name of the customer. Required when creating a customer via attributes. - FirstName *string `json:"first_name,omitempty"` - // The last name of the customer. Required when creating a customer via attributes. - LastName *string `json:"last_name,omitempty"` - // The email address of the customer. Required when creating a customer via attributes. - Email *string `json:"email,omitempty"` - // A list of emails that should be cc’d on all customer communications. Optional. - CcEmails *string `json:"cc_emails,omitempty"` - // The organization/company of the customer. Optional. - Organization *string `json:"organization,omitempty"` - // A customer “reference”, or unique identifier from your app, stored in Chargify. Can be used so that you may reference your customer’s within Chargify using the same unique value you use in your application. Optional. - Reference *string `json:"reference,omitempty"` - // (Optional) The customer’s shipping street address (i.e. “123 Main St.”). - Address *string `json:"address,omitempty"` - // (Optional) Second line of the customer’s shipping address i.e. “Apt. 100” - Address2 Optional[string] `json:"address_2"` - // (Optional) The customer’s shipping address city (i.e. “Boston”). - City *string `json:"city,omitempty"` - // (Optional) The customer’s shipping address state (i.e. “MA”). This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. - State *string `json:"state,omitempty"` - // (Optional) The customer’s shipping address zip code (i.e. “12345”). - Zip *string `json:"zip,omitempty"` - // (Optional) The customer shipping address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). - Country *string `json:"country,omitempty"` - // (Optional) The phone number of the customer. - Phone *string `json:"phone,omitempty"` - Verified *bool `json:"verified,omitempty"` - // (Optional) The tax_exempt status of the customer. Acceptable values are true or 1 for true and false or 0 for false. - TaxExempt *bool `json:"tax_exempt,omitempty"` - // (Optional) Supplying the VAT number allows EU customer’s to opt-out of the Value Added Tax assuming the merchant address and customer billing address are not within the same EU country. It’s important to omit the country code from the VAT number upon entry. Otherwise, taxes will be assessed upon the purchase. - VatNumber *string `json:"vat_number,omitempty"` - // (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. - Metafields map[string]string `json:"metafields,omitempty"` - // The parent ID in Chargify if applicable. Parent is another Customer object. - ParentId Optional[int] `json:"parent_id"` + // The first name of the customer. Required when creating a customer via attributes. + FirstName *string `json:"first_name,omitempty"` + // The last name of the customer. Required when creating a customer via attributes. + LastName *string `json:"last_name,omitempty"` + // The email address of the customer. Required when creating a customer via attributes. + Email *string `json:"email,omitempty"` + // A list of emails that should be cc’d on all customer communications. Optional. + CcEmails *string `json:"cc_emails,omitempty"` + // The organization/company of the customer. Optional. + Organization *string `json:"organization,omitempty"` + // A customer “reference”, or unique identifier from your app, stored in Chargify. Can be used so that you may reference your customer’s within Chargify using the same unique value you use in your application. Optional. + Reference *string `json:"reference,omitempty"` + // (Optional) The customer’s shipping street address (i.e. “123 Main St.”). + Address *string `json:"address,omitempty"` + // (Optional) Second line of the customer’s shipping address i.e. “Apt. 100” + Address2 Optional[string] `json:"address_2"` + // (Optional) The customer’s shipping address city (i.e. “Boston”). + City *string `json:"city,omitempty"` + // (Optional) The customer’s shipping address state (i.e. “MA”). This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. + State *string `json:"state,omitempty"` + // (Optional) The customer’s shipping address zip code (i.e. “12345”). + Zip *string `json:"zip,omitempty"` + // (Optional) The customer shipping address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). + Country *string `json:"country,omitempty"` + // (Optional) The phone number of the customer. + Phone *string `json:"phone,omitempty"` + Verified *bool `json:"verified,omitempty"` + // (Optional) The tax_exempt status of the customer. Acceptable values are true or 1 for true and false or 0 for false. + TaxExempt *bool `json:"tax_exempt,omitempty"` + // (Optional) Supplying the VAT number allows EU customer’s to opt-out of the Value Added Tax assuming the merchant address and customer billing address are not within the same EU country. It’s important to omit the country code from the VAT number upon entry. Otherwise, taxes will be assessed upon the purchase. + VatNumber *string `json:"vat_number,omitempty"` + // (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. + Metafields map[string]string `json:"metafields,omitempty"` + // The parent ID in Chargify if applicable. Parent is another Customer object. + ParentId Optional[int] `json:"parent_id"` } -// MarshalJSON implements the json.Marshaler interface for CustomerAttributes. +// MarshalJSON implements the json.Marshaler interface for CustomerAttributes. // It customizes the JSON marshaling process for CustomerAttributes objects. func (c *CustomerAttributes) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CustomerAttributes object to a map representation for JSON marshaling. func (c *CustomerAttributes) toMap() map[string]any { - structMap := make(map[string]any) - if c.FirstName != nil { - structMap["first_name"] = c.FirstName - } - if c.LastName != nil { - structMap["last_name"] = c.LastName - } - if c.Email != nil { - structMap["email"] = c.Email - } - if c.CcEmails != nil { - structMap["cc_emails"] = c.CcEmails - } - if c.Organization != nil { - structMap["organization"] = c.Organization - } - if c.Reference != nil { - structMap["reference"] = c.Reference - } - if c.Address != nil { - structMap["address"] = c.Address - } - if c.Address2.IsValueSet() { - structMap["address_2"] = c.Address2.Value() - } - if c.City != nil { - structMap["city"] = c.City - } - if c.State != nil { - structMap["state"] = c.State - } - if c.Zip != nil { - structMap["zip"] = c.Zip - } - if c.Country != nil { - structMap["country"] = c.Country - } - if c.Phone != nil { - structMap["phone"] = c.Phone - } - if c.Verified != nil { - structMap["verified"] = c.Verified - } - if c.TaxExempt != nil { - structMap["tax_exempt"] = c.TaxExempt - } - if c.VatNumber != nil { - structMap["vat_number"] = c.VatNumber - } - if c.Metafields != nil { - structMap["metafields"] = c.Metafields - } - if c.ParentId.IsValueSet() { - structMap["parent_id"] = c.ParentId.Value() - } - return structMap + structMap := make(map[string]any) + if c.FirstName != nil { + structMap["first_name"] = c.FirstName + } + if c.LastName != nil { + structMap["last_name"] = c.LastName + } + if c.Email != nil { + structMap["email"] = c.Email + } + if c.CcEmails != nil { + structMap["cc_emails"] = c.CcEmails + } + if c.Organization != nil { + structMap["organization"] = c.Organization + } + if c.Reference != nil { + structMap["reference"] = c.Reference + } + if c.Address != nil { + structMap["address"] = c.Address + } + if c.Address2.IsValueSet() { + if c.Address2.Value() != nil { + structMap["address_2"] = c.Address2.Value() + } else { + structMap["address_2"] = nil + } + } + if c.City != nil { + structMap["city"] = c.City + } + if c.State != nil { + structMap["state"] = c.State + } + if c.Zip != nil { + structMap["zip"] = c.Zip + } + if c.Country != nil { + structMap["country"] = c.Country + } + if c.Phone != nil { + structMap["phone"] = c.Phone + } + if c.Verified != nil { + structMap["verified"] = c.Verified + } + if c.TaxExempt != nil { + structMap["tax_exempt"] = c.TaxExempt + } + if c.VatNumber != nil { + structMap["vat_number"] = c.VatNumber + } + if c.Metafields != nil { + structMap["metafields"] = c.Metafields + } + if c.ParentId.IsValueSet() { + if c.ParentId.Value() != nil { + structMap["parent_id"] = c.ParentId.Value() + } else { + structMap["parent_id"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CustomerAttributes. +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerAttributes. // It customizes the JSON unmarshaling process for CustomerAttributes objects. func (c *CustomerAttributes) UnmarshalJSON(input []byte) error { - temp := &struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Email *string `json:"email,omitempty"` - CcEmails *string `json:"cc_emails,omitempty"` - Organization *string `json:"organization,omitempty"` - Reference *string `json:"reference,omitempty"` - Address *string `json:"address,omitempty"` - Address2 Optional[string] `json:"address_2"` - City *string `json:"city,omitempty"` - State *string `json:"state,omitempty"` - Zip *string `json:"zip,omitempty"` - Country *string `json:"country,omitempty"` - Phone *string `json:"phone,omitempty"` - Verified *bool `json:"verified,omitempty"` - TaxExempt *bool `json:"tax_exempt,omitempty"` - VatNumber *string `json:"vat_number,omitempty"` - Metafields map[string]string `json:"metafields,omitempty"` - ParentId Optional[int] `json:"parent_id"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.FirstName = temp.FirstName - c.LastName = temp.LastName - c.Email = temp.Email - c.CcEmails = temp.CcEmails - c.Organization = temp.Organization - c.Reference = temp.Reference - c.Address = temp.Address - c.Address2 = temp.Address2 - c.City = temp.City - c.State = temp.State - c.Zip = temp.Zip - c.Country = temp.Country - c.Phone = temp.Phone - c.Verified = temp.Verified - c.TaxExempt = temp.TaxExempt - c.VatNumber = temp.VatNumber - c.Metafields = temp.Metafields - c.ParentId = temp.ParentId - return nil + var temp customerAttributes + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.FirstName = temp.FirstName + c.LastName = temp.LastName + c.Email = temp.Email + c.CcEmails = temp.CcEmails + c.Organization = temp.Organization + c.Reference = temp.Reference + c.Address = temp.Address + c.Address2 = temp.Address2 + c.City = temp.City + c.State = temp.State + c.Zip = temp.Zip + c.Country = temp.Country + c.Phone = temp.Phone + c.Verified = temp.Verified + c.TaxExempt = temp.TaxExempt + c.VatNumber = temp.VatNumber + c.Metafields = temp.Metafields + c.ParentId = temp.ParentId + return nil +} + +// TODO +type customerAttributes struct { + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Email *string `json:"email,omitempty"` + CcEmails *string `json:"cc_emails,omitempty"` + Organization *string `json:"organization,omitempty"` + Reference *string `json:"reference,omitempty"` + Address *string `json:"address,omitempty"` + Address2 Optional[string] `json:"address_2"` + City *string `json:"city,omitempty"` + State *string `json:"state,omitempty"` + Zip *string `json:"zip,omitempty"` + Country *string `json:"country,omitempty"` + Phone *string `json:"phone,omitempty"` + Verified *bool `json:"verified,omitempty"` + TaxExempt *bool `json:"tax_exempt,omitempty"` + VatNumber *string `json:"vat_number,omitempty"` + Metafields map[string]string `json:"metafields,omitempty"` + ParentId Optional[int] `json:"parent_id"` } diff --git a/models/customer_change.go b/models/customer_change.go index 42dd627a..4b7c1f91 100644 --- a/models/customer_change.go +++ b/models/customer_change.go @@ -1,60 +1,78 @@ package models import ( - "encoding/json" + "encoding/json" ) // CustomerChange represents a CustomerChange struct. type CustomerChange struct { - Payer Optional[CustomerPayerChange] `json:"payer"` - ShippingAddress Optional[AddressChange] `json:"shipping_address"` - BillingAddress Optional[AddressChange] `json:"billing_address"` - CustomFields Optional[CustomerCustomFieldsChange] `json:"custom_fields"` + Payer Optional[CustomerChangePayer] `json:"payer"` + ShippingAddress Optional[CustomerChangeShippingAddress] `json:"shipping_address"` + BillingAddress Optional[CustomerChangeBillingAddress] `json:"billing_address"` + CustomFields Optional[CustomerChangeCustomFields] `json:"custom_fields"` } -// MarshalJSON implements the json.Marshaler interface for CustomerChange. +// MarshalJSON implements the json.Marshaler interface for CustomerChange. // It customizes the JSON marshaling process for CustomerChange objects. func (c *CustomerChange) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CustomerChange object to a map representation for JSON marshaling. func (c *CustomerChange) toMap() map[string]any { - structMap := make(map[string]any) - if c.Payer.IsValueSet() { - structMap["payer"] = c.Payer.Value() - } - if c.ShippingAddress.IsValueSet() { - structMap["shipping_address"] = c.ShippingAddress.Value() - } - if c.BillingAddress.IsValueSet() { - structMap["billing_address"] = c.BillingAddress.Value() - } - if c.CustomFields.IsValueSet() { - structMap["custom_fields"] = c.CustomFields.Value() - } - return structMap + structMap := make(map[string]any) + if c.Payer.IsValueSet() { + if c.Payer.Value() != nil { + structMap["payer"] = c.Payer.Value().toMap() + } else { + structMap["payer"] = nil + } + } + if c.ShippingAddress.IsValueSet() { + if c.ShippingAddress.Value() != nil { + structMap["shipping_address"] = c.ShippingAddress.Value().toMap() + } else { + structMap["shipping_address"] = nil + } + } + if c.BillingAddress.IsValueSet() { + if c.BillingAddress.Value() != nil { + structMap["billing_address"] = c.BillingAddress.Value().toMap() + } else { + structMap["billing_address"] = nil + } + } + if c.CustomFields.IsValueSet() { + if c.CustomFields.Value() != nil { + structMap["custom_fields"] = c.CustomFields.Value().toMap() + } else { + structMap["custom_fields"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CustomerChange. +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerChange. // It customizes the JSON unmarshaling process for CustomerChange objects. func (c *CustomerChange) UnmarshalJSON(input []byte) error { - temp := &struct { - Payer Optional[CustomerPayerChange] `json:"payer"` - ShippingAddress Optional[AddressChange] `json:"shipping_address"` - BillingAddress Optional[AddressChange] `json:"billing_address"` - CustomFields Optional[CustomerCustomFieldsChange] `json:"custom_fields"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Payer = temp.Payer - c.ShippingAddress = temp.ShippingAddress - c.BillingAddress = temp.BillingAddress - c.CustomFields = temp.CustomFields - return nil + var temp customerChange + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Payer = temp.Payer + c.ShippingAddress = temp.ShippingAddress + c.BillingAddress = temp.BillingAddress + c.CustomFields = temp.CustomFields + return nil +} + +// TODO +type customerChange struct { + Payer Optional[CustomerChangePayer] `json:"payer"` + ShippingAddress Optional[CustomerChangeShippingAddress] `json:"shipping_address"` + BillingAddress Optional[CustomerChangeBillingAddress] `json:"billing_address"` + CustomFields Optional[CustomerChangeCustomFields] `json:"custom_fields"` } diff --git a/models/customer_change_billing_address.go b/models/customer_change_billing_address.go new file mode 100644 index 00000000..b5bfd421 --- /dev/null +++ b/models/customer_change_billing_address.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CustomerChangeBillingAddress represents a CustomerChangeBillingAddress struct. +// This is a container for one-of cases. +type CustomerChangeBillingAddress struct { + value any + isAddressChange bool +} + +// String converts the CustomerChangeBillingAddress object to a string representation. +func (c CustomerChangeBillingAddress) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CustomerChangeBillingAddress. +// It customizes the JSON marshaling process for CustomerChangeBillingAddress objects. +func (c *CustomerChangeBillingAddress) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CustomerChangeBillingAddressContainer.From*` functions to initialize the CustomerChangeBillingAddress object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CustomerChangeBillingAddress object to a map representation for JSON marshaling. +func (c *CustomerChangeBillingAddress) toMap() any { + switch obj := c.value.(type) { + case *AddressChange: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerChangeBillingAddress. +// It customizes the JSON unmarshaling process for CustomerChangeBillingAddress objects. +func (c *CustomerChangeBillingAddress) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&AddressChange{}, false, &c.isAddressChange), + ) + + c.value = result + return err +} + +func (c *CustomerChangeBillingAddress) AsAddressChange() ( + *AddressChange, + bool) { + if !c.isAddressChange { + return nil, false + } + return c.value.(*AddressChange), true +} + +// internalCustomerChangeBillingAddress represents a customerChangeBillingAddress struct. +// This is a container for one-of cases. +type internalCustomerChangeBillingAddress struct{} + +var CustomerChangeBillingAddressContainer internalCustomerChangeBillingAddress + +func (c *internalCustomerChangeBillingAddress) FromAddressChange(val AddressChange) CustomerChangeBillingAddress { + return CustomerChangeBillingAddress{value: &val} +} diff --git a/models/customer_change_custom_fields.go b/models/customer_change_custom_fields.go new file mode 100644 index 00000000..7c264f6a --- /dev/null +++ b/models/customer_change_custom_fields.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CustomerChangeCustomFields represents a CustomerChangeCustomFields struct. +// This is a container for one-of cases. +type CustomerChangeCustomFields struct { + value any + isCustomerCustomFieldsChange bool +} + +// String converts the CustomerChangeCustomFields object to a string representation. +func (c CustomerChangeCustomFields) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CustomerChangeCustomFields. +// It customizes the JSON marshaling process for CustomerChangeCustomFields objects. +func (c *CustomerChangeCustomFields) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CustomerChangeCustomFieldsContainer.From*` functions to initialize the CustomerChangeCustomFields object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CustomerChangeCustomFields object to a map representation for JSON marshaling. +func (c *CustomerChangeCustomFields) toMap() any { + switch obj := c.value.(type) { + case *CustomerCustomFieldsChange: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerChangeCustomFields. +// It customizes the JSON unmarshaling process for CustomerChangeCustomFields objects. +func (c *CustomerChangeCustomFields) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&CustomerCustomFieldsChange{}, false, &c.isCustomerCustomFieldsChange), + ) + + c.value = result + return err +} + +func (c *CustomerChangeCustomFields) AsCustomerCustomFieldsChange() ( + *CustomerCustomFieldsChange, + bool) { + if !c.isCustomerCustomFieldsChange { + return nil, false + } + return c.value.(*CustomerCustomFieldsChange), true +} + +// internalCustomerChangeCustomFields represents a customerChangeCustomFields struct. +// This is a container for one-of cases. +type internalCustomerChangeCustomFields struct{} + +var CustomerChangeCustomFieldsContainer internalCustomerChangeCustomFields + +func (c *internalCustomerChangeCustomFields) FromCustomerCustomFieldsChange(val CustomerCustomFieldsChange) CustomerChangeCustomFields { + return CustomerChangeCustomFields{value: &val} +} diff --git a/models/customer_change_payer.go b/models/customer_change_payer.go new file mode 100644 index 00000000..5e37331a --- /dev/null +++ b/models/customer_change_payer.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CustomerChangePayer represents a CustomerChangePayer struct. +// This is a container for one-of cases. +type CustomerChangePayer struct { + value any + isCustomerPayerChange bool +} + +// String converts the CustomerChangePayer object to a string representation. +func (c CustomerChangePayer) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CustomerChangePayer. +// It customizes the JSON marshaling process for CustomerChangePayer objects. +func (c *CustomerChangePayer) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CustomerChangePayerContainer.From*` functions to initialize the CustomerChangePayer object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CustomerChangePayer object to a map representation for JSON marshaling. +func (c *CustomerChangePayer) toMap() any { + switch obj := c.value.(type) { + case *CustomerPayerChange: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerChangePayer. +// It customizes the JSON unmarshaling process for CustomerChangePayer objects. +func (c *CustomerChangePayer) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&CustomerPayerChange{}, false, &c.isCustomerPayerChange), + ) + + c.value = result + return err +} + +func (c *CustomerChangePayer) AsCustomerPayerChange() ( + *CustomerPayerChange, + bool) { + if !c.isCustomerPayerChange { + return nil, false + } + return c.value.(*CustomerPayerChange), true +} + +// internalCustomerChangePayer represents a customerChangePayer struct. +// This is a container for one-of cases. +type internalCustomerChangePayer struct{} + +var CustomerChangePayerContainer internalCustomerChangePayer + +func (c *internalCustomerChangePayer) FromCustomerPayerChange(val CustomerPayerChange) CustomerChangePayer { + return CustomerChangePayer{value: &val} +} diff --git a/models/customer_change_shipping_address.go b/models/customer_change_shipping_address.go new file mode 100644 index 00000000..bb2f90e2 --- /dev/null +++ b/models/customer_change_shipping_address.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CustomerChangeShippingAddress represents a CustomerChangeShippingAddress struct. +// This is a container for one-of cases. +type CustomerChangeShippingAddress struct { + value any + isAddressChange bool +} + +// String converts the CustomerChangeShippingAddress object to a string representation. +func (c CustomerChangeShippingAddress) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CustomerChangeShippingAddress. +// It customizes the JSON marshaling process for CustomerChangeShippingAddress objects. +func (c *CustomerChangeShippingAddress) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CustomerChangeShippingAddressContainer.From*` functions to initialize the CustomerChangeShippingAddress object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CustomerChangeShippingAddress object to a map representation for JSON marshaling. +func (c *CustomerChangeShippingAddress) toMap() any { + switch obj := c.value.(type) { + case *AddressChange: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerChangeShippingAddress. +// It customizes the JSON unmarshaling process for CustomerChangeShippingAddress objects. +func (c *CustomerChangeShippingAddress) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&AddressChange{}, false, &c.isAddressChange), + ) + + c.value = result + return err +} + +func (c *CustomerChangeShippingAddress) AsAddressChange() ( + *AddressChange, + bool) { + if !c.isAddressChange { + return nil, false + } + return c.value.(*AddressChange), true +} + +// internalCustomerChangeShippingAddress represents a customerChangeShippingAddress struct. +// This is a container for one-of cases. +type internalCustomerChangeShippingAddress struct{} + +var CustomerChangeShippingAddressContainer internalCustomerChangeShippingAddress + +func (c *internalCustomerChangeShippingAddress) FromAddressChange(val AddressChange) CustomerChangeShippingAddress { + return CustomerChangeShippingAddress{value: &val} +} diff --git a/models/customer_changes_preview_response.go b/models/customer_changes_preview_response.go index d3b8035c..d3ef9d43 100644 --- a/models/customer_changes_preview_response.go +++ b/models/customer_changes_preview_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CustomerChangesPreviewResponse represents a CustomerChangesPreviewResponse struct. type CustomerChangesPreviewResponse struct { - Changes CustomerChange `json:"changes"` + Changes CustomerChange `json:"changes"` } -// MarshalJSON implements the json.Marshaler interface for CustomerChangesPreviewResponse. +// MarshalJSON implements the json.Marshaler interface for CustomerChangesPreviewResponse. // It customizes the JSON marshaling process for CustomerChangesPreviewResponse objects. func (c *CustomerChangesPreviewResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CustomerChangesPreviewResponse object to a map representation for JSON marshaling. func (c *CustomerChangesPreviewResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["changes"] = c.Changes.toMap() - return structMap + structMap := make(map[string]any) + structMap["changes"] = c.Changes.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CustomerChangesPreviewResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerChangesPreviewResponse. // It customizes the JSON unmarshaling process for CustomerChangesPreviewResponse objects. func (c *CustomerChangesPreviewResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Changes CustomerChange `json:"changes"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Changes = temp.Changes - return nil + var temp customerChangesPreviewResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Changes = *temp.Changes + return nil +} + +// TODO +type customerChangesPreviewResponse struct { + Changes *CustomerChange `json:"changes"` +} + +func (c *customerChangesPreviewResponse) validate() error { + var errs []string + if c.Changes == nil { + errs = append(errs, "required field `changes` is missing for type `Customer Changes Preview Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/customer_custom_fields_change.go b/models/customer_custom_fields_change.go index 1a7550e3..cbc6e4ff 100644 --- a/models/customer_custom_fields_change.go +++ b/models/customer_custom_fields_change.go @@ -1,44 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CustomerCustomFieldsChange represents a CustomerCustomFieldsChange struct. type CustomerCustomFieldsChange struct { - Before []InvoiceCustomField `json:"before"` - After []InvoiceCustomField `json:"after"` + Before []InvoiceCustomField `json:"before"` + After []InvoiceCustomField `json:"after"` } -// MarshalJSON implements the json.Marshaler interface for CustomerCustomFieldsChange. +// MarshalJSON implements the json.Marshaler interface for CustomerCustomFieldsChange. // It customizes the JSON marshaling process for CustomerCustomFieldsChange objects. func (c *CustomerCustomFieldsChange) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CustomerCustomFieldsChange object to a map representation for JSON marshaling. func (c *CustomerCustomFieldsChange) toMap() map[string]any { - structMap := make(map[string]any) - structMap["before"] = c.Before - structMap["after"] = c.After - return structMap + structMap := make(map[string]any) + structMap["before"] = c.Before + structMap["after"] = c.After + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CustomerCustomFieldsChange. +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerCustomFieldsChange. // It customizes the JSON unmarshaling process for CustomerCustomFieldsChange objects. func (c *CustomerCustomFieldsChange) UnmarshalJSON(input []byte) error { - temp := &struct { - Before []InvoiceCustomField `json:"before"` - After []InvoiceCustomField `json:"after"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Before = temp.Before - c.After = temp.After - return nil + var temp customerCustomFieldsChange + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Before = *temp.Before + c.After = *temp.After + return nil +} + +// TODO +type customerCustomFieldsChange struct { + Before *[]InvoiceCustomField `json:"before"` + After *[]InvoiceCustomField `json:"after"` +} + +func (c *customerCustomFieldsChange) validate() error { + var errs []string + if c.Before == nil { + errs = append(errs, "required field `before` is missing for type `Customer Custom Fields Change`") + } + if c.After == nil { + errs = append(errs, "required field `after` is missing for type `Customer Custom Fields Change`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/customer_error.go b/models/customer_error.go new file mode 100644 index 00000000..14dd2e45 --- /dev/null +++ b/models/customer_error.go @@ -0,0 +1,44 @@ +package models + +import ( + "encoding/json" +) + +// CustomerError represents a CustomerError struct. +type CustomerError struct { + Customer *string `json:"customer,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for CustomerError. +// It customizes the JSON marshaling process for CustomerError objects. +func (c *CustomerError) MarshalJSON() ( + []byte, + error) { + return json.Marshal(c.toMap()) +} + +// toMap converts the CustomerError object to a map representation for JSON marshaling. +func (c *CustomerError) toMap() map[string]any { + structMap := make(map[string]any) + if c.Customer != nil { + structMap["customer"] = c.Customer + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerError. +// It customizes the JSON unmarshaling process for CustomerError objects. +func (c *CustomerError) UnmarshalJSON(input []byte) error { + var temp customerError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + c.Customer = temp.Customer + return nil +} + +// TODO +type customerError struct { + Customer *string `json:"customer,omitempty"` +} diff --git a/models/customer_error_response_errors.go b/models/customer_error_response_errors.go new file mode 100644 index 00000000..9f5ff016 --- /dev/null +++ b/models/customer_error_response_errors.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// CustomerErrorResponseErrors represents a CustomerErrorResponseErrors struct. +// This is a container for one-of cases. +type CustomerErrorResponseErrors struct { + value any + isCustomerError bool + isArrayOfString bool +} + +// String converts the CustomerErrorResponseErrors object to a string representation. +func (c CustomerErrorResponseErrors) String() string { + if bytes, err := json.Marshal(c.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for CustomerErrorResponseErrors. +// It customizes the JSON marshaling process for CustomerErrorResponseErrors objects. +func (c *CustomerErrorResponseErrors) MarshalJSON() ( + []byte, + error) { + if c.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.CustomerErrorResponseErrorsContainer.From*` functions to initialize the CustomerErrorResponseErrors object.") + } + return json.Marshal(c.toMap()) +} + +// toMap converts the CustomerErrorResponseErrors object to a map representation for JSON marshaling. +func (c *CustomerErrorResponseErrors) toMap() any { + switch obj := c.value.(type) { + case *CustomerError: + return obj.toMap() + case *[]string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerErrorResponseErrors. +// It customizes the JSON unmarshaling process for CustomerErrorResponseErrors objects. +func (c *CustomerErrorResponseErrors) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&CustomerError{}, false, &c.isCustomerError), + NewTypeHolder(new([]string), false, &c.isArrayOfString), + ) + + c.value = result + return err +} + +func (c *CustomerErrorResponseErrors) AsCustomerError() ( + *CustomerError, + bool) { + if !c.isCustomerError { + return nil, false + } + return c.value.(*CustomerError), true +} + +func (c *CustomerErrorResponseErrors) AsArrayOfString() ( + *[]string, + bool) { + if !c.isArrayOfString { + return nil, false + } + return c.value.(*[]string), true +} + +// internalCustomerErrorResponseErrors represents a customerErrorResponseErrors struct. +// This is a container for one-of cases. +type internalCustomerErrorResponseErrors struct{} + +var CustomerErrorResponseErrorsContainer internalCustomerErrorResponseErrors + +func (c *internalCustomerErrorResponseErrors) FromCustomerError(val CustomerError) CustomerErrorResponseErrors { + return CustomerErrorResponseErrors{value: &val} +} + +func (c *internalCustomerErrorResponseErrors) FromArrayOfString(val []string) CustomerErrorResponseErrors { + return CustomerErrorResponseErrors{value: &val} +} diff --git a/models/customer_payer_change.go b/models/customer_payer_change.go index e5ec1b3d..d91f31c4 100644 --- a/models/customer_payer_change.go +++ b/models/customer_payer_change.go @@ -1,44 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CustomerPayerChange represents a CustomerPayerChange struct. type CustomerPayerChange struct { - Before InvoicePayerChange `json:"before"` - After InvoicePayerChange `json:"after"` + Before InvoicePayerChange `json:"before"` + After InvoicePayerChange `json:"after"` } -// MarshalJSON implements the json.Marshaler interface for CustomerPayerChange. +// MarshalJSON implements the json.Marshaler interface for CustomerPayerChange. // It customizes the JSON marshaling process for CustomerPayerChange objects. func (c *CustomerPayerChange) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CustomerPayerChange object to a map representation for JSON marshaling. func (c *CustomerPayerChange) toMap() map[string]any { - structMap := make(map[string]any) - structMap["before"] = c.Before.toMap() - structMap["after"] = c.After.toMap() - return structMap + structMap := make(map[string]any) + structMap["before"] = c.Before.toMap() + structMap["after"] = c.After.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CustomerPayerChange. +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerPayerChange. // It customizes the JSON unmarshaling process for CustomerPayerChange objects. func (c *CustomerPayerChange) UnmarshalJSON(input []byte) error { - temp := &struct { - Before InvoicePayerChange `json:"before"` - After InvoicePayerChange `json:"after"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Before = temp.Before - c.After = temp.After - return nil + var temp customerPayerChange + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Before = *temp.Before + c.After = *temp.After + return nil +} + +// TODO +type customerPayerChange struct { + Before *InvoicePayerChange `json:"before"` + After *InvoicePayerChange `json:"after"` +} + +func (c *customerPayerChange) validate() error { + var errs []string + if c.Before == nil { + errs = append(errs, "required field `before` is missing for type `Customer Payer Change`") + } + if c.After == nil { + errs = append(errs, "required field `after` is missing for type `Customer Payer Change`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/customer_response.go b/models/customer_response.go index 97be6aa8..7ca7847e 100644 --- a/models/customer_response.go +++ b/models/customer_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // CustomerResponse represents a CustomerResponse struct. type CustomerResponse struct { - Customer Customer `json:"customer"` + Customer Customer `json:"customer"` } -// MarshalJSON implements the json.Marshaler interface for CustomerResponse. +// MarshalJSON implements the json.Marshaler interface for CustomerResponse. // It customizes the JSON marshaling process for CustomerResponse objects. func (c *CustomerResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(c.toMap()) + []byte, + error) { + return json.Marshal(c.toMap()) } // toMap converts the CustomerResponse object to a map representation for JSON marshaling. func (c *CustomerResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["customer"] = c.Customer.toMap() - return structMap + structMap := make(map[string]any) + structMap["customer"] = c.Customer.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for CustomerResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for CustomerResponse. // It customizes the JSON unmarshaling process for CustomerResponse objects. func (c *CustomerResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Customer Customer `json:"customer"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - c.Customer = temp.Customer - return nil + var temp customerResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + c.Customer = *temp.Customer + return nil +} + +// TODO +type customerResponse struct { + Customer *Customer `json:"customer"` +} + +func (c *customerResponse) validate() error { + var errs []string + if c.Customer == nil { + errs = append(errs, "required field `customer` is missing for type `Customer Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/deduct_service_credit.go b/models/deduct_service_credit.go index 9a2331d6..128e25a9 100644 --- a/models/deduct_service_credit.go +++ b/models/deduct_service_credit.go @@ -1,44 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // DeductServiceCredit represents a DeductServiceCredit struct. type DeductServiceCredit struct { - Amount interface{} `json:"amount"` - Memo string `json:"memo"` + Amount DeductServiceCreditAmount `json:"amount"` + Memo string `json:"memo"` } -// MarshalJSON implements the json.Marshaler interface for DeductServiceCredit. +// MarshalJSON implements the json.Marshaler interface for DeductServiceCredit. // It customizes the JSON marshaling process for DeductServiceCredit objects. func (d *DeductServiceCredit) MarshalJSON() ( - []byte, - error) { - return json.Marshal(d.toMap()) + []byte, + error) { + return json.Marshal(d.toMap()) } // toMap converts the DeductServiceCredit object to a map representation for JSON marshaling. func (d *DeductServiceCredit) toMap() map[string]any { - structMap := make(map[string]any) - structMap["amount"] = d.Amount - structMap["memo"] = d.Memo - return structMap + structMap := make(map[string]any) + structMap["amount"] = d.Amount.toMap() + structMap["memo"] = d.Memo + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for DeductServiceCredit. +// UnmarshalJSON implements the json.Unmarshaler interface for DeductServiceCredit. // It customizes the JSON unmarshaling process for DeductServiceCredit objects. func (d *DeductServiceCredit) UnmarshalJSON(input []byte) error { - temp := &struct { - Amount interface{} `json:"amount"` - Memo string `json:"memo"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - d.Amount = temp.Amount - d.Memo = temp.Memo - return nil + var temp deductServiceCredit + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + d.Amount = *temp.Amount + d.Memo = *temp.Memo + return nil +} + +// TODO +type deductServiceCredit struct { + Amount *DeductServiceCreditAmount `json:"amount"` + Memo *string `json:"memo"` +} + +func (d *deductServiceCredit) validate() error { + var errs []string + if d.Amount == nil { + errs = append(errs, "required field `amount` is missing for type `Deduct Service Credit`") + } + if d.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Deduct Service Credit`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/deduct_service_credit_amount.go b/models/deduct_service_credit_amount.go new file mode 100644 index 00000000..f2306335 --- /dev/null +++ b/models/deduct_service_credit_amount.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// DeductServiceCreditAmount represents a DeductServiceCreditAmount struct. +// This is a container for one-of cases. +type DeductServiceCreditAmount struct { + value any + isString bool + isPrecision bool +} + +// String converts the DeductServiceCreditAmount object to a string representation. +func (d DeductServiceCreditAmount) String() string { + if bytes, err := json.Marshal(d.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for DeductServiceCreditAmount. +// It customizes the JSON marshaling process for DeductServiceCreditAmount objects. +func (d *DeductServiceCreditAmount) MarshalJSON() ( + []byte, + error) { + if d.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.DeductServiceCreditAmountContainer.From*` functions to initialize the DeductServiceCreditAmount object.") + } + return json.Marshal(d.toMap()) +} + +// toMap converts the DeductServiceCreditAmount object to a map representation for JSON marshaling. +func (d *DeductServiceCreditAmount) toMap() any { + switch obj := d.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for DeductServiceCreditAmount. +// It customizes the JSON unmarshaling process for DeductServiceCreditAmount objects. +func (d *DeductServiceCreditAmount) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &d.isString), + NewTypeHolder(new(float64), false, &d.isPrecision), + ) + + d.value = result + return err +} + +func (d *DeductServiceCreditAmount) AsString() ( + *string, + bool) { + if !d.isString { + return nil, false + } + return d.value.(*string), true +} + +func (d *DeductServiceCreditAmount) AsPrecision() ( + *float64, + bool) { + if !d.isPrecision { + return nil, false + } + return d.value.(*float64), true +} + +// internalDeductServiceCreditAmount represents a deductServiceCreditAmount struct. +// This is a container for one-of cases. +type internalDeductServiceCreditAmount struct{} + +var DeductServiceCreditAmountContainer internalDeductServiceCreditAmount + +func (d *internalDeductServiceCreditAmount) FromString(val string) DeductServiceCreditAmount { + return DeductServiceCreditAmount{value: &val} +} + +func (d *internalDeductServiceCreditAmount) FromPrecision(val float64) DeductServiceCreditAmount { + return DeductServiceCreditAmount{value: &val} +} diff --git a/models/deduct_service_credit_request.go b/models/deduct_service_credit_request.go index eed78ac3..fdad8c1c 100644 --- a/models/deduct_service_credit_request.go +++ b/models/deduct_service_credit_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // DeductServiceCreditRequest represents a DeductServiceCreditRequest struct. type DeductServiceCreditRequest struct { - Deduction DeductServiceCredit `json:"deduction"` + Deduction DeductServiceCredit `json:"deduction"` } -// MarshalJSON implements the json.Marshaler interface for DeductServiceCreditRequest. +// MarshalJSON implements the json.Marshaler interface for DeductServiceCreditRequest. // It customizes the JSON marshaling process for DeductServiceCreditRequest objects. func (d *DeductServiceCreditRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(d.toMap()) + []byte, + error) { + return json.Marshal(d.toMap()) } // toMap converts the DeductServiceCreditRequest object to a map representation for JSON marshaling. func (d *DeductServiceCreditRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["deduction"] = d.Deduction.toMap() - return structMap + structMap := make(map[string]any) + structMap["deduction"] = d.Deduction.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for DeductServiceCreditRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for DeductServiceCreditRequest. // It customizes the JSON unmarshaling process for DeductServiceCreditRequest objects. func (d *DeductServiceCreditRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Deduction DeductServiceCredit `json:"deduction"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - d.Deduction = temp.Deduction - return nil + var temp deductServiceCreditRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + d.Deduction = *temp.Deduction + return nil +} + +// TODO +type deductServiceCreditRequest struct { + Deduction *DeductServiceCredit `json:"deduction"` +} + +func (d *deductServiceCreditRequest) validate() error { + var errs []string + if d.Deduction == nil { + errs = append(errs, "required field `deduction` is missing for type `Deduct Service Credit Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/delayed_cancellation_response.go b/models/delayed_cancellation_response.go index e42af920..d6a7e4e6 100644 --- a/models/delayed_cancellation_response.go +++ b/models/delayed_cancellation_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // DelayedCancellationResponse represents a DelayedCancellationResponse struct. type DelayedCancellationResponse struct { - Message *string `json:"message,omitempty"` + Message *string `json:"message,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for DelayedCancellationResponse. +// MarshalJSON implements the json.Marshaler interface for DelayedCancellationResponse. // It customizes the JSON marshaling process for DelayedCancellationResponse objects. func (d *DelayedCancellationResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(d.toMap()) + []byte, + error) { + return json.Marshal(d.toMap()) } // toMap converts the DelayedCancellationResponse object to a map representation for JSON marshaling. func (d *DelayedCancellationResponse) toMap() map[string]any { - structMap := make(map[string]any) - if d.Message != nil { - structMap["message"] = d.Message - } - return structMap + structMap := make(map[string]any) + if d.Message != nil { + structMap["message"] = d.Message + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for DelayedCancellationResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for DelayedCancellationResponse. // It customizes the JSON unmarshaling process for DelayedCancellationResponse objects. func (d *DelayedCancellationResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Message *string `json:"message,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - d.Message = temp.Message - return nil + var temp delayedCancellationResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + d.Message = temp.Message + return nil +} + +// TODO +type delayedCancellationResponse struct { + Message *string `json:"message,omitempty"` } diff --git a/models/delete_subscription_group_response.go b/models/delete_subscription_group_response.go index 20e24c2e..1e140dd6 100644 --- a/models/delete_subscription_group_response.go +++ b/models/delete_subscription_group_response.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // DeleteSubscriptionGroupResponse represents a DeleteSubscriptionGroupResponse struct. type DeleteSubscriptionGroupResponse struct { - Uid *string `json:"uid,omitempty"` - Deleted *bool `json:"deleted,omitempty"` + Uid *string `json:"uid,omitempty"` + Deleted *bool `json:"deleted,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for DeleteSubscriptionGroupResponse. +// MarshalJSON implements the json.Marshaler interface for DeleteSubscriptionGroupResponse. // It customizes the JSON marshaling process for DeleteSubscriptionGroupResponse objects. func (d *DeleteSubscriptionGroupResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(d.toMap()) + []byte, + error) { + return json.Marshal(d.toMap()) } // toMap converts the DeleteSubscriptionGroupResponse object to a map representation for JSON marshaling. func (d *DeleteSubscriptionGroupResponse) toMap() map[string]any { - structMap := make(map[string]any) - if d.Uid != nil { - structMap["uid"] = d.Uid - } - if d.Deleted != nil { - structMap["deleted"] = d.Deleted - } - return structMap + structMap := make(map[string]any) + if d.Uid != nil { + structMap["uid"] = d.Uid + } + if d.Deleted != nil { + structMap["deleted"] = d.Deleted + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for DeleteSubscriptionGroupResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for DeleteSubscriptionGroupResponse. // It customizes the JSON unmarshaling process for DeleteSubscriptionGroupResponse objects. func (d *DeleteSubscriptionGroupResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Deleted *bool `json:"deleted,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - d.Uid = temp.Uid - d.Deleted = temp.Deleted - return nil + var temp deleteSubscriptionGroupResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + d.Uid = temp.Uid + d.Deleted = temp.Deleted + return nil +} + +// TODO +type deleteSubscriptionGroupResponse struct { + Uid *string `json:"uid,omitempty"` + Deleted *bool `json:"deleted,omitempty"` } diff --git a/models/dunner_data.go b/models/dunner_data.go new file mode 100644 index 00000000..f573a65d --- /dev/null +++ b/models/dunner_data.go @@ -0,0 +1,105 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// DunnerData represents a DunnerData struct. +type DunnerData struct { + State string `json:"state"` + SubscriptionId int `json:"subscription_id"` + RevenueAtRiskInCents int64 `json:"revenue_at_risk_in_cents"` + CreatedAt time.Time `json:"created_at"` + Attempts int `json:"attempts"` + LastAttemptedAt time.Time `json:"last_attempted_at"` +} + +// MarshalJSON implements the json.Marshaler interface for DunnerData. +// It customizes the JSON marshaling process for DunnerData objects. +func (d *DunnerData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(d.toMap()) +} + +// toMap converts the DunnerData object to a map representation for JSON marshaling. +func (d *DunnerData) toMap() map[string]any { + structMap := make(map[string]any) + structMap["state"] = d.State + structMap["subscription_id"] = d.SubscriptionId + structMap["revenue_at_risk_in_cents"] = d.RevenueAtRiskInCents + structMap["created_at"] = d.CreatedAt.Format(time.RFC3339) + structMap["attempts"] = d.Attempts + structMap["last_attempted_at"] = d.LastAttemptedAt.Format(time.RFC3339) + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for DunnerData. +// It customizes the JSON unmarshaling process for DunnerData objects. +func (d *DunnerData) UnmarshalJSON(input []byte) error { + var temp dunnerData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + d.State = *temp.State + d.SubscriptionId = *temp.SubscriptionId + d.RevenueAtRiskInCents = *temp.RevenueAtRiskInCents + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + d.CreatedAt = CreatedAtVal + d.Attempts = *temp.Attempts + LastAttemptedAtVal, err := time.Parse(time.RFC3339, *temp.LastAttemptedAt) + if err != nil { + log.Fatalf("Cannot Parse last_attempted_at as % s format.", time.RFC3339) + } + d.LastAttemptedAt = LastAttemptedAtVal + return nil +} + +// TODO +type dunnerData struct { + State *string `json:"state"` + SubscriptionId *int `json:"subscription_id"` + RevenueAtRiskInCents *int64 `json:"revenue_at_risk_in_cents"` + CreatedAt *string `json:"created_at"` + Attempts *int `json:"attempts"` + LastAttemptedAt *string `json:"last_attempted_at"` +} + +func (d *dunnerData) validate() error { + var errs []string + if d.State == nil { + errs = append(errs, "required field `state` is missing for type `Dunner Data`") + } + if d.SubscriptionId == nil { + errs = append(errs, "required field `subscription_id` is missing for type `Dunner Data`") + } + if d.RevenueAtRiskInCents == nil { + errs = append(errs, "required field `revenue_at_risk_in_cents` is missing for type `Dunner Data`") + } + if d.CreatedAt == nil { + errs = append(errs, "required field `created_at` is missing for type `Dunner Data`") + } + if d.Attempts == nil { + errs = append(errs, "required field `attempts` is missing for type `Dunner Data`") + } + if d.LastAttemptedAt == nil { + errs = append(errs, "required field `last_attempted_at` is missing for type `Dunner Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/dunning_step_data.go b/models/dunning_step_data.go new file mode 100644 index 00000000..8f7547ee --- /dev/null +++ b/models/dunning_step_data.go @@ -0,0 +1,118 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// DunningStepData represents a DunningStepData struct. +type DunningStepData struct { + DayThreshold int `json:"day_threshold"` + Action string `json:"action"` + EmailBody Optional[string] `json:"email_body"` + EmailSubject Optional[string] `json:"email_subject"` + SendEmail bool `json:"send_email"` + SendBccEmail bool `json:"send_bcc_email"` + SendSms bool `json:"send_sms"` + SmsBody Optional[string] `json:"sms_body"` +} + +// MarshalJSON implements the json.Marshaler interface for DunningStepData. +// It customizes the JSON marshaling process for DunningStepData objects. +func (d *DunningStepData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(d.toMap()) +} + +// toMap converts the DunningStepData object to a map representation for JSON marshaling. +func (d *DunningStepData) toMap() map[string]any { + structMap := make(map[string]any) + structMap["day_threshold"] = d.DayThreshold + structMap["action"] = d.Action + if d.EmailBody.IsValueSet() { + if d.EmailBody.Value() != nil { + structMap["email_body"] = d.EmailBody.Value() + } else { + structMap["email_body"] = nil + } + } + if d.EmailSubject.IsValueSet() { + if d.EmailSubject.Value() != nil { + structMap["email_subject"] = d.EmailSubject.Value() + } else { + structMap["email_subject"] = nil + } + } + structMap["send_email"] = d.SendEmail + structMap["send_bcc_email"] = d.SendBccEmail + structMap["send_sms"] = d.SendSms + if d.SmsBody.IsValueSet() { + if d.SmsBody.Value() != nil { + structMap["sms_body"] = d.SmsBody.Value() + } else { + structMap["sms_body"] = nil + } + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for DunningStepData. +// It customizes the JSON unmarshaling process for DunningStepData objects. +func (d *DunningStepData) UnmarshalJSON(input []byte) error { + var temp dunningStepData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + d.DayThreshold = *temp.DayThreshold + d.Action = *temp.Action + d.EmailBody = temp.EmailBody + d.EmailSubject = temp.EmailSubject + d.SendEmail = *temp.SendEmail + d.SendBccEmail = *temp.SendBccEmail + d.SendSms = *temp.SendSms + d.SmsBody = temp.SmsBody + return nil +} + +// TODO +type dunningStepData struct { + DayThreshold *int `json:"day_threshold"` + Action *string `json:"action"` + EmailBody Optional[string] `json:"email_body"` + EmailSubject Optional[string] `json:"email_subject"` + SendEmail *bool `json:"send_email"` + SendBccEmail *bool `json:"send_bcc_email"` + SendSms *bool `json:"send_sms"` + SmsBody Optional[string] `json:"sms_body"` +} + +func (d *dunningStepData) validate() error { + var errs []string + if d.DayThreshold == nil { + errs = append(errs, "required field `day_threshold` is missing for type `Dunning Step Data`") + } + if d.Action == nil { + errs = append(errs, "required field `action` is missing for type `Dunning Step Data`") + } + if d.SendEmail == nil { + errs = append(errs, "required field `send_email` is missing for type `Dunning Step Data`") + } + if d.SendBccEmail == nil { + errs = append(errs, "required field `send_bcc_email` is missing for type `Dunning Step Data`") + } + if d.SendSms == nil { + errs = append(errs, "required field `send_sms` is missing for type `Dunning Step Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/dunning_step_reached.go b/models/dunning_step_reached.go new file mode 100644 index 00000000..c6a00935 --- /dev/null +++ b/models/dunning_step_reached.go @@ -0,0 +1,74 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// DunningStepReached represents a DunningStepReached struct. +type DunningStepReached struct { + Dunner DunnerData `json:"dunner"` + CurrentStep DunningStepData `json:"current_step"` + NextStep DunningStepData `json:"next_step"` +} + +// MarshalJSON implements the json.Marshaler interface for DunningStepReached. +// It customizes the JSON marshaling process for DunningStepReached objects. +func (d *DunningStepReached) MarshalJSON() ( + []byte, + error) { + return json.Marshal(d.toMap()) +} + +// toMap converts the DunningStepReached object to a map representation for JSON marshaling. +func (d *DunningStepReached) toMap() map[string]any { + structMap := make(map[string]any) + structMap["dunner"] = d.Dunner.toMap() + structMap["current_step"] = d.CurrentStep.toMap() + structMap["next_step"] = d.NextStep.toMap() + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for DunningStepReached. +// It customizes the JSON unmarshaling process for DunningStepReached objects. +func (d *DunningStepReached) UnmarshalJSON(input []byte) error { + var temp dunningStepReached + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + d.Dunner = *temp.Dunner + d.CurrentStep = *temp.CurrentStep + d.NextStep = *temp.NextStep + return nil +} + +// TODO +type dunningStepReached struct { + Dunner *DunnerData `json:"dunner"` + CurrentStep *DunningStepData `json:"current_step"` + NextStep *DunningStepData `json:"next_step"` +} + +func (d *dunningStepReached) validate() error { + var errs []string + if d.Dunner == nil { + errs = append(errs, "required field `dunner` is missing for type `Dunning Step Reached`") + } + if d.CurrentStep == nil { + errs = append(errs, "required field `current_step` is missing for type `Dunning Step Reached`") + } + if d.NextStep == nil { + errs = append(errs, "required field `next_step` is missing for type `Dunning Step Reached`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/ebb_component.go b/models/ebb_component.go index 0c9f7661..fb7de8e2 100644 --- a/models/ebb_component.go +++ b/models/ebb_component.go @@ -1,148 +1,185 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // EBBComponent represents a EBBComponent struct. type EBBComponent struct { - // A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". - Name string `json:"name"` - // The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item - UnitName string `json:"unit_name"` - // A description for the component that will be displayed to the user on the hosted signup page. - Description *string `json:"description,omitempty"` - // A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'. - Handle *string `json:"handle,omitempty"` - // Boolean flag describing whether a component is taxable or not. - Taxable *bool `json:"taxable,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme PricingScheme `json:"pricing_scheme"` - // (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://help.chargify.com/products/product-components.html#general-price-bracket-rules) for an overview of how price brackets work for different pricing schemes. - Prices []Price `json:"prices,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` - // The amount the customer will be charged per unit when the pricing scheme is “per_unit”. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 - UnitPrice *interface{} `json:"unit_price,omitempty"` - // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. - TaxCode *string `json:"tax_code,omitempty"` - // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - // deprecated May 2011 - use unit_price instead - PriceInCents *string `json:"price_in_cents,omitempty"` - // The ID of an event based billing metric that will be attached to this component. - EventBasedBillingMetricId int `json:"event_based_billing_metric_id"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + // A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". + Name string `json:"name"` + // The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item + UnitName string `json:"unit_name"` + // A description for the component that will be displayed to the user on the hosted signup page. + Description *string `json:"description,omitempty"` + // A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'. + Handle *string `json:"handle,omitempty"` + // Boolean flag describing whether a component is taxable or not. + Taxable *bool `json:"taxable,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme PricingScheme `json:"pricing_scheme"` + // (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://help.chargify.com/products/product-components.html#general-price-bracket-rules) for an overview of how price brackets work for different pricing schemes. + Prices []Price `json:"prices,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` + // The amount the customer will be charged per unit when the pricing scheme is “per_unit”. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 + UnitPrice *EBBComponentUnitPrice `json:"unit_price,omitempty"` + // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. + TaxCode *string `json:"tax_code,omitempty"` + // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + // deprecated May 2011 - use unit_price instead + PriceInCents *string `json:"price_in_cents,omitempty"` + // The ID of an event based billing metric that will be attached to this component. + EventBasedBillingMetricId int `json:"event_based_billing_metric_id"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for EBBComponent. +// MarshalJSON implements the json.Marshaler interface for EBBComponent. // It customizes the JSON marshaling process for EBBComponent objects. func (e *EBBComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(e.toMap()) + []byte, + error) { + return json.Marshal(e.toMap()) } // toMap converts the EBBComponent object to a map representation for JSON marshaling. func (e *EBBComponent) toMap() map[string]any { - structMap := make(map[string]any) - structMap["name"] = e.Name - structMap["unit_name"] = e.UnitName - if e.Description != nil { - structMap["description"] = e.Description - } - if e.Handle != nil { - structMap["handle"] = e.Handle - } - if e.Taxable != nil { - structMap["taxable"] = e.Taxable - } - structMap["pricing_scheme"] = e.PricingScheme - if e.Prices != nil { - structMap["prices"] = e.Prices - } - if e.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = e.UpgradeCharge.Value() - } - if e.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = e.DowngradeCredit.Value() - } - if e.PricePoints != nil { - structMap["price_points"] = e.PricePoints - } - if e.UnitPrice != nil { - structMap["unit_price"] = e.UnitPrice - } - if e.TaxCode != nil { - structMap["tax_code"] = e.TaxCode - } - if e.HideDateRangeOnInvoice != nil { - structMap["hide_date_range_on_invoice"] = e.HideDateRangeOnInvoice - } - if e.PriceInCents != nil { - structMap["price_in_cents"] = e.PriceInCents - } - structMap["event_based_billing_metric_id"] = e.EventBasedBillingMetricId - if e.Interval != nil { - structMap["interval"] = e.Interval - } - if e.IntervalUnit != nil { - structMap["interval_unit"] = e.IntervalUnit - } - return structMap + structMap := make(map[string]any) + structMap["name"] = e.Name + structMap["unit_name"] = e.UnitName + if e.Description != nil { + structMap["description"] = e.Description + } + if e.Handle != nil { + structMap["handle"] = e.Handle + } + if e.Taxable != nil { + structMap["taxable"] = e.Taxable + } + structMap["pricing_scheme"] = e.PricingScheme + if e.Prices != nil { + structMap["prices"] = e.Prices + } + if e.UpgradeCharge.IsValueSet() { + if e.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = e.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if e.DowngradeCredit.IsValueSet() { + if e.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = e.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if e.PricePoints != nil { + structMap["price_points"] = e.PricePoints + } + if e.UnitPrice != nil { + structMap["unit_price"] = e.UnitPrice.toMap() + } + if e.TaxCode != nil { + structMap["tax_code"] = e.TaxCode + } + if e.HideDateRangeOnInvoice != nil { + structMap["hide_date_range_on_invoice"] = e.HideDateRangeOnInvoice + } + if e.PriceInCents != nil { + structMap["price_in_cents"] = e.PriceInCents + } + structMap["event_based_billing_metric_id"] = e.EventBasedBillingMetricId + if e.Interval != nil { + structMap["interval"] = e.Interval + } + if e.IntervalUnit != nil { + structMap["interval_unit"] = e.IntervalUnit + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for EBBComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for EBBComponent. // It customizes the JSON unmarshaling process for EBBComponent objects. func (e *EBBComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - Name string `json:"name"` - UnitName string `json:"unit_name"` - Description *string `json:"description,omitempty"` - Handle *string `json:"handle,omitempty"` - Taxable *bool `json:"taxable,omitempty"` - PricingScheme PricingScheme `json:"pricing_scheme"` - Prices []Price `json:"prices,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` - UnitPrice *interface{} `json:"unit_price,omitempty"` - TaxCode *string `json:"tax_code,omitempty"` - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - PriceInCents *string `json:"price_in_cents,omitempty"` - EventBasedBillingMetricId int `json:"event_based_billing_metric_id"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - e.Name = temp.Name - e.UnitName = temp.UnitName - e.Description = temp.Description - e.Handle = temp.Handle - e.Taxable = temp.Taxable - e.PricingScheme = temp.PricingScheme - e.Prices = temp.Prices - e.UpgradeCharge = temp.UpgradeCharge - e.DowngradeCredit = temp.DowngradeCredit - e.PricePoints = temp.PricePoints - e.UnitPrice = temp.UnitPrice - e.TaxCode = temp.TaxCode - e.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice - e.PriceInCents = temp.PriceInCents - e.EventBasedBillingMetricId = temp.EventBasedBillingMetricId - e.Interval = temp.Interval - e.IntervalUnit = temp.IntervalUnit - return nil + var temp ebbComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + e.Name = *temp.Name + e.UnitName = *temp.UnitName + e.Description = temp.Description + e.Handle = temp.Handle + e.Taxable = temp.Taxable + e.PricingScheme = *temp.PricingScheme + e.Prices = temp.Prices + e.UpgradeCharge = temp.UpgradeCharge + e.DowngradeCredit = temp.DowngradeCredit + e.PricePoints = temp.PricePoints + e.UnitPrice = temp.UnitPrice + e.TaxCode = temp.TaxCode + e.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice + e.PriceInCents = temp.PriceInCents + e.EventBasedBillingMetricId = *temp.EventBasedBillingMetricId + e.Interval = temp.Interval + e.IntervalUnit = temp.IntervalUnit + return nil +} + +// TODO +type ebbComponent struct { + Name *string `json:"name"` + UnitName *string `json:"unit_name"` + Description *string `json:"description,omitempty"` + Handle *string `json:"handle,omitempty"` + Taxable *bool `json:"taxable,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme"` + Prices []Price `json:"prices,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` + UnitPrice *EBBComponentUnitPrice `json:"unit_price,omitempty"` + TaxCode *string `json:"tax_code,omitempty"` + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + PriceInCents *string `json:"price_in_cents,omitempty"` + EventBasedBillingMetricId *int `json:"event_based_billing_metric_id"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` +} + +func (e *ebbComponent) validate() error { + var errs []string + if e.Name == nil { + errs = append(errs, "required field `name` is missing for type `EBB Component`") + } + if e.UnitName == nil { + errs = append(errs, "required field `unit_name` is missing for type `EBB Component`") + } + if e.PricingScheme == nil { + errs = append(errs, "required field `pricing_scheme` is missing for type `EBB Component`") + } + if e.EventBasedBillingMetricId == nil { + errs = append(errs, "required field `event_based_billing_metric_id` is missing for type `EBB Component`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/ebb_component_unit_price.go b/models/ebb_component_unit_price.go new file mode 100644 index 00000000..1247da25 --- /dev/null +++ b/models/ebb_component_unit_price.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// EBBComponentUnitPrice represents a EBBComponentUnitPrice struct. +// This is a container for one-of cases. +type EBBComponentUnitPrice struct { + value any + isString bool + isPrecision bool +} + +// String converts the EBBComponentUnitPrice object to a string representation. +func (e EBBComponentUnitPrice) String() string { + if bytes, err := json.Marshal(e.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for EBBComponentUnitPrice. +// It customizes the JSON marshaling process for EBBComponentUnitPrice objects. +func (e *EBBComponentUnitPrice) MarshalJSON() ( + []byte, + error) { + if e.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.EBBComponentUnitPriceContainer.From*` functions to initialize the EBBComponentUnitPrice object.") + } + return json.Marshal(e.toMap()) +} + +// toMap converts the EBBComponentUnitPrice object to a map representation for JSON marshaling. +func (e *EBBComponentUnitPrice) toMap() any { + switch obj := e.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for EBBComponentUnitPrice. +// It customizes the JSON unmarshaling process for EBBComponentUnitPrice objects. +func (e *EBBComponentUnitPrice) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &e.isString), + NewTypeHolder(new(float64), false, &e.isPrecision), + ) + + e.value = result + return err +} + +func (e *EBBComponentUnitPrice) AsString() ( + *string, + bool) { + if !e.isString { + return nil, false + } + return e.value.(*string), true +} + +func (e *EBBComponentUnitPrice) AsPrecision() ( + *float64, + bool) { + if !e.isPrecision { + return nil, false + } + return e.value.(*float64), true +} + +// internalEBBComponentUnitPrice represents a EBBComponentUnitPrice struct. +// This is a container for one-of cases. +type internalEBBComponentUnitPrice struct{} + +var EBBComponentUnitPriceContainer internalEBBComponentUnitPrice + +func (e *internalEBBComponentUnitPrice) FromString(val string) EBBComponentUnitPrice { + return EBBComponentUnitPrice{value: &val} +} + +func (e *internalEBBComponentUnitPrice) FromPrecision(val float64) EBBComponentUnitPrice { + return EBBComponentUnitPrice{value: &val} +} diff --git a/models/ebb_event.go b/models/ebb_event.go index 85fce699..4a27c567 100644 --- a/models/ebb_event.go +++ b/models/ebb_event.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // EBBEvent represents a EBBEvent struct. type EBBEvent struct { - Chargify *ChargifyEBB `json:"chargify,omitempty"` + Chargify *ChargifyEBB `json:"chargify,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for EBBEvent. +// MarshalJSON implements the json.Marshaler interface for EBBEvent. // It customizes the JSON marshaling process for EBBEvent objects. func (e *EBBEvent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(e.toMap()) + []byte, + error) { + return json.Marshal(e.toMap()) } // toMap converts the EBBEvent object to a map representation for JSON marshaling. func (e *EBBEvent) toMap() map[string]any { - structMap := make(map[string]any) - if e.Chargify != nil { - structMap["chargify"] = e.Chargify.toMap() - } - return structMap + structMap := make(map[string]any) + if e.Chargify != nil { + structMap["chargify"] = e.Chargify.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for EBBEvent. +// UnmarshalJSON implements the json.Unmarshaler interface for EBBEvent. // It customizes the JSON unmarshaling process for EBBEvent objects. func (e *EBBEvent) UnmarshalJSON(input []byte) error { - temp := &struct { - Chargify *ChargifyEBB `json:"chargify,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - e.Chargify = temp.Chargify - return nil + var temp ebbEvent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + e.Chargify = temp.Chargify + return nil +} + +// TODO +type ebbEvent struct { + Chargify *ChargifyEBB `json:"chargify,omitempty"` } diff --git a/models/enable_webhooks_request.go b/models/enable_webhooks_request.go index a38e98b4..2727adbf 100644 --- a/models/enable_webhooks_request.go +++ b/models/enable_webhooks_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // EnableWebhooksRequest represents a EnableWebhooksRequest struct. type EnableWebhooksRequest struct { - WebhooksEnabled bool `json:"webhooks_enabled"` + WebhooksEnabled bool `json:"webhooks_enabled"` } -// MarshalJSON implements the json.Marshaler interface for EnableWebhooksRequest. +// MarshalJSON implements the json.Marshaler interface for EnableWebhooksRequest. // It customizes the JSON marshaling process for EnableWebhooksRequest objects. func (e *EnableWebhooksRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(e.toMap()) + []byte, + error) { + return json.Marshal(e.toMap()) } // toMap converts the EnableWebhooksRequest object to a map representation for JSON marshaling. func (e *EnableWebhooksRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["webhooks_enabled"] = e.WebhooksEnabled - return structMap + structMap := make(map[string]any) + structMap["webhooks_enabled"] = e.WebhooksEnabled + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for EnableWebhooksRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for EnableWebhooksRequest. // It customizes the JSON unmarshaling process for EnableWebhooksRequest objects. func (e *EnableWebhooksRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - WebhooksEnabled bool `json:"webhooks_enabled"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - e.WebhooksEnabled = temp.WebhooksEnabled - return nil + var temp enableWebhooksRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + e.WebhooksEnabled = *temp.WebhooksEnabled + return nil +} + +// TODO +type enableWebhooksRequest struct { + WebhooksEnabled *bool `json:"webhooks_enabled"` +} + +func (e *enableWebhooksRequest) validate() error { + var errs []string + if e.WebhooksEnabled == nil { + errs = append(errs, "required field `webhooks_enabled` is missing for type `Enable Webhooks Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/enable_webhooks_response.go b/models/enable_webhooks_response.go index bb0cc9ee..d2c94f69 100644 --- a/models/enable_webhooks_response.go +++ b/models/enable_webhooks_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // EnableWebhooksResponse represents a EnableWebhooksResponse struct. type EnableWebhooksResponse struct { - WebhooksEnabled *bool `json:"webhooks_enabled,omitempty"` + WebhooksEnabled *bool `json:"webhooks_enabled,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for EnableWebhooksResponse. +// MarshalJSON implements the json.Marshaler interface for EnableWebhooksResponse. // It customizes the JSON marshaling process for EnableWebhooksResponse objects. func (e *EnableWebhooksResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(e.toMap()) + []byte, + error) { + return json.Marshal(e.toMap()) } // toMap converts the EnableWebhooksResponse object to a map representation for JSON marshaling. func (e *EnableWebhooksResponse) toMap() map[string]any { - structMap := make(map[string]any) - if e.WebhooksEnabled != nil { - structMap["webhooks_enabled"] = e.WebhooksEnabled - } - return structMap + structMap := make(map[string]any) + if e.WebhooksEnabled != nil { + structMap["webhooks_enabled"] = e.WebhooksEnabled + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for EnableWebhooksResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for EnableWebhooksResponse. // It customizes the JSON unmarshaling process for EnableWebhooksResponse objects. func (e *EnableWebhooksResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - WebhooksEnabled *bool `json:"webhooks_enabled,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - e.WebhooksEnabled = temp.WebhooksEnabled - return nil + var temp enableWebhooksResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + e.WebhooksEnabled = temp.WebhooksEnabled + return nil +} + +// TODO +type enableWebhooksResponse struct { + WebhooksEnabled *bool `json:"webhooks_enabled,omitempty"` } diff --git a/models/endpoint.go b/models/endpoint.go index 41cbd59a..11c602f0 100644 --- a/models/endpoint.go +++ b/models/endpoint.go @@ -1,66 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" ) // Endpoint represents a Endpoint struct. type Endpoint struct { - Id *int `json:"id,omitempty"` - Url *string `json:"url,omitempty"` - SiteId *int `json:"site_id,omitempty"` - Status *string `json:"status,omitempty"` - WebhookSubscriptions []string `json:"webhook_subscriptions,omitempty"` + Id *int `json:"id,omitempty"` + Url *string `json:"url,omitempty"` + SiteId *int `json:"site_id,omitempty"` + Status *string `json:"status,omitempty"` + WebhookSubscriptions []string `json:"webhook_subscriptions,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Endpoint. +// MarshalJSON implements the json.Marshaler interface for Endpoint. // It customizes the JSON marshaling process for Endpoint objects. func (e *Endpoint) MarshalJSON() ( - []byte, - error) { - return json.Marshal(e.toMap()) + []byte, + error) { + return json.Marshal(e.toMap()) } // toMap converts the Endpoint object to a map representation for JSON marshaling. func (e *Endpoint) toMap() map[string]any { - structMap := make(map[string]any) - if e.Id != nil { - structMap["id"] = e.Id - } - if e.Url != nil { - structMap["url"] = e.Url - } - if e.SiteId != nil { - structMap["site_id"] = e.SiteId - } - if e.Status != nil { - structMap["status"] = e.Status - } - if e.WebhookSubscriptions != nil { - structMap["webhook_subscriptions"] = e.WebhookSubscriptions - } - return structMap + structMap := make(map[string]any) + if e.Id != nil { + structMap["id"] = e.Id + } + if e.Url != nil { + structMap["url"] = e.Url + } + if e.SiteId != nil { + structMap["site_id"] = e.SiteId + } + if e.Status != nil { + structMap["status"] = e.Status + } + if e.WebhookSubscriptions != nil { + structMap["webhook_subscriptions"] = e.WebhookSubscriptions + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Endpoint. +// UnmarshalJSON implements the json.Unmarshaler interface for Endpoint. // It customizes the JSON unmarshaling process for Endpoint objects. func (e *Endpoint) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Url *string `json:"url,omitempty"` - SiteId *int `json:"site_id,omitempty"` - Status *string `json:"status,omitempty"` - WebhookSubscriptions []string `json:"webhook_subscriptions,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - e.Id = temp.Id - e.Url = temp.Url - e.SiteId = temp.SiteId - e.Status = temp.Status - e.WebhookSubscriptions = temp.WebhookSubscriptions - return nil + var temp endpoint + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + e.Id = temp.Id + e.Url = temp.Url + e.SiteId = temp.SiteId + e.Status = temp.Status + e.WebhookSubscriptions = temp.WebhookSubscriptions + return nil +} + +// TODO +type endpoint struct { + Id *int `json:"id,omitempty"` + Url *string `json:"url,omitempty"` + SiteId *int `json:"site_id,omitempty"` + Status *string `json:"status,omitempty"` + WebhookSubscriptions []string `json:"webhook_subscriptions,omitempty"` } diff --git a/models/endpoint_response.go b/models/endpoint_response.go index 42052157..5a25ac13 100644 --- a/models/endpoint_response.go +++ b/models/endpoint_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // EndpointResponse represents a EndpointResponse struct. type EndpointResponse struct { - Endpoint *Endpoint `json:"endpoint,omitempty"` + Endpoint *Endpoint `json:"endpoint,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for EndpointResponse. +// MarshalJSON implements the json.Marshaler interface for EndpointResponse. // It customizes the JSON marshaling process for EndpointResponse objects. func (e *EndpointResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(e.toMap()) + []byte, + error) { + return json.Marshal(e.toMap()) } // toMap converts the EndpointResponse object to a map representation for JSON marshaling. func (e *EndpointResponse) toMap() map[string]any { - structMap := make(map[string]any) - if e.Endpoint != nil { - structMap["endpoint"] = e.Endpoint.toMap() - } - return structMap + structMap := make(map[string]any) + if e.Endpoint != nil { + structMap["endpoint"] = e.Endpoint.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for EndpointResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for EndpointResponse. // It customizes the JSON unmarshaling process for EndpointResponse objects. func (e *EndpointResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Endpoint *Endpoint `json:"endpoint,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - e.Endpoint = temp.Endpoint - return nil + var temp endpointResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + e.Endpoint = temp.Endpoint + return nil +} + +// TODO +type endpointResponse struct { + Endpoint *Endpoint `json:"endpoint,omitempty"` } diff --git a/models/enums.go b/models/enums.go index 705044f8..2e17335f 100644 --- a/models/enums.go +++ b/models/enums.go @@ -1,7 +1,7 @@ -/* -Package advancedbilling - -This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). */ package models @@ -9,353 +9,353 @@ package models type AllocationPreviewDirection string const ( - AllocationPreviewDirection_UPGRADE AllocationPreviewDirection = "upgrade" - AllocationPreviewDirection_DOWNGRADE AllocationPreviewDirection = "downgrade" + AllocationPreviewDirection_UPGRADE AllocationPreviewDirection = "upgrade" + AllocationPreviewDirection_DOWNGRADE AllocationPreviewDirection = "downgrade" ) -// AllocationPreviewLineItemKind is a string enum. +// AllocationPreviewLineItemKind is a string enum. // A handle for the line item kind for allocation preview type AllocationPreviewLineItemKind string const ( - AllocationPreviewLineItemKind_QUANTITYBASEDCOMPONENT AllocationPreviewLineItemKind = "quantity_based_component" - AllocationPreviewLineItemKind_ONOFFCOMPONENT AllocationPreviewLineItemKind = "on_off_component" - AllocationPreviewLineItemKind_COUPON AllocationPreviewLineItemKind = "coupon" - AllocationPreviewLineItemKind_TAX AllocationPreviewLineItemKind = "tax" + AllocationPreviewLineItemKind_QUANTITYBASEDCOMPONENT AllocationPreviewLineItemKind = "quantity_based_component" + AllocationPreviewLineItemKind_ONOFFCOMPONENT AllocationPreviewLineItemKind = "on_off_component" + AllocationPreviewLineItemKind_COUPON AllocationPreviewLineItemKind = "coupon" + AllocationPreviewLineItemKind_TAX AllocationPreviewLineItemKind = "tax" ) // AutoInvite is a int enum. type AutoInvite int const ( - AutoInvite_NO AutoInvite = 0 - AutoInvite_YES AutoInvite = 1 + AutoInvite_NO AutoInvite = 0 + AutoInvite_YES AutoInvite = 1 ) -// BankAccountHolderType is a string enum. +// BankAccountHolderType is a string enum. // Defaults to personal type BankAccountHolderType string const ( - BankAccountHolderType_PERSONAL BankAccountHolderType = "personal" - BankAccountHolderType_BUSINESS BankAccountHolderType = "business" + BankAccountHolderType_PERSONAL BankAccountHolderType = "personal" + BankAccountHolderType_BUSINESS BankAccountHolderType = "business" ) -// BankAccountType is a string enum. +// BankAccountType is a string enum. // Defaults to checking type BankAccountType string const ( - BankAccountType_CHECKING BankAccountType = "checking" - BankAccountType_SAVINGS BankAccountType = "savings" + BankAccountType_CHECKING BankAccountType = "checking" + BankAccountType_SAVINGS BankAccountType = "savings" ) -// BankAccountVault is a string enum. +// BankAccountVault is a string enum. // The vault that stores the payment profile with the provided vault_token. type BankAccountVault string const ( - BankAccountVault_BOGUS BankAccountVault = "bogus" - BankAccountVault_AUTHORIZENET BankAccountVault = "authorizenet" - BankAccountVault_STRIPECONNECT BankAccountVault = "stripe_connect" - BankAccountVault_BRAINTREEBLUE BankAccountVault = "braintree_blue" - BankAccountVault_GOCARDLESS BankAccountVault = "gocardless" + BankAccountVault_BOGUS BankAccountVault = "bogus" + BankAccountVault_AUTHORIZENET BankAccountVault = "authorizenet" + BankAccountVault_STRIPECONNECT BankAccountVault = "stripe_connect" + BankAccountVault_BRAINTREEBLUE BankAccountVault = "braintree_blue" + BankAccountVault_GOCARDLESS BankAccountVault = "gocardless" ) -// BasicDateField is a string enum. +// BasicDateField is a string enum. // Allows to filter by `created_at` or `updated_at`. type BasicDateField string const ( - BasicDateField_UPDATEDAT BasicDateField = "updated_at" - BasicDateField_CREATEDAT BasicDateField = "created_at" + BasicDateField_UPDATEDAT BasicDateField = "updated_at" + BasicDateField_CREATEDAT BasicDateField = "created_at" ) -// BillingManifestLineItemKind is a string enum. +// BillingManifestLineItemKind is a string enum. // A handle for the billing manifest line item kind type BillingManifestLineItemKind string const ( - BillingManifestLineItemKind_BASELINE BillingManifestLineItemKind = "baseline" - BillingManifestLineItemKind_INITIAL BillingManifestLineItemKind = "initial" - BillingManifestLineItemKind_TRIAL BillingManifestLineItemKind = "trial" - BillingManifestLineItemKind_COUPON BillingManifestLineItemKind = "coupon" - BillingManifestLineItemKind_COMPONENT BillingManifestLineItemKind = "component" - BillingManifestLineItemKind_TAX BillingManifestLineItemKind = "tax" + BillingManifestLineItemKind_BASELINE BillingManifestLineItemKind = "baseline" + BillingManifestLineItemKind_INITIAL BillingManifestLineItemKind = "initial" + BillingManifestLineItemKind_TRIAL BillingManifestLineItemKind = "trial" + BillingManifestLineItemKind_COUPON BillingManifestLineItemKind = "coupon" + BillingManifestLineItemKind_COMPONENT BillingManifestLineItemKind = "component" + BillingManifestLineItemKind_TAX BillingManifestLineItemKind = "tax" ) -// CancellationMethod is a string enum. +// CancellationMethod is a string enum. // The process used to cancel the subscription, if the subscription has been canceled. It is nil if the subscription's state is not canceled. type CancellationMethod string const ( - CancellationMethod_MERCHANTUI CancellationMethod = "merchant_ui" - CancellationMethod_MERCHANTAPI CancellationMethod = "merchant_api" - CancellationMethod_DUNNING CancellationMethod = "dunning" - CancellationMethod_BILLINGPORTAL CancellationMethod = "billing_portal" - CancellationMethod_UNKNOWN CancellationMethod = "unknown" + CancellationMethod_MERCHANTUI CancellationMethod = "merchant_ui" + CancellationMethod_MERCHANTAPI CancellationMethod = "merchant_api" + CancellationMethod_DUNNING CancellationMethod = "dunning" + CancellationMethod_BILLINGPORTAL CancellationMethod = "billing_portal" + CancellationMethod_UNKNOWN CancellationMethod = "unknown" ) -// CardType is a string enum. +// CardType is a string enum. // The type of card used. type CardType string const ( - CardType_VISA CardType = "visa" - CardType_MASTER CardType = "master" - CardType_ELO CardType = "elo" - CardType_CABAL CardType = "cabal" - CardType_ALELO CardType = "alelo" - CardType_DISCOVER CardType = "discover" - CardType_AMERICANEXPRESS CardType = "american_express" - CardType_NARANJA CardType = "naranja" - CardType_DINERSCLUB CardType = "diners_club" - CardType_JCB CardType = "jcb" - CardType_DANKORT CardType = "dankort" - CardType_MAESTRO CardType = "maestro" - CardType_MAESTRONOLUHN CardType = "maestro_no_luhn" - CardType_FORBRUGSFORENINGEN CardType = "forbrugsforeningen" - CardType_SODEXO CardType = "sodexo" - CardType_ALIA CardType = "alia" - CardType_VR CardType = "vr" - CardType_UNIONPAY CardType = "unionpay" - CardType_CARNET CardType = "carnet" - CardType_CARTESBANCAIRES CardType = "cartes_bancaires" - CardType_OLIMPICA CardType = "olimpica" - CardType_CREDITEL CardType = "creditel" - CardType_CONFIABLE CardType = "confiable" - CardType_SYNCHRONY CardType = "synchrony" - CardType_ROUTEX CardType = "routex" - CardType_MADA CardType = "mada" - CardType_BPPLUS CardType = "bp_plus" - CardType_PASSCARD CardType = "passcard" - CardType_EDENRED CardType = "edenred" - CardType_ANDA CardType = "anda" - CardType_TARJETAD CardType = "tarjeta-d" - CardType_HIPERCARD CardType = "hipercard" - CardType_BOGUS CardType = "bogus" - CardType_ENUMSWITCH CardType = "switch" - CardType_SOLO CardType = "solo" - CardType_LASER CardType = "laser" -) - -// CleanupScope is a string enum. + CardType_VISA CardType = "visa" + CardType_MASTER CardType = "master" + CardType_ELO CardType = "elo" + CardType_CABAL CardType = "cabal" + CardType_ALELO CardType = "alelo" + CardType_DISCOVER CardType = "discover" + CardType_AMERICANEXPRESS CardType = "american_express" + CardType_NARANJA CardType = "naranja" + CardType_DINERSCLUB CardType = "diners_club" + CardType_JCB CardType = "jcb" + CardType_DANKORT CardType = "dankort" + CardType_MAESTRO CardType = "maestro" + CardType_MAESTRONOLUHN CardType = "maestro_no_luhn" + CardType_FORBRUGSFORENINGEN CardType = "forbrugsforeningen" + CardType_SODEXO CardType = "sodexo" + CardType_ALIA CardType = "alia" + CardType_VR CardType = "vr" + CardType_UNIONPAY CardType = "unionpay" + CardType_CARNET CardType = "carnet" + CardType_CARTESBANCAIRES CardType = "cartes_bancaires" + CardType_OLIMPICA CardType = "olimpica" + CardType_CREDITEL CardType = "creditel" + CardType_CONFIABLE CardType = "confiable" + CardType_SYNCHRONY CardType = "synchrony" + CardType_ROUTEX CardType = "routex" + CardType_MADA CardType = "mada" + CardType_BPPLUS CardType = "bp_plus" + CardType_PASSCARD CardType = "passcard" + CardType_EDENRED CardType = "edenred" + CardType_ANDA CardType = "anda" + CardType_TARJETAD CardType = "tarjeta-d" + CardType_HIPERCARD CardType = "hipercard" + CardType_BOGUS CardType = "bogus" + CardType_ENUMSWITCH CardType = "switch" + CardType_SOLO CardType = "solo" + CardType_LASER CardType = "laser" +) + +// CleanupScope is a string enum. // all: Will clear all products, customers, and related subscriptions from the site. customers: Will clear only customers and related subscriptions (leaving the products untouched) for the site. Revenue will also be reset to 0. type CleanupScope string const ( - CleanupScope_ALL CleanupScope = "all" - CleanupScope_CUSTOMERS CleanupScope = "customers" + CleanupScope_ALL CleanupScope = "all" + CleanupScope_CUSTOMERS CleanupScope = "customers" ) -// CollectionMethod is a string enum. +// CollectionMethod is a string enum. // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. type CollectionMethod string const ( - CollectionMethod_AUTOMATIC CollectionMethod = "automatic" - CollectionMethod_REMITTANCE CollectionMethod = "remittance" - CollectionMethod_PREPAID CollectionMethod = "prepaid" - CollectionMethod_INVOICE CollectionMethod = "invoice" + CollectionMethod_AUTOMATIC CollectionMethod = "automatic" + CollectionMethod_REMITTANCE CollectionMethod = "remittance" + CollectionMethod_PREPAID CollectionMethod = "prepaid" + CollectionMethod_INVOICE CollectionMethod = "invoice" ) -// ComponentKind is a string enum. +// ComponentKind is a string enum. // A handle for the component type type ComponentKind string const ( - ComponentKind_METEREDCOMPONENT ComponentKind = "metered_component" - ComponentKind_QUANTITYBASEDCOMPONENT ComponentKind = "quantity_based_component" - ComponentKind_ONOFFCOMPONENT ComponentKind = "on_off_component" - ComponentKind_PREPAIDUSAGECOMPONENT ComponentKind = "prepaid_usage_component" - ComponentKind_EVENTBASEDCOMPONENT ComponentKind = "event_based_component" + ComponentKind_METEREDCOMPONENT ComponentKind = "metered_component" + ComponentKind_QUANTITYBASEDCOMPONENT ComponentKind = "quantity_based_component" + ComponentKind_ONOFFCOMPONENT ComponentKind = "on_off_component" + ComponentKind_PREPAIDUSAGECOMPONENT ComponentKind = "prepaid_usage_component" + ComponentKind_EVENTBASEDCOMPONENT ComponentKind = "event_based_component" ) // CompoundingStrategy is a string enum. type CompoundingStrategy string const ( - CompoundingStrategy_COMPOUND CompoundingStrategy = "compound" - CompoundingStrategy_FULLPRICE CompoundingStrategy = "full-price" + CompoundingStrategy_COMPOUND CompoundingStrategy = "compound" + CompoundingStrategy_FULLPRICE CompoundingStrategy = "full-price" ) // CreateInvoiceStatus is a string enum. type CreateInvoiceStatus string const ( - CreateInvoiceStatus_DRAFT CreateInvoiceStatus = "draft" - CreateInvoiceStatus_OPEN CreateInvoiceStatus = "open" + CreateInvoiceStatus_DRAFT CreateInvoiceStatus = "draft" + CreateInvoiceStatus_OPEN CreateInvoiceStatus = "open" ) -// CreatePrepaymentMethod is a string enum. +// CreatePrepaymentMethod is a string enum. // :- When the `method` specified is `"credit_card_on_file"`, the prepayment amount will be collected using the default credit card payment profile and applied to the prepayment account balance. This is especially useful for manual replenishment of prepaid subscriptions. type CreatePrepaymentMethod string const ( - CreatePrepaymentMethod_CHECK CreatePrepaymentMethod = "check" - CreatePrepaymentMethod_CASH CreatePrepaymentMethod = "cash" - CreatePrepaymentMethod_MONEYORDER CreatePrepaymentMethod = "money_order" - CreatePrepaymentMethod_ACH CreatePrepaymentMethod = "ach" - CreatePrepaymentMethod_PAYPALACCOUNT CreatePrepaymentMethod = "paypal_account" - CreatePrepaymentMethod_CREDITCARD CreatePrepaymentMethod = "credit_card" - CreatePrepaymentMethod_CREDITCARDONFILE CreatePrepaymentMethod = "credit_card_on_file" - CreatePrepaymentMethod_OTHER CreatePrepaymentMethod = "other" + CreatePrepaymentMethod_CHECK CreatePrepaymentMethod = "check" + CreatePrepaymentMethod_CASH CreatePrepaymentMethod = "cash" + CreatePrepaymentMethod_MONEYORDER CreatePrepaymentMethod = "money_order" + CreatePrepaymentMethod_ACH CreatePrepaymentMethod = "ach" + CreatePrepaymentMethod_PAYPALACCOUNT CreatePrepaymentMethod = "paypal_account" + CreatePrepaymentMethod_CREDITCARD CreatePrepaymentMethod = "credit_card" + CreatePrepaymentMethod_CREDITCARDONFILE CreatePrepaymentMethod = "credit_card_on_file" + CreatePrepaymentMethod_OTHER CreatePrepaymentMethod = "other" ) // CreateSignupProformaPreviewInclude is a string enum. type CreateSignupProformaPreviewInclude string const ( - CreateSignupProformaPreviewInclude_NEXTPROFORMAINVOICE CreateSignupProformaPreviewInclude = "next_proforma_invoice" + CreateSignupProformaPreviewInclude_NEXTPROFORMAINVOICE CreateSignupProformaPreviewInclude = "next_proforma_invoice" ) -// CreditNoteStatus is a string enum. +// CreditNoteStatus is a string enum. // Current status of the credit note. type CreditNoteStatus string const ( - CreditNoteStatus_OPEN CreditNoteStatus = "open" - CreditNoteStatus_APPLIED CreditNoteStatus = "applied" + CreditNoteStatus_OPEN CreditNoteStatus = "open" + CreditNoteStatus_APPLIED CreditNoteStatus = "applied" ) // CreditScheme is a string enum. type CreditScheme string const ( - CreditScheme_NONE CreditScheme = "none" - CreditScheme_CREDIT CreditScheme = "credit" - CreditScheme_REFUND CreditScheme = "refund" + CreditScheme_NONE CreditScheme = "none" + CreditScheme_CREDIT CreditScheme = "credit" + CreditScheme_REFUND CreditScheme = "refund" ) -// CreditType is a string enum. +// CreditType is a string enum. // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. // Available values: `full`, `prorated`, `none`. type CreditType string const ( - CreditType_FULL CreditType = "full" - CreditType_PRORATED CreditType = "prorated" - CreditType_NONE CreditType = "none" + CreditType_FULL CreditType = "full" + CreditType_PRORATED CreditType = "prorated" + CreditType_NONE CreditType = "none" ) -// CurrencyPriceRole is a string enum. +// CurrencyPriceRole is a string enum. // Role for the price. type CurrencyPriceRole string const ( - CurrencyPriceRole_BASELINE CurrencyPriceRole = "baseline" - CurrencyPriceRole_TRIAL CurrencyPriceRole = "trial" - CurrencyPriceRole_INITIAL CurrencyPriceRole = "initial" + CurrencyPriceRole_BASELINE CurrencyPriceRole = "baseline" + CurrencyPriceRole_TRIAL CurrencyPriceRole = "trial" + CurrencyPriceRole_INITIAL CurrencyPriceRole = "initial" ) -// CurrentVault is a string enum. +// CurrentVault is a string enum. // The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. type CurrentVault string const ( - CurrentVault_ADYEN CurrentVault = "adyen" - CurrentVault_AUTHORIZENET CurrentVault = "authorizenet" - CurrentVault_AVALARA CurrentVault = "avalara" - CurrentVault_BEANSTREAM CurrentVault = "beanstream" - CurrentVault_BLUESNAP CurrentVault = "blue_snap" - CurrentVault_BOGUS CurrentVault = "bogus" - CurrentVault_BRAINTREEBLUE CurrentVault = "braintree_blue" - CurrentVault_CHECKOUT CurrentVault = "checkout" - CurrentVault_CYBERSOURCE CurrentVault = "cybersource" - CurrentVault_ELAVON CurrentVault = "elavon" - CurrentVault_EWAY CurrentVault = "eway" - CurrentVault_EWAYRAPIDSTD CurrentVault = "eway_rapid_std" - CurrentVault_FIRSTDATA CurrentVault = "firstdata" - CurrentVault_FORTE CurrentVault = "forte" - CurrentVault_GOCARDLESS CurrentVault = "gocardless" - CurrentVault_LITLE CurrentVault = "litle" - CurrentVault_MAXIOPAYMENTS CurrentVault = "maxio_payments" - CurrentVault_MODUSLINK CurrentVault = "moduslink" - CurrentVault_MONERIS CurrentVault = "moneris" - CurrentVault_NMI CurrentVault = "nmi" - CurrentVault_ORBITAL CurrentVault = "orbital" - CurrentVault_PAYMENTEXPRESS CurrentVault = "payment_express" - CurrentVault_PIN CurrentVault = "pin" - CurrentVault_SQUARE CurrentVault = "square" - CurrentVault_STRIPECONNECT CurrentVault = "stripe_connect" - CurrentVault_TRUSTCOMMERCE CurrentVault = "trust_commerce" - CurrentVault_UNIPAAS CurrentVault = "unipaas" + CurrentVault_ADYEN CurrentVault = "adyen" + CurrentVault_AUTHORIZENET CurrentVault = "authorizenet" + CurrentVault_AVALARA CurrentVault = "avalara" + CurrentVault_BEANSTREAM CurrentVault = "beanstream" + CurrentVault_BLUESNAP CurrentVault = "blue_snap" + CurrentVault_BOGUS CurrentVault = "bogus" + CurrentVault_BRAINTREEBLUE CurrentVault = "braintree_blue" + CurrentVault_CHECKOUT CurrentVault = "checkout" + CurrentVault_CYBERSOURCE CurrentVault = "cybersource" + CurrentVault_ELAVON CurrentVault = "elavon" + CurrentVault_EWAY CurrentVault = "eway" + CurrentVault_EWAYRAPIDSTD CurrentVault = "eway_rapid_std" + CurrentVault_FIRSTDATA CurrentVault = "firstdata" + CurrentVault_FORTE CurrentVault = "forte" + CurrentVault_GOCARDLESS CurrentVault = "gocardless" + CurrentVault_LITLE CurrentVault = "litle" + CurrentVault_MAXIOPAYMENTS CurrentVault = "maxio_payments" + CurrentVault_MODUSLINK CurrentVault = "moduslink" + CurrentVault_MONERIS CurrentVault = "moneris" + CurrentVault_NMI CurrentVault = "nmi" + CurrentVault_ORBITAL CurrentVault = "orbital" + CurrentVault_PAYMENTEXPRESS CurrentVault = "payment_express" + CurrentVault_PIN CurrentVault = "pin" + CurrentVault_SQUARE CurrentVault = "square" + CurrentVault_STRIPECONNECT CurrentVault = "stripe_connect" + CurrentVault_TRUSTCOMMERCE CurrentVault = "trust_commerce" + CurrentVault_UNIPAAS CurrentVault = "unipaas" ) // CustomFieldOwner is a string enum. type CustomFieldOwner string const ( - CustomFieldOwner_CUSTOMER CustomFieldOwner = "Customer" - CustomFieldOwner_SUBSCRIPTION CustomFieldOwner = "Subscription" + CustomFieldOwner_CUSTOMER CustomFieldOwner = "Customer" + CustomFieldOwner_SUBSCRIPTION CustomFieldOwner = "Subscription" ) // Direction is a string enum. type Direction string const ( - Direction_ASC Direction = "asc" - Direction_DESC Direction = "desc" + Direction_ASC Direction = "asc" + Direction_DESC Direction = "desc" ) // DiscountType is a string enum. type DiscountType string const ( - DiscountType_AMOUNT DiscountType = "amount" - DiscountType_PERCENT DiscountType = "percent" + DiscountType_AMOUNT DiscountType = "amount" + DiscountType_PERCENT DiscountType = "percent" ) // EventType is a string enum. type EventType string const ( - EventType_ACCOUNTTRANSACTIONCHANGED EventType = "account_transaction_changed" - EventType_BILLINGDATECHANGE EventType = "billing_date_change" - EventType_COMPONENTALLOCATIONCHANGE EventType = "component_allocation_change" - EventType_CUSTOMERUPDATE EventType = "customer_update" - EventType_CUSTOMERCREATE EventType = "customer_create" - EventType_DUNNINGSTEPREACHED EventType = "dunning_step_reached" - EventType_EXPIRATIONDATECHANGE EventType = "expiration_date_change" - EventType_EXPIRINGCARD EventType = "expiring_card" - EventType_METEREDUSAGE EventType = "metered_usage" - EventType_PAYMENTSUCCESS EventType = "payment_success" - EventType_PAYMENTSUCCESSRECREATED EventType = "payment_success_recreated" - EventType_PAYMENTFAILURE EventType = "payment_failure" - EventType_PAYMENTFAILURERECREATED EventType = "payment_failure_recreated" - EventType_REFUNDFAILURE EventType = "refund_failure" - EventType_REFUNDSUCCESS EventType = "refund_success" - EventType_RENEWALSUCCESS EventType = "renewal_success" - EventType_RENEWALSUCCESSRECREATED EventType = "renewal_success_recreated" - EventType_RENEWALFAILURE EventType = "renewal_failure" - EventType_SIGNUPSUCCESS EventType = "signup_success" - EventType_SIGNUPFAILURE EventType = "signup_failure" - EventType_STATEMENTCLOSED EventType = "statement_closed" - EventType_STATEMENTSETTLED EventType = "statement_settled" - EventType_SUBSCRIPTIONBANKACCOUNTUPDATE EventType = "subscription_bank_account_update" - EventType_SUBSCRIPTIONDELETION EventType = "subscription_deletion" - EventType_SUBSCRIPTIONPAYPALACCOUNTUPDATE EventType = "subscription_paypal_account_update" - EventType_SUBSCRIPTIONPRODUCTCHANGE EventType = "subscription_product_change" - EventType_SUBSCRIPTIONSTATECHANGE EventType = "subscription_state_change" - EventType_TRIALENDNOTICE EventType = "trial_end_notice" - EventType_UPGRADEDOWNGRADESUCCESS EventType = "upgrade_downgrade_success" - EventType_UPGRADEDOWNGRADEFAILURE EventType = "upgrade_downgrade_failure" - EventType_UPCOMINGRENEWALNOTICE EventType = "upcoming_renewal_notice" - EventType_CUSTOMFIELDVALUECHANGE EventType = "custom_field_value_change" - EventType_SUBSCRIPTIONPREPAYMENTACCOUNTBALANCECHANGED EventType = "subscription_prepayment_account_balance_changed" - EventType_SUBSCRIPTIONSERVICECREDITACCOUNTBALANCECHANGED EventType = "subscription_service_credit_account_balance_changed" + EventType_ACCOUNTTRANSACTIONCHANGED EventType = "account_transaction_changed" + EventType_BILLINGDATECHANGE EventType = "billing_date_change" + EventType_COMPONENTALLOCATIONCHANGE EventType = "component_allocation_change" + EventType_CUSTOMERUPDATE EventType = "customer_update" + EventType_CUSTOMERCREATE EventType = "customer_create" + EventType_DUNNINGSTEPREACHED EventType = "dunning_step_reached" + EventType_EXPIRATIONDATECHANGE EventType = "expiration_date_change" + EventType_EXPIRINGCARD EventType = "expiring_card" + EventType_METEREDUSAGE EventType = "metered_usage" + EventType_PAYMENTSUCCESS EventType = "payment_success" + EventType_PAYMENTSUCCESSRECREATED EventType = "payment_success_recreated" + EventType_PAYMENTFAILURE EventType = "payment_failure" + EventType_PAYMENTFAILURERECREATED EventType = "payment_failure_recreated" + EventType_REFUNDFAILURE EventType = "refund_failure" + EventType_REFUNDSUCCESS EventType = "refund_success" + EventType_RENEWALSUCCESS EventType = "renewal_success" + EventType_RENEWALSUCCESSRECREATED EventType = "renewal_success_recreated" + EventType_RENEWALFAILURE EventType = "renewal_failure" + EventType_SIGNUPSUCCESS EventType = "signup_success" + EventType_SIGNUPFAILURE EventType = "signup_failure" + EventType_STATEMENTCLOSED EventType = "statement_closed" + EventType_STATEMENTSETTLED EventType = "statement_settled" + EventType_SUBSCRIPTIONBANKACCOUNTUPDATE EventType = "subscription_bank_account_update" + EventType_SUBSCRIPTIONDELETION EventType = "subscription_deletion" + EventType_SUBSCRIPTIONPAYPALACCOUNTUPDATE EventType = "subscription_paypal_account_update" + EventType_SUBSCRIPTIONPRODUCTCHANGE EventType = "subscription_product_change" + EventType_SUBSCRIPTIONSTATECHANGE EventType = "subscription_state_change" + EventType_TRIALENDNOTICE EventType = "trial_end_notice" + EventType_UPGRADEDOWNGRADESUCCESS EventType = "upgrade_downgrade_success" + EventType_UPGRADEDOWNGRADEFAILURE EventType = "upgrade_downgrade_failure" + EventType_UPCOMINGRENEWALNOTICE EventType = "upcoming_renewal_notice" + EventType_CUSTOMFIELDVALUECHANGE EventType = "custom_field_value_change" + EventType_SUBSCRIPTIONPREPAYMENTACCOUNTBALANCECHANGED EventType = "subscription_prepayment_account_balance_changed" + EventType_SUBSCRIPTIONSERVICECREDITACCOUNTBALANCECHANGED EventType = "subscription_service_credit_account_balance_changed" ) // ExtendedIntervalUnit is a string enum. type ExtendedIntervalUnit string const ( - ExtendedIntervalUnit_DAY ExtendedIntervalUnit = "day" - ExtendedIntervalUnit_MONTH ExtendedIntervalUnit = "month" - ExtendedIntervalUnit_NEVER ExtendedIntervalUnit = "never" + ExtendedIntervalUnit_DAY ExtendedIntervalUnit = "day" + ExtendedIntervalUnit_MONTH ExtendedIntervalUnit = "month" + ExtendedIntervalUnit_NEVER ExtendedIntervalUnit = "never" ) -// FailedPaymentAction is a string enum. +// FailedPaymentAction is a string enum. // Action taken when payment for an invoice fails: // - `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. // - `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. @@ -363,57 +363,65 @@ const ( type FailedPaymentAction string const ( - FailedPaymentAction_LEAVEOPENINVOICE FailedPaymentAction = "leave_open_invoice" - FailedPaymentAction_ROLLBACKTOPENDING FailedPaymentAction = "rollback_to_pending" - FailedPaymentAction_INITIATEDUNNING FailedPaymentAction = "initiate_dunning" + FailedPaymentAction_LEAVEOPENINVOICE FailedPaymentAction = "leave_open_invoice" + FailedPaymentAction_ROLLBACKTOPENDING FailedPaymentAction = "rollback_to_pending" + FailedPaymentAction_INITIATEDUNNING FailedPaymentAction = "initiate_dunning" ) // FirstChargeType is a string enum. type FirstChargeType string const ( - FirstChargeType_PRORATED FirstChargeType = "prorated" - FirstChargeType_IMMEDIATE FirstChargeType = "immediate" - FirstChargeType_DELAYED FirstChargeType = "delayed" + FirstChargeType_PRORATED FirstChargeType = "prorated" + FirstChargeType_IMMEDIATE FirstChargeType = "immediate" + FirstChargeType_DELAYED FirstChargeType = "delayed" ) -// GroupTargetType is a string enum. +// GroupTargetType is a string enum. // The type of object indicated by the id attribute. type GroupTargetType string const ( - GroupTargetType_CUSTOMER GroupTargetType = "customer" - GroupTargetType_SUBSCRIPTION GroupTargetType = "subscription" - GroupTargetType_SELF GroupTargetType = "self" - GroupTargetType_PARENT GroupTargetType = "parent" - GroupTargetType_ELDEST GroupTargetType = "eldest" + GroupTargetType_CUSTOMER GroupTargetType = "customer" + GroupTargetType_SUBSCRIPTION GroupTargetType = "subscription" + GroupTargetType_SELF GroupTargetType = "self" + GroupTargetType_PARENT GroupTargetType = "parent" + GroupTargetType_ELDEST GroupTargetType = "eldest" +) + +// GroupType is a string enum. +type GroupType string + +const ( + GroupType_SINGLECUSTOMER GroupType = "single_customer" + GroupType_MULTIPLECUSTOMERS GroupType = "multiple_customers" ) -// IncludeNotNull is a string enum. +// IncludeNotNull is a string enum. // Passed as a parameter to list methods to return only non null values. type IncludeNotNull string const ( - IncludeNotNull_NOTNULL IncludeNotNull = "not_null" + IncludeNotNull_NOTNULL IncludeNotNull = "not_null" ) // IncludeOption is a string enum. type IncludeOption string const ( - IncludeOption_EXCLUDE IncludeOption = "0" - IncludeOption_INCLUDE IncludeOption = "1" + IncludeOption_EXCLUDE IncludeOption = "0" + IncludeOption_INCLUDE IncludeOption = "1" ) // IntervalUnit is a string enum. type IntervalUnit string const ( - IntervalUnit_DAY IntervalUnit = "day" - IntervalUnit_MONTH IntervalUnit = "month" + IntervalUnit_DAY IntervalUnit = "day" + IntervalUnit_MONTH IntervalUnit = "month" ) -// InvoiceConsolidationLevel is a string enum. +// InvoiceConsolidationLevel is a string enum. // Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values: // * "none": A normal invoice with no consolidation. // * "child": An invoice segment which has been combined into a consolidated invoice. @@ -423,267 +431,267 @@ const ( type InvoiceConsolidationLevel string const ( - InvoiceConsolidationLevel_NONE InvoiceConsolidationLevel = "none" - InvoiceConsolidationLevel_CHILD InvoiceConsolidationLevel = "child" - InvoiceConsolidationLevel_PARENT InvoiceConsolidationLevel = "parent" + InvoiceConsolidationLevel_NONE InvoiceConsolidationLevel = "none" + InvoiceConsolidationLevel_CHILD InvoiceConsolidationLevel = "child" + InvoiceConsolidationLevel_PARENT InvoiceConsolidationLevel = "parent" ) // InvoiceDateField is a string enum. type InvoiceDateField string const ( - InvoiceDateField_CREATEDAT InvoiceDateField = "created_at" - InvoiceDateField_DUEDATE InvoiceDateField = "due_date" - InvoiceDateField_ISSUEDATE InvoiceDateField = "issue_date" - InvoiceDateField_UPDATEDAT InvoiceDateField = "updated_at" - InvoiceDateField_PAIDDATE InvoiceDateField = "paid_date" + InvoiceDateField_CREATEDAT InvoiceDateField = "created_at" + InvoiceDateField_DUEDATE InvoiceDateField = "due_date" + InvoiceDateField_ISSUEDATE InvoiceDateField = "issue_date" + InvoiceDateField_UPDATEDAT InvoiceDateField = "updated_at" + InvoiceDateField_PAIDDATE InvoiceDateField = "paid_date" ) // InvoiceDiscountSourceType is a string enum. type InvoiceDiscountSourceType string const ( - InvoiceDiscountSourceType_COUPON InvoiceDiscountSourceType = "Coupon" - InvoiceDiscountSourceType_REFERRAL InvoiceDiscountSourceType = "Referral" - InvoiceDiscountSourceType_ENUMADHOCCOUPON InvoiceDiscountSourceType = "Ad Hoc Coupon" + InvoiceDiscountSourceType_COUPON InvoiceDiscountSourceType = "Coupon" + InvoiceDiscountSourceType_REFERRAL InvoiceDiscountSourceType = "Referral" + InvoiceDiscountSourceType_ENUMADHOCCOUPON InvoiceDiscountSourceType = "Ad Hoc Coupon" ) // InvoiceDiscountType is a string enum. type InvoiceDiscountType string const ( - InvoiceDiscountType_PERCENTAGE InvoiceDiscountType = "percentage" - InvoiceDiscountType_FLATAMOUNT InvoiceDiscountType = "flat_amount" - InvoiceDiscountType_ROLLOVER InvoiceDiscountType = "rollover" + InvoiceDiscountType_PERCENTAGE InvoiceDiscountType = "percentage" + InvoiceDiscountType_FLATAMOUNT InvoiceDiscountType = "flat_amount" + InvoiceDiscountType_ROLLOVER InvoiceDiscountType = "rollover" ) // InvoiceEventPaymentMethod is a string enum. type InvoiceEventPaymentMethod string const ( - InvoiceEventPaymentMethod_APPLEPAY InvoiceEventPaymentMethod = "apple_pay" - InvoiceEventPaymentMethod_BANKACCOUNT InvoiceEventPaymentMethod = "bank_account" - InvoiceEventPaymentMethod_CREDITCARD InvoiceEventPaymentMethod = "credit_card" - InvoiceEventPaymentMethod_EXTERNAL InvoiceEventPaymentMethod = "external" - InvoiceEventPaymentMethod_PAYPALACCOUNT InvoiceEventPaymentMethod = "paypal_account" + InvoiceEventPaymentMethod_APPLEPAY InvoiceEventPaymentMethod = "apple_pay" + InvoiceEventPaymentMethod_BANKACCOUNT InvoiceEventPaymentMethod = "bank_account" + InvoiceEventPaymentMethod_CREDITCARD InvoiceEventPaymentMethod = "credit_card" + InvoiceEventPaymentMethod_EXTERNAL InvoiceEventPaymentMethod = "external" + InvoiceEventPaymentMethod_PAYPALACCOUNT InvoiceEventPaymentMethod = "paypal_account" ) -// InvoiceEventType is a string enum. +// InvoiceEventType is a string enum. // Invoice Event Type type InvoiceEventType string const ( - InvoiceEventType_ISSUEINVOICE InvoiceEventType = "issue_invoice" - InvoiceEventType_APPLYCREDITNOTE InvoiceEventType = "apply_credit_note" - InvoiceEventType_CREATECREDITNOTE InvoiceEventType = "create_credit_note" - InvoiceEventType_APPLYPAYMENT InvoiceEventType = "apply_payment" - InvoiceEventType_APPLYDEBITNOTE InvoiceEventType = "apply_debit_note" - InvoiceEventType_REFUNDINVOICE InvoiceEventType = "refund_invoice" - InvoiceEventType_VOIDINVOICE InvoiceEventType = "void_invoice" - InvoiceEventType_VOIDREMAINDER InvoiceEventType = "void_remainder" - InvoiceEventType_BACKPORTINVOICE InvoiceEventType = "backport_invoice" - InvoiceEventType_CHANGEINVOICESTATUS InvoiceEventType = "change_invoice_status" - InvoiceEventType_CHANGEINVOICECOLLECTIONMETHOD InvoiceEventType = "change_invoice_collection_method" - InvoiceEventType_REMOVEPAYMENT InvoiceEventType = "remove_payment" - InvoiceEventType_FAILEDPAYMENT InvoiceEventType = "failed_payment" - InvoiceEventType_CHANGECHARGEBACKSTATUS InvoiceEventType = "change_chargeback_status" + InvoiceEventType_ISSUEINVOICE InvoiceEventType = "issue_invoice" + InvoiceEventType_APPLYCREDITNOTE InvoiceEventType = "apply_credit_note" + InvoiceEventType_CREATECREDITNOTE InvoiceEventType = "create_credit_note" + InvoiceEventType_APPLYPAYMENT InvoiceEventType = "apply_payment" + InvoiceEventType_APPLYDEBITNOTE InvoiceEventType = "apply_debit_note" + InvoiceEventType_REFUNDINVOICE InvoiceEventType = "refund_invoice" + InvoiceEventType_VOIDINVOICE InvoiceEventType = "void_invoice" + InvoiceEventType_VOIDREMAINDER InvoiceEventType = "void_remainder" + InvoiceEventType_BACKPORTINVOICE InvoiceEventType = "backport_invoice" + InvoiceEventType_CHANGEINVOICESTATUS InvoiceEventType = "change_invoice_status" + InvoiceEventType_CHANGEINVOICECOLLECTIONMETHOD InvoiceEventType = "change_invoice_collection_method" + InvoiceEventType_REMOVEPAYMENT InvoiceEventType = "remove_payment" + InvoiceEventType_FAILEDPAYMENT InvoiceEventType = "failed_payment" + InvoiceEventType_CHANGECHARGEBACKSTATUS InvoiceEventType = "change_chargeback_status" ) -// InvoicePaymentMethodType is a string enum. +// InvoicePaymentMethodType is a string enum. // The type of payment method used. Defaults to other. type InvoicePaymentMethodType string const ( - InvoicePaymentMethodType_CREDITCARD InvoicePaymentMethodType = "credit_card" - InvoicePaymentMethodType_CHECK InvoicePaymentMethodType = "check" - InvoicePaymentMethodType_CASH InvoicePaymentMethodType = "cash" - InvoicePaymentMethodType_MONEYORDER InvoicePaymentMethodType = "money_order" - InvoicePaymentMethodType_ACH InvoicePaymentMethodType = "ach" - InvoicePaymentMethodType_OTHER InvoicePaymentMethodType = "other" + InvoicePaymentMethodType_CREDITCARD InvoicePaymentMethodType = "credit_card" + InvoicePaymentMethodType_CHECK InvoicePaymentMethodType = "check" + InvoicePaymentMethodType_CASH InvoicePaymentMethodType = "cash" + InvoicePaymentMethodType_MONEYORDER InvoicePaymentMethodType = "money_order" + InvoicePaymentMethodType_ACH InvoicePaymentMethodType = "ach" + InvoicePaymentMethodType_OTHER InvoicePaymentMethodType = "other" ) -// InvoicePaymentType is a string enum. +// InvoicePaymentType is a string enum. // The type of payment to be applied to an Invoice. Defaults to external. type InvoicePaymentType string const ( - InvoicePaymentType_EXTERNAL InvoicePaymentType = "external" - InvoicePaymentType_PREPAYMENT InvoicePaymentType = "prepayment" - InvoicePaymentType_SERVICECREDIT InvoicePaymentType = "service_credit" - InvoicePaymentType_PAYMENT InvoicePaymentType = "payment" + InvoicePaymentType_EXTERNAL InvoicePaymentType = "external" + InvoicePaymentType_PREPAYMENT InvoicePaymentType = "prepayment" + InvoicePaymentType_SERVICECREDIT InvoicePaymentType = "service_credit" + InvoicePaymentType_PAYMENT InvoicePaymentType = "payment" ) // InvoiceRole is a string enum. type InvoiceRole string const ( - InvoiceRole_UNSET InvoiceRole = "unset" - InvoiceRole_SIGNUP InvoiceRole = "signup" - InvoiceRole_RENEWAL InvoiceRole = "renewal" - InvoiceRole_USAGE InvoiceRole = "usage" - InvoiceRole_REACTIVATION InvoiceRole = "reactivation" - InvoiceRole_PRORATION InvoiceRole = "proration" - InvoiceRole_MIGRATION InvoiceRole = "migration" - InvoiceRole_ADHOC InvoiceRole = "adhoc" - InvoiceRole_BACKPORT InvoiceRole = "backport" - InvoiceRole_BACKPORTBALANCERECONCILIATION InvoiceRole = "backport-balance-reconciliation" + InvoiceRole_UNSET InvoiceRole = "unset" + InvoiceRole_SIGNUP InvoiceRole = "signup" + InvoiceRole_RENEWAL InvoiceRole = "renewal" + InvoiceRole_USAGE InvoiceRole = "usage" + InvoiceRole_REACTIVATION InvoiceRole = "reactivation" + InvoiceRole_PRORATION InvoiceRole = "proration" + InvoiceRole_MIGRATION InvoiceRole = "migration" + InvoiceRole_ADHOC InvoiceRole = "adhoc" + InvoiceRole_BACKPORT InvoiceRole = "backport" + InvoiceRole_BACKPORTBALANCERECONCILIATION InvoiceRole = "backport-balance-reconciliation" ) // InvoiceSortField is a string enum. type InvoiceSortField string const ( - InvoiceSortField_STATUS InvoiceSortField = "status" - InvoiceSortField_TOTALAMOUNT InvoiceSortField = "total_amount" - InvoiceSortField_DUEAMOUNT InvoiceSortField = "due_amount" - InvoiceSortField_CREATEDAT InvoiceSortField = "created_at" - InvoiceSortField_UPDATEDAT InvoiceSortField = "updated_at" - InvoiceSortField_ISSUEDATE InvoiceSortField = "issue_date" - InvoiceSortField_DUEDATE InvoiceSortField = "due_date" - InvoiceSortField_NUMBER InvoiceSortField = "number" + InvoiceSortField_STATUS InvoiceSortField = "status" + InvoiceSortField_TOTALAMOUNT InvoiceSortField = "total_amount" + InvoiceSortField_DUEAMOUNT InvoiceSortField = "due_amount" + InvoiceSortField_CREATEDAT InvoiceSortField = "created_at" + InvoiceSortField_UPDATEDAT InvoiceSortField = "updated_at" + InvoiceSortField_ISSUEDATE InvoiceSortField = "issue_date" + InvoiceSortField_DUEDATE InvoiceSortField = "due_date" + InvoiceSortField_NUMBER InvoiceSortField = "number" ) -// InvoiceStatus is a string enum. +// InvoiceStatus is a string enum. // The current status of the invoice. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. type InvoiceStatus string const ( - InvoiceStatus_DRAFT InvoiceStatus = "draft" - InvoiceStatus_OPEN InvoiceStatus = "open" - InvoiceStatus_PAID InvoiceStatus = "paid" - InvoiceStatus_PENDING InvoiceStatus = "pending" - InvoiceStatus_VOIDED InvoiceStatus = "voided" - InvoiceStatus_CANCELED InvoiceStatus = "canceled" + InvoiceStatus_DRAFT InvoiceStatus = "draft" + InvoiceStatus_OPEN InvoiceStatus = "open" + InvoiceStatus_PAID InvoiceStatus = "paid" + InvoiceStatus_PENDING InvoiceStatus = "pending" + InvoiceStatus_VOIDED InvoiceStatus = "voided" + InvoiceStatus_CANCELED InvoiceStatus = "canceled" ) -// ItemCategory is a string enum. +// ItemCategory is a string enum. // One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other type ItemCategory string const ( - ItemCategory_ENUMBUSINESSSOFTWARE ItemCategory = "Business Software" - ItemCategory_ENUMCONSUMERSOFTWARE ItemCategory = "Consumer Software" - ItemCategory_ENUMDIGITALSERVICES ItemCategory = "Digital Services" - ItemCategory_ENUMPHYSICALGOODS ItemCategory = "Physical Goods" - ItemCategory_OTHER ItemCategory = "Other" + ItemCategory_ENUMBUSINESSSOFTWARE ItemCategory = "Business Software" + ItemCategory_ENUMCONSUMERSOFTWARE ItemCategory = "Consumer Software" + ItemCategory_ENUMDIGITALSERVICES ItemCategory = "Digital Services" + ItemCategory_ENUMPHYSICALGOODS ItemCategory = "Physical Goods" + ItemCategory_OTHER ItemCategory = "Other" ) -// LineItemKind is a string enum. +// LineItemKind is a string enum. // A handle for the line item kind type LineItemKind string const ( - LineItemKind_BASELINE LineItemKind = "baseline" - LineItemKind_INITIAL LineItemKind = "initial" - LineItemKind_TRIAL LineItemKind = "trial" - LineItemKind_QUANTITYBASEDCOMPONENT LineItemKind = "quantity_based_component" - LineItemKind_PREPAIDUSAGECOMPONENT LineItemKind = "prepaid_usage_component" - LineItemKind_ONOFFCOMPONENT LineItemKind = "on_off_component" - LineItemKind_METEREDCOMPONENT LineItemKind = "metered_component" - LineItemKind_EVENTBASEDCOMPONENT LineItemKind = "event_based_component" - LineItemKind_COUPON LineItemKind = "coupon" - LineItemKind_TAX LineItemKind = "tax" + LineItemKind_BASELINE LineItemKind = "baseline" + LineItemKind_INITIAL LineItemKind = "initial" + LineItemKind_TRIAL LineItemKind = "trial" + LineItemKind_QUANTITYBASEDCOMPONENT LineItemKind = "quantity_based_component" + LineItemKind_PREPAIDUSAGECOMPONENT LineItemKind = "prepaid_usage_component" + LineItemKind_ONOFFCOMPONENT LineItemKind = "on_off_component" + LineItemKind_METEREDCOMPONENT LineItemKind = "metered_component" + LineItemKind_EVENTBASEDCOMPONENT LineItemKind = "event_based_component" + LineItemKind_COUPON LineItemKind = "coupon" + LineItemKind_TAX LineItemKind = "tax" ) -// LineItemTransactionType is a string enum. +// LineItemTransactionType is a string enum. // A handle for the line item transaction type type LineItemTransactionType string const ( - LineItemTransactionType_CHARGE LineItemTransactionType = "charge" - LineItemTransactionType_CREDIT LineItemTransactionType = "credit" - LineItemTransactionType_ADJUSTMENT LineItemTransactionType = "adjustment" - LineItemTransactionType_PAYMENT LineItemTransactionType = "payment" - LineItemTransactionType_REFUND LineItemTransactionType = "refund" - LineItemTransactionType_INFOTRANSACTION LineItemTransactionType = "info_transaction" - LineItemTransactionType_PAYMENTAUTHORIZATION LineItemTransactionType = "payment_authorization" + LineItemTransactionType_CHARGE LineItemTransactionType = "charge" + LineItemTransactionType_CREDIT LineItemTransactionType = "credit" + LineItemTransactionType_ADJUSTMENT LineItemTransactionType = "adjustment" + LineItemTransactionType_PAYMENT LineItemTransactionType = "payment" + LineItemTransactionType_REFUND LineItemTransactionType = "refund" + LineItemTransactionType_INFOTRANSACTION LineItemTransactionType = "info_transaction" + LineItemTransactionType_PAYMENTAUTHORIZATION LineItemTransactionType = "payment_authorization" ) // ListComponentsPricePointsInclude is a string enum. type ListComponentsPricePointsInclude string const ( - ListComponentsPricePointsInclude_CURRENCYPRICES ListComponentsPricePointsInclude = "currency_prices" + ListComponentsPricePointsInclude_CURRENCYPRICES ListComponentsPricePointsInclude = "currency_prices" ) // ListEventsDateField is a string enum. type ListEventsDateField string const ( - ListEventsDateField_CREATEDAT ListEventsDateField = "created_at" + ListEventsDateField_CREATEDAT ListEventsDateField = "created_at" ) // ListProductsInclude is a string enum. type ListProductsInclude string const ( - ListProductsInclude_PREPAIDPRODUCTPRICEPOINT ListProductsInclude = "prepaid_product_price_point" + ListProductsInclude_PREPAIDPRODUCTPRICEPOINT ListProductsInclude = "prepaid_product_price_point" ) // ListProductsPricePointsInclude is a string enum. type ListProductsPricePointsInclude string const ( - ListProductsPricePointsInclude_CURRENCYPRICES ListProductsPricePointsInclude = "currency_prices" + ListProductsPricePointsInclude_CURRENCYPRICES ListProductsPricePointsInclude = "currency_prices" ) // ListSubscriptionComponentsInclude is a string enum. type ListSubscriptionComponentsInclude string const ( - ListSubscriptionComponentsInclude_SUBSCRIPTION ListSubscriptionComponentsInclude = "subscription" + ListSubscriptionComponentsInclude_SUBSCRIPTION ListSubscriptionComponentsInclude = "subscription" ) // ListSubscriptionComponentsSort is a string enum. type ListSubscriptionComponentsSort string const ( - ListSubscriptionComponentsSort_ID ListSubscriptionComponentsSort = "id" - ListSubscriptionComponentsSort_UPDATEDAT ListSubscriptionComponentsSort = "updated_at" + ListSubscriptionComponentsSort_ID ListSubscriptionComponentsSort = "id" + ListSubscriptionComponentsSort_UPDATEDAT ListSubscriptionComponentsSort = "updated_at" ) // ListSubscriptionGroupPrepaymentDateField is a string enum. type ListSubscriptionGroupPrepaymentDateField string const ( - ListSubscriptionGroupPrepaymentDateField_CREATEDAT ListSubscriptionGroupPrepaymentDateField = "created_at" - ListSubscriptionGroupPrepaymentDateField_APPLICATIONAT ListSubscriptionGroupPrepaymentDateField = "application_at" + ListSubscriptionGroupPrepaymentDateField_CREATEDAT ListSubscriptionGroupPrepaymentDateField = "created_at" + ListSubscriptionGroupPrepaymentDateField_APPLICATIONAT ListSubscriptionGroupPrepaymentDateField = "application_at" ) -// MetafieldInput is a string enum. +// MetafieldInput is a string enum. // Indicates how data should be added to the metafield. For example, a text type is just a string, so a given metafield of this type can have any value attached. On the other hand, dropdown and radio have a set of allowed values that can be input, and appear differently on a Public Signup Page. Defaults to 'text' type MetafieldInput string const ( - MetafieldInput_BALANCETRACKER MetafieldInput = "balance_tracker" - MetafieldInput_TEXT MetafieldInput = "text" - MetafieldInput_RADIO MetafieldInput = "radio" - MetafieldInput_DROPDOWN MetafieldInput = "dropdown" + MetafieldInput_BALANCETRACKER MetafieldInput = "balance_tracker" + MetafieldInput_TEXT MetafieldInput = "text" + MetafieldInput_RADIO MetafieldInput = "radio" + MetafieldInput_DROPDOWN MetafieldInput = "dropdown" ) // PaymentType is a string enum. type PaymentType string const ( - PaymentType_CREDITCARD PaymentType = "credit_card" - PaymentType_BANKACCOUNT PaymentType = "bank_account" - PaymentType_PAYPALACCOUNT PaymentType = "paypal_account" + PaymentType_CREDITCARD PaymentType = "credit_card" + PaymentType_BANKACCOUNT PaymentType = "bank_account" + PaymentType_PAYPALACCOUNT PaymentType = "paypal_account" ) // PrepaymentMethod is a string enum. type PrepaymentMethod string const ( - PrepaymentMethod_CHECK PrepaymentMethod = "check" - PrepaymentMethod_CASH PrepaymentMethod = "cash" - PrepaymentMethod_MONEYORDER PrepaymentMethod = "money_order" - PrepaymentMethod_ACH PrepaymentMethod = "ach" - PrepaymentMethod_PAYPALACCOUNT PrepaymentMethod = "paypal_account" - PrepaymentMethod_CREDITCARD PrepaymentMethod = "credit_card" - PrepaymentMethod_OTHER PrepaymentMethod = "other" + PrepaymentMethod_CHECK PrepaymentMethod = "check" + PrepaymentMethod_CASH PrepaymentMethod = "cash" + PrepaymentMethod_MONEYORDER PrepaymentMethod = "money_order" + PrepaymentMethod_ACH PrepaymentMethod = "ach" + PrepaymentMethod_PAYPALACCOUNT PrepaymentMethod = "paypal_account" + PrepaymentMethod_CREDITCARD PrepaymentMethod = "credit_card" + PrepaymentMethod_OTHER PrepaymentMethod = "other" ) -// PricePointType is a string enum. +// PricePointType is a string enum. // Price point type. We expose the following types: // 1. **default**: a price point that is marked as a default price for a certain product. // 2. **custom**: a custom price point. @@ -691,325 +699,350 @@ const ( type PricePointType string const ( - PricePointType_CATALOG PricePointType = "catalog" - PricePointType_ENUMDEFAULT PricePointType = "default" - PricePointType_CUSTOM PricePointType = "custom" + PricePointType_CATALOG PricePointType = "catalog" + PricePointType_ENUMDEFAULT PricePointType = "default" + PricePointType_CUSTOM PricePointType = "custom" ) -// PricingScheme is a string enum. +// PricingScheme is a string enum. // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. type PricingScheme string const ( - PricingScheme_STAIRSTEP PricingScheme = "stairstep" - PricingScheme_VOLUME PricingScheme = "volume" - PricingScheme_PERUNIT PricingScheme = "per_unit" - PricingScheme_TIERED PricingScheme = "tiered" + PricingScheme_STAIRSTEP PricingScheme = "stairstep" + PricingScheme_VOLUME PricingScheme = "volume" + PricingScheme_PERUNIT PricingScheme = "per_unit" + PricingScheme_TIERED PricingScheme = "tiered" ) // ProformaInvoiceDiscountSourceType is a string enum. type ProformaInvoiceDiscountSourceType string const ( - ProformaInvoiceDiscountSourceType_COUPON ProformaInvoiceDiscountSourceType = "Coupon" - ProformaInvoiceDiscountSourceType_REFERRAL ProformaInvoiceDiscountSourceType = "Referral" + ProformaInvoiceDiscountSourceType_COUPON ProformaInvoiceDiscountSourceType = "Coupon" + ProformaInvoiceDiscountSourceType_REFERRAL ProformaInvoiceDiscountSourceType = "Referral" ) -// ProformaInvoiceRole is a string enum. +// ProformaInvoiceRole is a string enum. // 'proforma' value is deprecated in favor of proforma_adhoc and proforma_automatic type ProformaInvoiceRole string const ( - ProformaInvoiceRole_UNSET ProformaInvoiceRole = "unset" - ProformaInvoiceRole_PROFORMA ProformaInvoiceRole = "proforma" - ProformaInvoiceRole_PROFORMAADHOC ProformaInvoiceRole = "proforma_adhoc" - ProformaInvoiceRole_PROFORMAAUTOMATIC ProformaInvoiceRole = "proforma_automatic" + ProformaInvoiceRole_UNSET ProformaInvoiceRole = "unset" + ProformaInvoiceRole_PROFORMA ProformaInvoiceRole = "proforma" + ProformaInvoiceRole_PROFORMAADHOC ProformaInvoiceRole = "proforma_adhoc" + ProformaInvoiceRole_PROFORMAAUTOMATIC ProformaInvoiceRole = "proforma_automatic" ) // ProformaInvoiceStatus is a string enum. type ProformaInvoiceStatus string const ( - ProformaInvoiceStatus_DRAFT ProformaInvoiceStatus = "draft" - ProformaInvoiceStatus_VOIDED ProformaInvoiceStatus = "voided" - ProformaInvoiceStatus_ARCHIVED ProformaInvoiceStatus = "archived" + ProformaInvoiceStatus_DRAFT ProformaInvoiceStatus = "draft" + ProformaInvoiceStatus_VOIDED ProformaInvoiceStatus = "voided" + ProformaInvoiceStatus_ARCHIVED ProformaInvoiceStatus = "archived" ) // ProformaInvoiceTaxSourceType is a string enum. type ProformaInvoiceTaxSourceType string const ( - ProformaInvoiceTaxSourceType_TAX ProformaInvoiceTaxSourceType = "Tax" - ProformaInvoiceTaxSourceType_AVALARA ProformaInvoiceTaxSourceType = "Avalara" + ProformaInvoiceTaxSourceType_TAX ProformaInvoiceTaxSourceType = "Tax" + ProformaInvoiceTaxSourceType_AVALARA ProformaInvoiceTaxSourceType = "Avalara" ) -// ReactivationCharge is a string enum. +// ReactivationCharge is a string enum. // You may choose how to handle the reactivation charge for that subscription: 1) `prorated` A prorated charge for the product price will be attempted for to complete the period 2) `immediate` A full-price charge for the product price will be attempted immediately 3) `delayed` A full-price charge for the product price will be attempted at the next renewal type ReactivationCharge string const ( - ReactivationCharge_PRORATED ReactivationCharge = "prorated" - ReactivationCharge_IMMEDIATE ReactivationCharge = "immediate" - ReactivationCharge_DELAYED ReactivationCharge = "delayed" + ReactivationCharge_PRORATED ReactivationCharge = "prorated" + ReactivationCharge_IMMEDIATE ReactivationCharge = "immediate" + ReactivationCharge_DELAYED ReactivationCharge = "delayed" ) // RecurringScheme is a string enum. type RecurringScheme string const ( - RecurringScheme_DONOTRECUR RecurringScheme = "do_not_recur" - RecurringScheme_RECURINDEFINITELY RecurringScheme = "recur_indefinitely" - RecurringScheme_RECURWITHDURATION RecurringScheme = "recur_with_duration" + RecurringScheme_DONOTRECUR RecurringScheme = "do_not_recur" + RecurringScheme_RECURINDEFINITELY RecurringScheme = "recur_indefinitely" + RecurringScheme_RECURWITHDURATION RecurringScheme = "recur_with_duration" ) // ResourceType is a string enum. type ResourceType string const ( - ResourceType_SUBSCRIPTIONS ResourceType = "subscriptions" - ResourceType_CUSTOMERS ResourceType = "customers" + ResourceType_SUBSCRIPTIONS ResourceType = "subscriptions" + ResourceType_CUSTOMERS ResourceType = "customers" ) // RestrictionType is a string enum. type RestrictionType string const ( - RestrictionType_COMPONENT RestrictionType = "Component" - RestrictionType_PRODUCT RestrictionType = "Product" + RestrictionType_COMPONENT RestrictionType = "Component" + RestrictionType_PRODUCT RestrictionType = "Product" ) -// ResumptionCharge is a string enum. +// ResumptionCharge is a string enum. // (For calendar billing subscriptions only) The way that the resumed subscription's charge should be handled type ResumptionCharge string const ( - ResumptionCharge_PRORATED ResumptionCharge = "prorated" - ResumptionCharge_IMMEDIATE ResumptionCharge = "immediate" - ResumptionCharge_DELAYED ResumptionCharge = "delayed" + ResumptionCharge_PRORATED ResumptionCharge = "prorated" + ResumptionCharge_IMMEDIATE ResumptionCharge = "immediate" + ResumptionCharge_DELAYED ResumptionCharge = "delayed" ) -// ServiceCreditType is a string enum. +// ServiceCreditType is a string enum. // The type of entry type ServiceCreditType string const ( - ServiceCreditType_CREDIT ServiceCreditType = "Credit" - ServiceCreditType_DEBIT ServiceCreditType = "Debit" + ServiceCreditType_CREDIT ServiceCreditType = "Credit" + ServiceCreditType_DEBIT ServiceCreditType = "Debit" +) + +// SnapDay is a string enum. +// Use for subscriptions with product eligible for calendar billing only. Value can be 1-28 or 'end'. +type SnapDay string + +const ( + SnapDay_END SnapDay = "end" ) -// SortingDirection is a string enum. +// SortingDirection is a string enum. // Used for sorting results. type SortingDirection string const ( - SortingDirection_ASC SortingDirection = "asc" - SortingDirection_DESC SortingDirection = "desc" + SortingDirection_ASC SortingDirection = "asc" + SortingDirection_DESC SortingDirection = "desc" ) // SubscriptionDateField is a string enum. type SubscriptionDateField string const ( - SubscriptionDateField_CURRENTPERIODENDSAT SubscriptionDateField = "current_period_ends_at" - SubscriptionDateField_CURRENTPERIODSTARTSAT SubscriptionDateField = "current_period_starts_at" - SubscriptionDateField_CREATEDAT SubscriptionDateField = "created_at" - SubscriptionDateField_ACTIVATEDAT SubscriptionDateField = "activated_at" - SubscriptionDateField_CANCELEDAT SubscriptionDateField = "canceled_at" - SubscriptionDateField_EXPIRESAT SubscriptionDateField = "expires_at" - SubscriptionDateField_TRIALSTARTEDAT SubscriptionDateField = "trial_started_at" - SubscriptionDateField_TRIALENDEDAT SubscriptionDateField = "trial_ended_at" - SubscriptionDateField_UPDATEDAT SubscriptionDateField = "updated_at" + SubscriptionDateField_CURRENTPERIODENDSAT SubscriptionDateField = "current_period_ends_at" + SubscriptionDateField_CURRENTPERIODSTARTSAT SubscriptionDateField = "current_period_starts_at" + SubscriptionDateField_CREATEDAT SubscriptionDateField = "created_at" + SubscriptionDateField_ACTIVATEDAT SubscriptionDateField = "activated_at" + SubscriptionDateField_CANCELEDAT SubscriptionDateField = "canceled_at" + SubscriptionDateField_EXPIRESAT SubscriptionDateField = "expires_at" + SubscriptionDateField_TRIALSTARTEDAT SubscriptionDateField = "trial_started_at" + SubscriptionDateField_TRIALENDEDAT SubscriptionDateField = "trial_ended_at" + SubscriptionDateField_UPDATEDAT SubscriptionDateField = "updated_at" +) + +// SubscriptionGroupInclude is a string enum. +type SubscriptionGroupInclude string + +const ( + SubscriptionGroupInclude_CURRENTBILLINGAMOUNTINCENTS SubscriptionGroupInclude = "current_billing_amount_in_cents" ) // SubscriptionGroupPrepaymentMethod is a string enum. type SubscriptionGroupPrepaymentMethod string const ( - SubscriptionGroupPrepaymentMethod_CHECK SubscriptionGroupPrepaymentMethod = "check" - SubscriptionGroupPrepaymentMethod_CASH SubscriptionGroupPrepaymentMethod = "cash" - SubscriptionGroupPrepaymentMethod_MONEYORDER SubscriptionGroupPrepaymentMethod = "money_order" - SubscriptionGroupPrepaymentMethod_ACH SubscriptionGroupPrepaymentMethod = "ach" - SubscriptionGroupPrepaymentMethod_PAYPALACCOUNT SubscriptionGroupPrepaymentMethod = "paypal_account" - SubscriptionGroupPrepaymentMethod_OTHER SubscriptionGroupPrepaymentMethod = "other" + SubscriptionGroupPrepaymentMethod_CHECK SubscriptionGroupPrepaymentMethod = "check" + SubscriptionGroupPrepaymentMethod_CASH SubscriptionGroupPrepaymentMethod = "cash" + SubscriptionGroupPrepaymentMethod_MONEYORDER SubscriptionGroupPrepaymentMethod = "money_order" + SubscriptionGroupPrepaymentMethod_ACH SubscriptionGroupPrepaymentMethod = "ach" + SubscriptionGroupPrepaymentMethod_PAYPALACCOUNT SubscriptionGroupPrepaymentMethod = "paypal_account" + SubscriptionGroupPrepaymentMethod_OTHER SubscriptionGroupPrepaymentMethod = "other" +) + +// SubscriptionGroupsListInclude is a string enum. +type SubscriptionGroupsListInclude string + +const ( + SubscriptionGroupsListInclude_ACCOUNTBALANCES SubscriptionGroupsListInclude = "account_balances" ) // SubscriptionInclude is a string enum. type SubscriptionInclude string const ( - SubscriptionInclude_COUPONS SubscriptionInclude = "coupons" - SubscriptionInclude_SELFSERVICEPAGETOKEN SubscriptionInclude = "self_service_page_token" + SubscriptionInclude_COUPONS SubscriptionInclude = "coupons" + SubscriptionInclude_SELFSERVICEPAGETOKEN SubscriptionInclude = "self_service_page_token" ) // SubscriptionListDateField is a string enum. type SubscriptionListDateField string const ( - SubscriptionListDateField_UPDATEDAT SubscriptionListDateField = "updated_at" + SubscriptionListDateField_UPDATEDAT SubscriptionListDateField = "updated_at" ) // SubscriptionListInclude is a string enum. type SubscriptionListInclude string const ( - SubscriptionListInclude_SELFSERVICEPAGETOKEN SubscriptionListInclude = "self_service_page_token" + SubscriptionListInclude_SELFSERVICEPAGETOKEN SubscriptionListInclude = "self_service_page_token" ) // SubscriptionPurgeType is a string enum. type SubscriptionPurgeType string const ( - SubscriptionPurgeType_CUSTOMER SubscriptionPurgeType = "customer" - SubscriptionPurgeType_PAYMENTPROFILE SubscriptionPurgeType = "payment_profile" + SubscriptionPurgeType_CUSTOMER SubscriptionPurgeType = "customer" + SubscriptionPurgeType_PAYMENTPROFILE SubscriptionPurgeType = "payment_profile" ) // SubscriptionSort is a string enum. type SubscriptionSort string const ( - SubscriptionSort_SIGNUPDATE SubscriptionSort = "signup_date" - SubscriptionSort_PERIODSTART SubscriptionSort = "period_start" - SubscriptionSort_PERIODEND SubscriptionSort = "period_end" - SubscriptionSort_NEXTASSESSMENT SubscriptionSort = "next_assessment" - SubscriptionSort_UPDATEDAT SubscriptionSort = "updated_at" - SubscriptionSort_CREATEDAT SubscriptionSort = "created_at" + SubscriptionSort_SIGNUPDATE SubscriptionSort = "signup_date" + SubscriptionSort_PERIODSTART SubscriptionSort = "period_start" + SubscriptionSort_PERIODEND SubscriptionSort = "period_end" + SubscriptionSort_NEXTASSESSMENT SubscriptionSort = "next_assessment" + SubscriptionSort_UPDATEDAT SubscriptionSort = "updated_at" + SubscriptionSort_CREATEDAT SubscriptionSort = "created_at" ) -// SubscriptionState is a string enum. +// SubscriptionState is a string enum. // The state of a subscription. // * **Live States** -// * `active` - A normal, active subscription. It is not in a trial and is paid and up to date. -// * `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed. -// * `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed. -// * `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state. -// * `paused` - An internal state that indicates that your account with Advanced Billing is in arrears. +// - `active` - A normal, active subscription. It is not in a trial and is paid and up to date. +// - `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed. +// - `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed. +// - `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state. +// - `paused` - An internal state that indicates that your account with Advanced Billing is in arrears. +// // * **Problem States** -// * `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers. -// * `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed. -// * `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`. +// - `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers. +// - `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed. +// - `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`. +// // * **End of Life States** -// * `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription. +// - `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription. // While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance. -// * `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period. -// * `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.) -// * `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time. -// * `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state. -// * `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details. +// - `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period. +// - `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.) +// - `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time. +// - `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state. +// - `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details. +// // See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. type SubscriptionState string const ( - SubscriptionState_PENDING SubscriptionState = "pending" - SubscriptionState_FAILEDTOCREATE SubscriptionState = "failed_to_create" - SubscriptionState_TRIALING SubscriptionState = "trialing" - SubscriptionState_ASSESSING SubscriptionState = "assessing" - SubscriptionState_ACTIVE SubscriptionState = "active" - SubscriptionState_SOFTFAILURE SubscriptionState = "soft_failure" - SubscriptionState_PASTDUE SubscriptionState = "past_due" - SubscriptionState_SUSPENDED SubscriptionState = "suspended" - SubscriptionState_CANCELED SubscriptionState = "canceled" - SubscriptionState_EXPIRED SubscriptionState = "expired" - SubscriptionState_PAUSED SubscriptionState = "paused" - SubscriptionState_UNPAID SubscriptionState = "unpaid" - SubscriptionState_TRIALENDED SubscriptionState = "trial_ended" - SubscriptionState_ONHOLD SubscriptionState = "on_hold" - SubscriptionState_AWAITINGSIGNUP SubscriptionState = "awaiting_signup" -) - -// SubscriptionStateFilter is a string enum. + SubscriptionState_PENDING SubscriptionState = "pending" + SubscriptionState_FAILEDTOCREATE SubscriptionState = "failed_to_create" + SubscriptionState_TRIALING SubscriptionState = "trialing" + SubscriptionState_ASSESSING SubscriptionState = "assessing" + SubscriptionState_ACTIVE SubscriptionState = "active" + SubscriptionState_SOFTFAILURE SubscriptionState = "soft_failure" + SubscriptionState_PASTDUE SubscriptionState = "past_due" + SubscriptionState_SUSPENDED SubscriptionState = "suspended" + SubscriptionState_CANCELED SubscriptionState = "canceled" + SubscriptionState_EXPIRED SubscriptionState = "expired" + SubscriptionState_PAUSED SubscriptionState = "paused" + SubscriptionState_UNPAID SubscriptionState = "unpaid" + SubscriptionState_TRIALENDED SubscriptionState = "trial_ended" + SubscriptionState_ONHOLD SubscriptionState = "on_hold" + SubscriptionState_AWAITINGSIGNUP SubscriptionState = "awaiting_signup" +) + +// SubscriptionStateFilter is a string enum. // Allowed values for filtering by the current state of the subscription. type SubscriptionStateFilter string const ( - SubscriptionStateFilter_ACTIVE SubscriptionStateFilter = "active" - SubscriptionStateFilter_CANCELED SubscriptionStateFilter = "canceled" - SubscriptionStateFilter_EXPIRED SubscriptionStateFilter = "expired" - SubscriptionStateFilter_EXPIREDCARDS SubscriptionStateFilter = "expired_cards" - SubscriptionStateFilter_ONHOLD SubscriptionStateFilter = "on_hold" - SubscriptionStateFilter_PASTDUE SubscriptionStateFilter = "past_due" - SubscriptionStateFilter_PENDINGCANCELLATION SubscriptionStateFilter = "pending_cancellation" - SubscriptionStateFilter_PENDINGRENEWAL SubscriptionStateFilter = "pending_renewal" - SubscriptionStateFilter_SUSPENDED SubscriptionStateFilter = "suspended" - SubscriptionStateFilter_TRIALENDED SubscriptionStateFilter = "trial_ended" - SubscriptionStateFilter_TRIALING SubscriptionStateFilter = "trialing" - SubscriptionStateFilter_UNPAID SubscriptionStateFilter = "unpaid" + SubscriptionStateFilter_ACTIVE SubscriptionStateFilter = "active" + SubscriptionStateFilter_CANCELED SubscriptionStateFilter = "canceled" + SubscriptionStateFilter_EXPIRED SubscriptionStateFilter = "expired" + SubscriptionStateFilter_EXPIREDCARDS SubscriptionStateFilter = "expired_cards" + SubscriptionStateFilter_ONHOLD SubscriptionStateFilter = "on_hold" + SubscriptionStateFilter_PASTDUE SubscriptionStateFilter = "past_due" + SubscriptionStateFilter_PENDINGCANCELLATION SubscriptionStateFilter = "pending_cancellation" + SubscriptionStateFilter_PENDINGRENEWAL SubscriptionStateFilter = "pending_renewal" + SubscriptionStateFilter_SUSPENDED SubscriptionStateFilter = "suspended" + SubscriptionStateFilter_TRIALENDED SubscriptionStateFilter = "trial_ended" + SubscriptionStateFilter_TRIALING SubscriptionStateFilter = "trialing" + SubscriptionStateFilter_UNPAID SubscriptionStateFilter = "unpaid" ) // TaxConfigurationKind is a string enum. type TaxConfigurationKind string const ( - TaxConfigurationKind_CUSTOM TaxConfigurationKind = "custom" - TaxConfigurationKind_ENUMMANAGEDAVALARA TaxConfigurationKind = "managed avalara" - TaxConfigurationKind_ENUMLINKEDAVALARA TaxConfigurationKind = "linked avalara" - TaxConfigurationKind_ENUMDIGITALRIVER TaxConfigurationKind = "digital river" + TaxConfigurationKind_CUSTOM TaxConfigurationKind = "custom" + TaxConfigurationKind_ENUMMANAGEDAVALARA TaxConfigurationKind = "managed avalara" + TaxConfigurationKind_ENUMLINKEDAVALARA TaxConfigurationKind = "linked avalara" + TaxConfigurationKind_ENUMDIGITALRIVER TaxConfigurationKind = "digital river" ) // TaxDestinationAddress is a string enum. type TaxDestinationAddress string const ( - TaxDestinationAddress_SHIPPINGTHENBILLING TaxDestinationAddress = "shipping_then_billing" - TaxDestinationAddress_BILLINGTHENSHIPPING TaxDestinationAddress = "billing_then_shipping" - TaxDestinationAddress_SHIPPINGONLY TaxDestinationAddress = "shipping_only" - TaxDestinationAddress_BILLINGONLY TaxDestinationAddress = "billing_only" + TaxDestinationAddress_SHIPPINGTHENBILLING TaxDestinationAddress = "shipping_then_billing" + TaxDestinationAddress_BILLINGTHENSHIPPING TaxDestinationAddress = "billing_then_shipping" + TaxDestinationAddress_SHIPPINGONLY TaxDestinationAddress = "shipping_only" + TaxDestinationAddress_BILLINGONLY TaxDestinationAddress = "billing_only" ) // WebhookOrder is a string enum. type WebhookOrder string const ( - WebhookOrder_NEWESTFIRST WebhookOrder = "newest_first" - WebhookOrder_OLDESTFIRST WebhookOrder = "oldest_first" + WebhookOrder_NEWESTFIRST WebhookOrder = "newest_first" + WebhookOrder_OLDESTFIRST WebhookOrder = "oldest_first" ) // WebhookStatus is a string enum. type WebhookStatus string const ( - WebhookStatus_SUCCESSFUL WebhookStatus = "successful" - WebhookStatus_FAILED WebhookStatus = "failed" - WebhookStatus_PENDING WebhookStatus = "pending" - WebhookStatus_PAUSED WebhookStatus = "paused" + WebhookStatus_SUCCESSFUL WebhookStatus = "successful" + WebhookStatus_FAILED WebhookStatus = "failed" + WebhookStatus_PENDING WebhookStatus = "pending" + WebhookStatus_PAUSED WebhookStatus = "paused" ) // WebhookSubscription is a string enum. type WebhookSubscription string const ( - WebhookSubscription_BILLINGDATECHANGE WebhookSubscription = "billing_date_change" - WebhookSubscription_COMPONENTALLOCATIONCHANGE WebhookSubscription = "component_allocation_change" - WebhookSubscription_CUSTOMERCREATE WebhookSubscription = "customer_create" - WebhookSubscription_CUSTOMERUPDATE WebhookSubscription = "customer_update" - WebhookSubscription_DUNNINGSTEPREACHED WebhookSubscription = "dunning_step_reached" - WebhookSubscription_EXPIRINGCARD WebhookSubscription = "expiring_card" - WebhookSubscription_EXPIRATIONDATECHANGE WebhookSubscription = "expiration_date_change" - WebhookSubscription_INVOICEISSUED WebhookSubscription = "invoice_issued" - WebhookSubscription_METEREDUSAGE WebhookSubscription = "metered_usage" - WebhookSubscription_PAYMENTFAILURE WebhookSubscription = "payment_failure" - WebhookSubscription_PAYMENTSUCCESS WebhookSubscription = "payment_success" - WebhookSubscription_DIRECTDEBITPAYMENTPENDING WebhookSubscription = "direct_debit_payment_pending" - WebhookSubscription_DIRECTDEBITPAYMENTPAIDOUT WebhookSubscription = "direct_debit_payment_paid_out" - WebhookSubscription_DIRECTDEBITPAYMENTREJECTED WebhookSubscription = "direct_debit_payment_rejected" - WebhookSubscription_PREPAIDSUBSCRIPTIONBALANCECHANGED WebhookSubscription = "prepaid_subscription_balance_changed" - WebhookSubscription_PREPAIDUSAGE WebhookSubscription = "prepaid_usage" - WebhookSubscription_REFUNDFAILURE WebhookSubscription = "refund_failure" - WebhookSubscription_REFUNDSUCCESS WebhookSubscription = "refund_success" - WebhookSubscription_RENEWALFAILURE WebhookSubscription = "renewal_failure" - WebhookSubscription_RENEWALSUCCESS WebhookSubscription = "renewal_success" - WebhookSubscription_SIGNUPFAILURE WebhookSubscription = "signup_failure" - WebhookSubscription_SIGNUPSUCCESS WebhookSubscription = "signup_success" - WebhookSubscription_STATEMENTCLOSED WebhookSubscription = "statement_closed" - WebhookSubscription_STATEMENTSETTLED WebhookSubscription = "statement_settled" - WebhookSubscription_SUBSCRIPTIONCARDUPDATE WebhookSubscription = "subscription_card_update" - WebhookSubscription_SUBSCRIPTIONGROUPCARDUPDATE WebhookSubscription = "subscription_group_card_update" - WebhookSubscription_SUBSCRIPTIONPRODUCTCHANGE WebhookSubscription = "subscription_product_change" - WebhookSubscription_SUBSCRIPTIONSTATECHANGE WebhookSubscription = "subscription_state_change" - WebhookSubscription_TRIALENDNOTICE WebhookSubscription = "trial_end_notice" - WebhookSubscription_UPCOMINGRENEWALNOTICE WebhookSubscription = "upcoming_renewal_notice" - WebhookSubscription_UPGRADEDOWNGRADEFAILURE WebhookSubscription = "upgrade_downgrade_failure" - WebhookSubscription_UPGRADEDOWNGRADESUCCESS WebhookSubscription = "upgrade_downgrade_success" - WebhookSubscription_PENDINGCANCELLATIONCHANGE WebhookSubscription = "pending_cancellation_change" - WebhookSubscription_SUBSCRIPTIONPREPAYMENTACCOUNTBALANCECHANGED WebhookSubscription = "subscription_prepayment_account_balance_changed" - WebhookSubscription_SUBSCRIPTIONSERVICECREDITACCOUNTBALANCECHANGED WebhookSubscription = "subscription_service_credit_account_balance_changed" + WebhookSubscription_BILLINGDATECHANGE WebhookSubscription = "billing_date_change" + WebhookSubscription_COMPONENTALLOCATIONCHANGE WebhookSubscription = "component_allocation_change" + WebhookSubscription_CUSTOMERCREATE WebhookSubscription = "customer_create" + WebhookSubscription_CUSTOMERUPDATE WebhookSubscription = "customer_update" + WebhookSubscription_DUNNINGSTEPREACHED WebhookSubscription = "dunning_step_reached" + WebhookSubscription_EXPIRINGCARD WebhookSubscription = "expiring_card" + WebhookSubscription_EXPIRATIONDATECHANGE WebhookSubscription = "expiration_date_change" + WebhookSubscription_INVOICEISSUED WebhookSubscription = "invoice_issued" + WebhookSubscription_METEREDUSAGE WebhookSubscription = "metered_usage" + WebhookSubscription_PAYMENTFAILURE WebhookSubscription = "payment_failure" + WebhookSubscription_PAYMENTSUCCESS WebhookSubscription = "payment_success" + WebhookSubscription_DIRECTDEBITPAYMENTPENDING WebhookSubscription = "direct_debit_payment_pending" + WebhookSubscription_DIRECTDEBITPAYMENTPAIDOUT WebhookSubscription = "direct_debit_payment_paid_out" + WebhookSubscription_DIRECTDEBITPAYMENTREJECTED WebhookSubscription = "direct_debit_payment_rejected" + WebhookSubscription_PREPAIDSUBSCRIPTIONBALANCECHANGED WebhookSubscription = "prepaid_subscription_balance_changed" + WebhookSubscription_PREPAIDUSAGE WebhookSubscription = "prepaid_usage" + WebhookSubscription_REFUNDFAILURE WebhookSubscription = "refund_failure" + WebhookSubscription_REFUNDSUCCESS WebhookSubscription = "refund_success" + WebhookSubscription_RENEWALFAILURE WebhookSubscription = "renewal_failure" + WebhookSubscription_RENEWALSUCCESS WebhookSubscription = "renewal_success" + WebhookSubscription_SIGNUPFAILURE WebhookSubscription = "signup_failure" + WebhookSubscription_SIGNUPSUCCESS WebhookSubscription = "signup_success" + WebhookSubscription_STATEMENTCLOSED WebhookSubscription = "statement_closed" + WebhookSubscription_STATEMENTSETTLED WebhookSubscription = "statement_settled" + WebhookSubscription_SUBSCRIPTIONCARDUPDATE WebhookSubscription = "subscription_card_update" + WebhookSubscription_SUBSCRIPTIONGROUPCARDUPDATE WebhookSubscription = "subscription_group_card_update" + WebhookSubscription_SUBSCRIPTIONPRODUCTCHANGE WebhookSubscription = "subscription_product_change" + WebhookSubscription_SUBSCRIPTIONSTATECHANGE WebhookSubscription = "subscription_state_change" + WebhookSubscription_TRIALENDNOTICE WebhookSubscription = "trial_end_notice" + WebhookSubscription_UPCOMINGRENEWALNOTICE WebhookSubscription = "upcoming_renewal_notice" + WebhookSubscription_UPGRADEDOWNGRADEFAILURE WebhookSubscription = "upgrade_downgrade_failure" + WebhookSubscription_UPGRADEDOWNGRADESUCCESS WebhookSubscription = "upgrade_downgrade_success" + WebhookSubscription_PENDINGCANCELLATIONCHANGE WebhookSubscription = "pending_cancellation_change" + WebhookSubscription_SUBSCRIPTIONPREPAYMENTACCOUNTBALANCECHANGED WebhookSubscription = "subscription_prepayment_account_balance_changed" + WebhookSubscription_SUBSCRIPTIONSERVICECREDITACCOUNTBALANCECHANGED WebhookSubscription = "subscription_service_credit_account_balance_changed" ) diff --git a/models/event.go b/models/event.go index a38cdc2e..a6195644 100644 --- a/models/event.go +++ b/models/event.go @@ -1,70 +1,111 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "errors" + "log" + "strings" + "time" ) // Event represents a Event struct. type Event struct { - Id int `json:"id"` - Key string `json:"key"` - Message string `json:"message"` - SubscriptionId *int `json:"subscription_id"` - CustomerId *int `json:"customer_id"` - CreatedAt time.Time `json:"created_at"` - EventSpecificData interface{} `json:"event_specific_data"` + Id int `json:"id"` + Key string `json:"key"` + Message string `json:"message"` + SubscriptionId *int `json:"subscription_id"` + CustomerId *int `json:"customer_id"` + CreatedAt time.Time `json:"created_at"` + EventSpecificData *EventEventSpecificData `json:"event_specific_data"` } -// MarshalJSON implements the json.Marshaler interface for Event. +// MarshalJSON implements the json.Marshaler interface for Event. // It customizes the JSON marshaling process for Event objects. func (e *Event) MarshalJSON() ( - []byte, - error) { - return json.Marshal(e.toMap()) + []byte, + error) { + return json.Marshal(e.toMap()) } // toMap converts the Event object to a map representation for JSON marshaling. func (e *Event) toMap() map[string]any { - structMap := make(map[string]any) - structMap["id"] = e.Id - structMap["key"] = e.Key - structMap["message"] = e.Message - structMap["subscription_id"] = e.SubscriptionId - structMap["customer_id"] = e.CustomerId - structMap["created_at"] = e.CreatedAt.Format(time.RFC3339) - structMap["event_specific_data"] = e.EventSpecificData - return structMap + structMap := make(map[string]any) + structMap["id"] = e.Id + structMap["key"] = e.Key + structMap["message"] = e.Message + if e.SubscriptionId != nil { + structMap["subscription_id"] = e.SubscriptionId + } else { + structMap["subscription_id"] = nil + } + if e.CustomerId != nil { + structMap["customer_id"] = e.CustomerId + } else { + structMap["customer_id"] = nil + } + structMap["created_at"] = e.CreatedAt.Format(time.RFC3339) + if e.EventSpecificData != nil { + structMap["event_specific_data"] = e.EventSpecificData.toMap() + } else { + structMap["event_specific_data"] = nil + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Event. +// UnmarshalJSON implements the json.Unmarshaler interface for Event. // It customizes the JSON unmarshaling process for Event objects. func (e *Event) UnmarshalJSON(input []byte) error { - temp := &struct { - Id int `json:"id"` - Key string `json:"key"` - Message string `json:"message"` - SubscriptionId *int `json:"subscription_id"` - CustomerId *int `json:"customer_id"` - CreatedAt string `json:"created_at"` - EventSpecificData interface{} `json:"event_specific_data"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - e.Id = temp.Id - e.Key = temp.Key - e.Message = temp.Message - e.SubscriptionId = temp.SubscriptionId - e.CustomerId = temp.CustomerId - CreatedAtVal, err := time.Parse(time.RFC3339, temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - e.CreatedAt = CreatedAtVal - e.EventSpecificData = temp.EventSpecificData - return nil + var temp event + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + e.Id = *temp.Id + e.Key = *temp.Key + e.Message = *temp.Message + e.SubscriptionId = temp.SubscriptionId + e.CustomerId = temp.CustomerId + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + e.CreatedAt = CreatedAtVal + e.EventSpecificData = temp.EventSpecificData + return nil +} + +// TODO +type event struct { + Id *int `json:"id"` + Key *string `json:"key"` + Message *string `json:"message"` + SubscriptionId *int `json:"subscription_id"` + CustomerId *int `json:"customer_id"` + CreatedAt *string `json:"created_at"` + EventSpecificData *EventEventSpecificData `json:"event_specific_data"` +} + +func (e *event) validate() error { + var errs []string + if e.Id == nil { + errs = append(errs, "required field `id` is missing for type `Event`") + } + if e.Key == nil { + errs = append(errs, "required field `key` is missing for type `Event`") + } + if e.Message == nil { + errs = append(errs, "required field `message` is missing for type `Event`") + } + if e.CreatedAt == nil { + errs = append(errs, "required field `created_at` is missing for type `Event`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/event_based_billing_segment_error.go b/models/event_based_billing_segment_error.go index d800b77f..379bd8c3 100644 --- a/models/event_based_billing_segment_error.go +++ b/models/event_based_billing_segment_error.go @@ -1,41 +1,61 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // EventBasedBillingSegmentError represents a EventBasedBillingSegmentError struct. type EventBasedBillingSegmentError struct { - // The key of the object would be a number (an index in the request array) where the error occurred. In the value object, the key represents the field and the value is an array with error messages. In most cases, this object would contain just one key. - Segments map[string]interface{} `json:"segments"` + // The key of the object would be a number (an index in the request array) where the error occurred. In the value object, the key represents the field and the value is an array with error messages. In most cases, this object would contain just one key. + Segments map[string]interface{} `json:"segments"` } -// MarshalJSON implements the json.Marshaler interface for EventBasedBillingSegmentError. +// MarshalJSON implements the json.Marshaler interface for EventBasedBillingSegmentError. // It customizes the JSON marshaling process for EventBasedBillingSegmentError objects. func (e *EventBasedBillingSegmentError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(e.toMap()) + []byte, + error) { + return json.Marshal(e.toMap()) } // toMap converts the EventBasedBillingSegmentError object to a map representation for JSON marshaling. func (e *EventBasedBillingSegmentError) toMap() map[string]any { - structMap := make(map[string]any) - structMap["segments"] = e.Segments - return structMap + structMap := make(map[string]any) + structMap["segments"] = e.Segments + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for EventBasedBillingSegmentError. +// UnmarshalJSON implements the json.Unmarshaler interface for EventBasedBillingSegmentError. // It customizes the JSON unmarshaling process for EventBasedBillingSegmentError objects. func (e *EventBasedBillingSegmentError) UnmarshalJSON(input []byte) error { - temp := &struct { - Segments map[string]interface{} `json:"segments"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - e.Segments = temp.Segments - return nil + var temp eventBasedBillingSegmentError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + e.Segments = *temp.Segments + return nil +} + +// TODO +type eventBasedBillingSegmentError struct { + Segments *map[string]interface{} `json:"segments"` +} + +func (e *eventBasedBillingSegmentError) validate() error { + var errs []string + if e.Segments == nil { + errs = append(errs, "required field `segments` is missing for type `Event Based Billing Segment Error`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/event_event_specific_data.go b/models/event_event_specific_data.go new file mode 100644 index 00000000..a9d821cc --- /dev/null +++ b/models/event_event_specific_data.go @@ -0,0 +1,383 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// EventEventSpecificData represents a EventEventSpecificData struct. +// This is a container for one-of cases. +type EventEventSpecificData struct { + value any + isSubscriptionProductChange bool + isSubscriptionStateChange bool + isPaymentRelatedEvents bool + isRefundSuccess bool + isComponentAllocationChange bool + isMeteredUsage bool + isPrepaidUsage bool + isDunningStepReached bool + isInvoiceIssued bool + isPendingCancellationChange bool + isPrepaidSubscriptionBalanceChanged bool + isProformaInvoiceIssued bool + isSubscriptionGroupSignupSuccess bool + isSubscriptionGroupSignupFailure bool + isCreditAccountBalanceChanged bool + isPrepaymentAccountBalanceChanged bool + isPaymentCollectionMethodChanged bool + isItemPricePointChanged bool + isCustomFieldValueChange bool +} + +// String converts the EventEventSpecificData object to a string representation. +func (e EventEventSpecificData) String() string { + if bytes, err := json.Marshal(e.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for EventEventSpecificData. +// It customizes the JSON marshaling process for EventEventSpecificData objects. +func (e *EventEventSpecificData) MarshalJSON() ( + []byte, + error) { + if e.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.EventEventSpecificDataContainer.From*` functions to initialize the EventEventSpecificData object.") + } + return json.Marshal(e.toMap()) +} + +// toMap converts the EventEventSpecificData object to a map representation for JSON marshaling. +func (e *EventEventSpecificData) toMap() any { + switch obj := e.value.(type) { + case *SubscriptionProductChange: + return obj.toMap() + case *SubscriptionStateChange: + return obj.toMap() + case *PaymentRelatedEvents: + return obj.toMap() + case *RefundSuccess: + return obj.toMap() + case *ComponentAllocationChange: + return obj.toMap() + case *MeteredUsage: + return obj.toMap() + case *PrepaidUsage: + return obj.toMap() + case *DunningStepReached: + return obj.toMap() + case *InvoiceIssued: + return obj.toMap() + case *PendingCancellationChange: + return obj.toMap() + case *PrepaidSubscriptionBalanceChanged: + return obj.toMap() + case *ProformaInvoiceIssued: + return obj.toMap() + case *SubscriptionGroupSignupSuccess: + return obj.toMap() + case *SubscriptionGroupSignupFailure: + return obj.toMap() + case *CreditAccountBalanceChanged: + return obj.toMap() + case *PrepaymentAccountBalanceChanged: + return obj.toMap() + case *PaymentCollectionMethodChanged: + return obj.toMap() + case *ItemPricePointChanged: + return obj.toMap() + case *CustomFieldValueChange: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for EventEventSpecificData. +// It customizes the JSON unmarshaling process for EventEventSpecificData objects. +func (e *EventEventSpecificData) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&SubscriptionProductChange{}, false, &e.isSubscriptionProductChange), + NewTypeHolder(&SubscriptionStateChange{}, false, &e.isSubscriptionStateChange), + NewTypeHolder(&PaymentRelatedEvents{}, false, &e.isPaymentRelatedEvents), + NewTypeHolder(&RefundSuccess{}, false, &e.isRefundSuccess), + NewTypeHolder(&ComponentAllocationChange{}, false, &e.isComponentAllocationChange), + NewTypeHolder(&MeteredUsage{}, false, &e.isMeteredUsage), + NewTypeHolder(&PrepaidUsage{}, false, &e.isPrepaidUsage), + NewTypeHolder(&DunningStepReached{}, false, &e.isDunningStepReached), + NewTypeHolder(&InvoiceIssued{}, false, &e.isInvoiceIssued), + NewTypeHolder(&PendingCancellationChange{}, false, &e.isPendingCancellationChange), + NewTypeHolder(&PrepaidSubscriptionBalanceChanged{}, false, &e.isPrepaidSubscriptionBalanceChanged), + NewTypeHolder(&ProformaInvoiceIssued{}, false, &e.isProformaInvoiceIssued), + NewTypeHolder(&SubscriptionGroupSignupSuccess{}, false, &e.isSubscriptionGroupSignupSuccess), + NewTypeHolder(&SubscriptionGroupSignupFailure{}, false, &e.isSubscriptionGroupSignupFailure), + NewTypeHolder(&CreditAccountBalanceChanged{}, false, &e.isCreditAccountBalanceChanged), + NewTypeHolder(&PrepaymentAccountBalanceChanged{}, false, &e.isPrepaymentAccountBalanceChanged), + NewTypeHolder(&PaymentCollectionMethodChanged{}, false, &e.isPaymentCollectionMethodChanged), + NewTypeHolder(&ItemPricePointChanged{}, false, &e.isItemPricePointChanged), + NewTypeHolder(&CustomFieldValueChange{}, false, &e.isCustomFieldValueChange), + ) + + e.value = result + return err +} + +func (e *EventEventSpecificData) AsSubscriptionProductChange() ( + *SubscriptionProductChange, + bool) { + if !e.isSubscriptionProductChange { + return nil, false + } + return e.value.(*SubscriptionProductChange), true +} + +func (e *EventEventSpecificData) AsSubscriptionStateChange() ( + *SubscriptionStateChange, + bool) { + if !e.isSubscriptionStateChange { + return nil, false + } + return e.value.(*SubscriptionStateChange), true +} + +func (e *EventEventSpecificData) AsPaymentRelatedEvents() ( + *PaymentRelatedEvents, + bool) { + if !e.isPaymentRelatedEvents { + return nil, false + } + return e.value.(*PaymentRelatedEvents), true +} + +func (e *EventEventSpecificData) AsRefundSuccess() ( + *RefundSuccess, + bool) { + if !e.isRefundSuccess { + return nil, false + } + return e.value.(*RefundSuccess), true +} + +func (e *EventEventSpecificData) AsComponentAllocationChange() ( + *ComponentAllocationChange, + bool) { + if !e.isComponentAllocationChange { + return nil, false + } + return e.value.(*ComponentAllocationChange), true +} + +func (e *EventEventSpecificData) AsMeteredUsage() ( + *MeteredUsage, + bool) { + if !e.isMeteredUsage { + return nil, false + } + return e.value.(*MeteredUsage), true +} + +func (e *EventEventSpecificData) AsPrepaidUsage() ( + *PrepaidUsage, + bool) { + if !e.isPrepaidUsage { + return nil, false + } + return e.value.(*PrepaidUsage), true +} + +func (e *EventEventSpecificData) AsDunningStepReached() ( + *DunningStepReached, + bool) { + if !e.isDunningStepReached { + return nil, false + } + return e.value.(*DunningStepReached), true +} + +func (e *EventEventSpecificData) AsInvoiceIssued() ( + *InvoiceIssued, + bool) { + if !e.isInvoiceIssued { + return nil, false + } + return e.value.(*InvoiceIssued), true +} + +func (e *EventEventSpecificData) AsPendingCancellationChange() ( + *PendingCancellationChange, + bool) { + if !e.isPendingCancellationChange { + return nil, false + } + return e.value.(*PendingCancellationChange), true +} + +func (e *EventEventSpecificData) AsPrepaidSubscriptionBalanceChanged() ( + *PrepaidSubscriptionBalanceChanged, + bool) { + if !e.isPrepaidSubscriptionBalanceChanged { + return nil, false + } + return e.value.(*PrepaidSubscriptionBalanceChanged), true +} + +func (e *EventEventSpecificData) AsProformaInvoiceIssued() ( + *ProformaInvoiceIssued, + bool) { + if !e.isProformaInvoiceIssued { + return nil, false + } + return e.value.(*ProformaInvoiceIssued), true +} + +func (e *EventEventSpecificData) AsSubscriptionGroupSignupSuccess() ( + *SubscriptionGroupSignupSuccess, + bool) { + if !e.isSubscriptionGroupSignupSuccess { + return nil, false + } + return e.value.(*SubscriptionGroupSignupSuccess), true +} + +func (e *EventEventSpecificData) AsSubscriptionGroupSignupFailure() ( + *SubscriptionGroupSignupFailure, + bool) { + if !e.isSubscriptionGroupSignupFailure { + return nil, false + } + return e.value.(*SubscriptionGroupSignupFailure), true +} + +func (e *EventEventSpecificData) AsCreditAccountBalanceChanged() ( + *CreditAccountBalanceChanged, + bool) { + if !e.isCreditAccountBalanceChanged { + return nil, false + } + return e.value.(*CreditAccountBalanceChanged), true +} + +func (e *EventEventSpecificData) AsPrepaymentAccountBalanceChanged() ( + *PrepaymentAccountBalanceChanged, + bool) { + if !e.isPrepaymentAccountBalanceChanged { + return nil, false + } + return e.value.(*PrepaymentAccountBalanceChanged), true +} + +func (e *EventEventSpecificData) AsPaymentCollectionMethodChanged() ( + *PaymentCollectionMethodChanged, + bool) { + if !e.isPaymentCollectionMethodChanged { + return nil, false + } + return e.value.(*PaymentCollectionMethodChanged), true +} + +func (e *EventEventSpecificData) AsItemPricePointChanged() ( + *ItemPricePointChanged, + bool) { + if !e.isItemPricePointChanged { + return nil, false + } + return e.value.(*ItemPricePointChanged), true +} + +func (e *EventEventSpecificData) AsCustomFieldValueChange() ( + *CustomFieldValueChange, + bool) { + if !e.isCustomFieldValueChange { + return nil, false + } + return e.value.(*CustomFieldValueChange), true +} + +// internalEventEventSpecificData represents a eventEventSpecificData struct. +// This is a container for one-of cases. +type internalEventEventSpecificData struct{} + +var EventEventSpecificDataContainer internalEventEventSpecificData + +func (e *internalEventEventSpecificData) FromSubscriptionProductChange(val SubscriptionProductChange) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromSubscriptionStateChange(val SubscriptionStateChange) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromPaymentRelatedEvents(val PaymentRelatedEvents) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromRefundSuccess(val RefundSuccess) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromComponentAllocationChange(val ComponentAllocationChange) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromMeteredUsage(val MeteredUsage) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromPrepaidUsage(val PrepaidUsage) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromDunningStepReached(val DunningStepReached) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromInvoiceIssued(val InvoiceIssued) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromPendingCancellationChange(val PendingCancellationChange) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromPrepaidSubscriptionBalanceChanged(val PrepaidSubscriptionBalanceChanged) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromProformaInvoiceIssued(val ProformaInvoiceIssued) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromSubscriptionGroupSignupSuccess(val SubscriptionGroupSignupSuccess) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromSubscriptionGroupSignupFailure(val SubscriptionGroupSignupFailure) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromCreditAccountBalanceChanged(val CreditAccountBalanceChanged) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromPrepaymentAccountBalanceChanged(val PrepaymentAccountBalanceChanged) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromPaymentCollectionMethodChanged(val PaymentCollectionMethodChanged) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromItemPricePointChanged(val ItemPricePointChanged) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} + +func (e *internalEventEventSpecificData) FromCustomFieldValueChange(val CustomFieldValueChange) EventEventSpecificData { + return EventEventSpecificData{value: &val} +} diff --git a/models/event_response.go b/models/event_response.go index 9ed3b2f1..931fab14 100644 --- a/models/event_response.go +++ b/models/event_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // EventResponse represents a EventResponse struct. type EventResponse struct { - Event Event `json:"event"` + Event Event `json:"event"` } -// MarshalJSON implements the json.Marshaler interface for EventResponse. +// MarshalJSON implements the json.Marshaler interface for EventResponse. // It customizes the JSON marshaling process for EventResponse objects. func (e *EventResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(e.toMap()) + []byte, + error) { + return json.Marshal(e.toMap()) } // toMap converts the EventResponse object to a map representation for JSON marshaling. func (e *EventResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["event"] = e.Event.toMap() - return structMap + structMap := make(map[string]any) + structMap["event"] = e.Event.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for EventResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for EventResponse. // It customizes the JSON unmarshaling process for EventResponse objects. func (e *EventResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Event Event `json:"event"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - e.Event = temp.Event - return nil + var temp eventResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + e.Event = *temp.Event + return nil +} + +// TODO +type eventResponse struct { + Event *Event `json:"event"` +} + +func (e *eventResponse) validate() error { + var errs []string + if e.Event == nil { + errs = append(errs, "required field `event` is missing for type `Event Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/full_subscription_group_response.go b/models/full_subscription_group_response.go index 856936b1..72a66ecb 100644 --- a/models/full_subscription_group_response.go +++ b/models/full_subscription_group_response.go @@ -1,116 +1,138 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // FullSubscriptionGroupResponse represents a FullSubscriptionGroupResponse struct. type FullSubscriptionGroupResponse struct { - Uid *string `json:"uid,omitempty"` - Scheme *int `json:"scheme,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - SubscriptionIds []int `json:"subscription_ids,omitempty"` - PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` - NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` - State *string `json:"state,omitempty"` - CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` - CurrentBillingAmountInCents *int64 `json:"current_billing_amount_in_cents,omitempty"` - Customer *SubscriptionGroupCustomer `json:"customer,omitempty"` - AccountBalances *SubscriptionGroupBalances `json:"account_balances,omitempty"` + Uid *string `json:"uid,omitempty"` + Scheme *int `json:"scheme,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + SubscriptionIds []int `json:"subscription_ids,omitempty"` + PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` + NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` + // The state of a subscription. + // * **Live States** + // * `active` - A normal, active subscription. It is not in a trial and is paid and up to date. + // * `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed. + // * `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed. + // * `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state. + // * `paused` - An internal state that indicates that your account with Advanced Billing is in arrears. + // * **Problem States** + // * `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers. + // * `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed. + // * `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`. + // * **End of Life States** + // * `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription. + // While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance. + // * `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period. + // * `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.) + // * `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time. + // * `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state. + // * `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details. + // See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. + State *SubscriptionState `json:"state,omitempty"` + CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` + CurrentBillingAmountInCents *int64 `json:"current_billing_amount_in_cents,omitempty"` + Customer *SubscriptionGroupCustomer `json:"customer,omitempty"` + AccountBalances *SubscriptionGroupBalances `json:"account_balances,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for FullSubscriptionGroupResponse. +// MarshalJSON implements the json.Marshaler interface for FullSubscriptionGroupResponse. // It customizes the JSON marshaling process for FullSubscriptionGroupResponse objects. func (f *FullSubscriptionGroupResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(f.toMap()) + []byte, + error) { + return json.Marshal(f.toMap()) } // toMap converts the FullSubscriptionGroupResponse object to a map representation for JSON marshaling. func (f *FullSubscriptionGroupResponse) toMap() map[string]any { - structMap := make(map[string]any) - if f.Uid != nil { - structMap["uid"] = f.Uid - } - if f.Scheme != nil { - structMap["scheme"] = f.Scheme - } - if f.CustomerId != nil { - structMap["customer_id"] = f.CustomerId - } - if f.PaymentProfileId != nil { - structMap["payment_profile_id"] = f.PaymentProfileId - } - if f.SubscriptionIds != nil { - structMap["subscription_ids"] = f.SubscriptionIds - } - if f.PrimarySubscriptionId != nil { - structMap["primary_subscription_id"] = f.PrimarySubscriptionId - } - if f.NextAssessmentAt != nil { - structMap["next_assessment_at"] = f.NextAssessmentAt.Format(time.RFC3339) - } - if f.State != nil { - structMap["state"] = f.State - } - if f.CancelAtEndOfPeriod != nil { - structMap["cancel_at_end_of_period"] = f.CancelAtEndOfPeriod - } - if f.CurrentBillingAmountInCents != nil { - structMap["current_billing_amount_in_cents"] = f.CurrentBillingAmountInCents - } - if f.Customer != nil { - structMap["customer"] = f.Customer.toMap() - } - if f.AccountBalances != nil { - structMap["account_balances"] = f.AccountBalances.toMap() - } - return structMap + structMap := make(map[string]any) + if f.Uid != nil { + structMap["uid"] = f.Uid + } + if f.Scheme != nil { + structMap["scheme"] = f.Scheme + } + if f.CustomerId != nil { + structMap["customer_id"] = f.CustomerId + } + if f.PaymentProfileId != nil { + structMap["payment_profile_id"] = f.PaymentProfileId + } + if f.SubscriptionIds != nil { + structMap["subscription_ids"] = f.SubscriptionIds + } + if f.PrimarySubscriptionId != nil { + structMap["primary_subscription_id"] = f.PrimarySubscriptionId + } + if f.NextAssessmentAt != nil { + structMap["next_assessment_at"] = f.NextAssessmentAt.Format(time.RFC3339) + } + if f.State != nil { + structMap["state"] = f.State + } + if f.CancelAtEndOfPeriod != nil { + structMap["cancel_at_end_of_period"] = f.CancelAtEndOfPeriod + } + if f.CurrentBillingAmountInCents != nil { + structMap["current_billing_amount_in_cents"] = f.CurrentBillingAmountInCents + } + if f.Customer != nil { + structMap["customer"] = f.Customer.toMap() + } + if f.AccountBalances != nil { + structMap["account_balances"] = f.AccountBalances.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for FullSubscriptionGroupResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for FullSubscriptionGroupResponse. // It customizes the JSON unmarshaling process for FullSubscriptionGroupResponse objects. func (f *FullSubscriptionGroupResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Scheme *int `json:"scheme,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - SubscriptionIds []int `json:"subscription_ids,omitempty"` - PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` - NextAssessmentAt *string `json:"next_assessment_at,omitempty"` - State *string `json:"state,omitempty"` - CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` - CurrentBillingAmountInCents *int64 `json:"current_billing_amount_in_cents,omitempty"` - Customer *SubscriptionGroupCustomer `json:"customer,omitempty"` - AccountBalances *SubscriptionGroupBalances `json:"account_balances,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - f.Uid = temp.Uid - f.Scheme = temp.Scheme - f.CustomerId = temp.CustomerId - f.PaymentProfileId = temp.PaymentProfileId - f.SubscriptionIds = temp.SubscriptionIds - f.PrimarySubscriptionId = temp.PrimarySubscriptionId - if temp.NextAssessmentAt != nil { - NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) - if err != nil { - log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) - } - f.NextAssessmentAt = &NextAssessmentAtVal - } - f.State = temp.State - f.CancelAtEndOfPeriod = temp.CancelAtEndOfPeriod - f.CurrentBillingAmountInCents = temp.CurrentBillingAmountInCents - f.Customer = temp.Customer - f.AccountBalances = temp.AccountBalances - return nil + var temp fullSubscriptionGroupResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + f.Uid = temp.Uid + f.Scheme = temp.Scheme + f.CustomerId = temp.CustomerId + f.PaymentProfileId = temp.PaymentProfileId + f.SubscriptionIds = temp.SubscriptionIds + f.PrimarySubscriptionId = temp.PrimarySubscriptionId + if temp.NextAssessmentAt != nil { + NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) + if err != nil { + log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) + } + f.NextAssessmentAt = &NextAssessmentAtVal + } + f.State = temp.State + f.CancelAtEndOfPeriod = temp.CancelAtEndOfPeriod + f.CurrentBillingAmountInCents = temp.CurrentBillingAmountInCents + f.Customer = temp.Customer + f.AccountBalances = temp.AccountBalances + return nil +} + +// TODO +type fullSubscriptionGroupResponse struct { + Uid *string `json:"uid,omitempty"` + Scheme *int `json:"scheme,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + SubscriptionIds []int `json:"subscription_ids,omitempty"` + PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` + NextAssessmentAt *string `json:"next_assessment_at,omitempty"` + State *SubscriptionState `json:"state,omitempty"` + CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` + CurrentBillingAmountInCents *int64 `json:"current_billing_amount_in_cents,omitempty"` + Customer *SubscriptionGroupCustomer `json:"customer,omitempty"` + AccountBalances *SubscriptionGroupBalances `json:"account_balances,omitempty"` } diff --git a/models/get_one_time_token_payment_profile.go b/models/get_one_time_token_payment_profile.go index b488ab7a..d424f38c 100644 --- a/models/get_one_time_token_payment_profile.go +++ b/models/get_one_time_token_payment_profile.go @@ -1,132 +1,213 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // GetOneTimeTokenPaymentProfile represents a GetOneTimeTokenPaymentProfile struct. type GetOneTimeTokenPaymentProfile struct { - Id Optional[string] `json:"id"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - MaskedCardNumber string `json:"masked_card_number"` - // The type of card used. - CardType CardType `json:"card_type"` - ExpirationMonth float64 `json:"expiration_month"` - ExpirationYear float64 `json:"expiration_year"` - CustomerId Optional[string] `json:"customer_id"` - // The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. - CurrentVault CurrentVault `json:"current_vault"` - VaultToken string `json:"vault_token"` - BillingAddress string `json:"billing_address"` - BillingAddress2 *string `json:"billing_address_2,omitempty"` - BillingCity string `json:"billing_city"` - BillingCountry string `json:"billing_country"` - BillingState string `json:"billing_state"` - BillingZip string `json:"billing_zip"` - PaymentType string `json:"payment_type"` - Disabled bool `json:"disabled"` - SiteGatewaySettingId int `json:"site_gateway_setting_id"` - CustomerVaultToken Optional[string] `json:"customer_vault_token"` - GatewayHandle Optional[string] `json:"gateway_handle"` + Id Optional[string] `json:"id"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + MaskedCardNumber string `json:"masked_card_number"` + // The type of card used. + CardType CardType `json:"card_type"` + ExpirationMonth float64 `json:"expiration_month"` + ExpirationYear float64 `json:"expiration_year"` + CustomerId Optional[string] `json:"customer_id"` + // The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. + CurrentVault CurrentVault `json:"current_vault"` + VaultToken string `json:"vault_token"` + BillingAddress string `json:"billing_address"` + BillingAddress2 *string `json:"billing_address_2,omitempty"` + BillingCity string `json:"billing_city"` + BillingCountry string `json:"billing_country"` + BillingState string `json:"billing_state"` + BillingZip string `json:"billing_zip"` + PaymentType string `json:"payment_type"` + Disabled bool `json:"disabled"` + SiteGatewaySettingId int `json:"site_gateway_setting_id"` + CustomerVaultToken Optional[string] `json:"customer_vault_token"` + GatewayHandle Optional[string] `json:"gateway_handle"` } -// MarshalJSON implements the json.Marshaler interface for GetOneTimeTokenPaymentProfile. +// MarshalJSON implements the json.Marshaler interface for GetOneTimeTokenPaymentProfile. // It customizes the JSON marshaling process for GetOneTimeTokenPaymentProfile objects. func (g *GetOneTimeTokenPaymentProfile) MarshalJSON() ( - []byte, - error) { - return json.Marshal(g.toMap()) + []byte, + error) { + return json.Marshal(g.toMap()) } // toMap converts the GetOneTimeTokenPaymentProfile object to a map representation for JSON marshaling. func (g *GetOneTimeTokenPaymentProfile) toMap() map[string]any { - structMap := make(map[string]any) - if g.Id.IsValueSet() { - structMap["id"] = g.Id.Value() - } - structMap["first_name"] = g.FirstName - structMap["last_name"] = g.LastName - structMap["masked_card_number"] = g.MaskedCardNumber - structMap["card_type"] = g.CardType - structMap["expiration_month"] = g.ExpirationMonth - structMap["expiration_year"] = g.ExpirationYear - if g.CustomerId.IsValueSet() { - structMap["customer_id"] = g.CustomerId.Value() - } - structMap["current_vault"] = g.CurrentVault - structMap["vault_token"] = g.VaultToken - structMap["billing_address"] = g.BillingAddress - if g.BillingAddress2 != nil { - structMap["billing_address_2"] = g.BillingAddress2 - } - structMap["billing_city"] = g.BillingCity - structMap["billing_country"] = g.BillingCountry - structMap["billing_state"] = g.BillingState - structMap["billing_zip"] = g.BillingZip - structMap["payment_type"] = g.PaymentType - structMap["disabled"] = g.Disabled - structMap["site_gateway_setting_id"] = g.SiteGatewaySettingId - if g.CustomerVaultToken.IsValueSet() { - structMap["customer_vault_token"] = g.CustomerVaultToken.Value() - } - if g.GatewayHandle.IsValueSet() { - structMap["gateway_handle"] = g.GatewayHandle.Value() - } - return structMap + structMap := make(map[string]any) + if g.Id.IsValueSet() { + if g.Id.Value() != nil { + structMap["id"] = g.Id.Value() + } else { + structMap["id"] = nil + } + } + structMap["first_name"] = g.FirstName + structMap["last_name"] = g.LastName + structMap["masked_card_number"] = g.MaskedCardNumber + structMap["card_type"] = g.CardType + structMap["expiration_month"] = g.ExpirationMonth + structMap["expiration_year"] = g.ExpirationYear + if g.CustomerId.IsValueSet() { + if g.CustomerId.Value() != nil { + structMap["customer_id"] = g.CustomerId.Value() + } else { + structMap["customer_id"] = nil + } + } + structMap["current_vault"] = g.CurrentVault + structMap["vault_token"] = g.VaultToken + structMap["billing_address"] = g.BillingAddress + if g.BillingAddress2 != nil { + structMap["billing_address_2"] = g.BillingAddress2 + } + structMap["billing_city"] = g.BillingCity + structMap["billing_country"] = g.BillingCountry + structMap["billing_state"] = g.BillingState + structMap["billing_zip"] = g.BillingZip + structMap["payment_type"] = g.PaymentType + structMap["disabled"] = g.Disabled + structMap["site_gateway_setting_id"] = g.SiteGatewaySettingId + if g.CustomerVaultToken.IsValueSet() { + if g.CustomerVaultToken.Value() != nil { + structMap["customer_vault_token"] = g.CustomerVaultToken.Value() + } else { + structMap["customer_vault_token"] = nil + } + } + if g.GatewayHandle.IsValueSet() { + if g.GatewayHandle.Value() != nil { + structMap["gateway_handle"] = g.GatewayHandle.Value() + } else { + structMap["gateway_handle"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for GetOneTimeTokenPaymentProfile. +// UnmarshalJSON implements the json.Unmarshaler interface for GetOneTimeTokenPaymentProfile. // It customizes the JSON unmarshaling process for GetOneTimeTokenPaymentProfile objects. func (g *GetOneTimeTokenPaymentProfile) UnmarshalJSON(input []byte) error { - temp := &struct { - Id Optional[string] `json:"id"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - MaskedCardNumber string `json:"masked_card_number"` - CardType CardType `json:"card_type"` - ExpirationMonth float64 `json:"expiration_month"` - ExpirationYear float64 `json:"expiration_year"` - CustomerId Optional[string] `json:"customer_id"` - CurrentVault CurrentVault `json:"current_vault"` - VaultToken string `json:"vault_token"` - BillingAddress string `json:"billing_address"` - BillingAddress2 *string `json:"billing_address_2,omitempty"` - BillingCity string `json:"billing_city"` - BillingCountry string `json:"billing_country"` - BillingState string `json:"billing_state"` - BillingZip string `json:"billing_zip"` - PaymentType string `json:"payment_type"` - Disabled bool `json:"disabled"` - SiteGatewaySettingId int `json:"site_gateway_setting_id"` - CustomerVaultToken Optional[string] `json:"customer_vault_token"` - GatewayHandle Optional[string] `json:"gateway_handle"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - g.Id = temp.Id - g.FirstName = temp.FirstName - g.LastName = temp.LastName - g.MaskedCardNumber = temp.MaskedCardNumber - g.CardType = temp.CardType - g.ExpirationMonth = temp.ExpirationMonth - g.ExpirationYear = temp.ExpirationYear - g.CustomerId = temp.CustomerId - g.CurrentVault = temp.CurrentVault - g.VaultToken = temp.VaultToken - g.BillingAddress = temp.BillingAddress - g.BillingAddress2 = temp.BillingAddress2 - g.BillingCity = temp.BillingCity - g.BillingCountry = temp.BillingCountry - g.BillingState = temp.BillingState - g.BillingZip = temp.BillingZip - g.PaymentType = temp.PaymentType - g.Disabled = temp.Disabled - g.SiteGatewaySettingId = temp.SiteGatewaySettingId - g.CustomerVaultToken = temp.CustomerVaultToken - g.GatewayHandle = temp.GatewayHandle - return nil + var temp getOneTimeTokenPaymentProfile + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + g.Id = temp.Id + g.FirstName = *temp.FirstName + g.LastName = *temp.LastName + g.MaskedCardNumber = *temp.MaskedCardNumber + g.CardType = *temp.CardType + g.ExpirationMonth = *temp.ExpirationMonth + g.ExpirationYear = *temp.ExpirationYear + g.CustomerId = temp.CustomerId + g.CurrentVault = *temp.CurrentVault + g.VaultToken = *temp.VaultToken + g.BillingAddress = *temp.BillingAddress + g.BillingAddress2 = temp.BillingAddress2 + g.BillingCity = *temp.BillingCity + g.BillingCountry = *temp.BillingCountry + g.BillingState = *temp.BillingState + g.BillingZip = *temp.BillingZip + g.PaymentType = *temp.PaymentType + g.Disabled = *temp.Disabled + g.SiteGatewaySettingId = *temp.SiteGatewaySettingId + g.CustomerVaultToken = temp.CustomerVaultToken + g.GatewayHandle = temp.GatewayHandle + return nil +} + +// TODO +type getOneTimeTokenPaymentProfile struct { + Id Optional[string] `json:"id"` + FirstName *string `json:"first_name"` + LastName *string `json:"last_name"` + MaskedCardNumber *string `json:"masked_card_number"` + CardType *CardType `json:"card_type"` + ExpirationMonth *float64 `json:"expiration_month"` + ExpirationYear *float64 `json:"expiration_year"` + CustomerId Optional[string] `json:"customer_id"` + CurrentVault *CurrentVault `json:"current_vault"` + VaultToken *string `json:"vault_token"` + BillingAddress *string `json:"billing_address"` + BillingAddress2 *string `json:"billing_address_2,omitempty"` + BillingCity *string `json:"billing_city"` + BillingCountry *string `json:"billing_country"` + BillingState *string `json:"billing_state"` + BillingZip *string `json:"billing_zip"` + PaymentType *string `json:"payment_type"` + Disabled *bool `json:"disabled"` + SiteGatewaySettingId *int `json:"site_gateway_setting_id"` + CustomerVaultToken Optional[string] `json:"customer_vault_token"` + GatewayHandle Optional[string] `json:"gateway_handle"` +} + +func (g *getOneTimeTokenPaymentProfile) validate() error { + var errs []string + if g.FirstName == nil { + errs = append(errs, "required field `first_name` is missing for type `Get One Time Token Payment Profile`") + } + if g.LastName == nil { + errs = append(errs, "required field `last_name` is missing for type `Get One Time Token Payment Profile`") + } + if g.MaskedCardNumber == nil { + errs = append(errs, "required field `masked_card_number` is missing for type `Get One Time Token Payment Profile`") + } + if g.CardType == nil { + errs = append(errs, "required field `card_type` is missing for type `Get One Time Token Payment Profile`") + } + if g.ExpirationMonth == nil { + errs = append(errs, "required field `expiration_month` is missing for type `Get One Time Token Payment Profile`") + } + if g.ExpirationYear == nil { + errs = append(errs, "required field `expiration_year` is missing for type `Get One Time Token Payment Profile`") + } + if g.CurrentVault == nil { + errs = append(errs, "required field `current_vault` is missing for type `Get One Time Token Payment Profile`") + } + if g.VaultToken == nil { + errs = append(errs, "required field `vault_token` is missing for type `Get One Time Token Payment Profile`") + } + if g.BillingAddress == nil { + errs = append(errs, "required field `billing_address` is missing for type `Get One Time Token Payment Profile`") + } + if g.BillingCity == nil { + errs = append(errs, "required field `billing_city` is missing for type `Get One Time Token Payment Profile`") + } + if g.BillingCountry == nil { + errs = append(errs, "required field `billing_country` is missing for type `Get One Time Token Payment Profile`") + } + if g.BillingState == nil { + errs = append(errs, "required field `billing_state` is missing for type `Get One Time Token Payment Profile`") + } + if g.BillingZip == nil { + errs = append(errs, "required field `billing_zip` is missing for type `Get One Time Token Payment Profile`") + } + if g.PaymentType == nil { + errs = append(errs, "required field `payment_type` is missing for type `Get One Time Token Payment Profile`") + } + if g.Disabled == nil { + errs = append(errs, "required field `disabled` is missing for type `Get One Time Token Payment Profile`") + } + if g.SiteGatewaySettingId == nil { + errs = append(errs, "required field `site_gateway_setting_id` is missing for type `Get One Time Token Payment Profile`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/get_one_time_token_request.go b/models/get_one_time_token_request.go index 4d9339d4..9efaaaa4 100644 --- a/models/get_one_time_token_request.go +++ b/models/get_one_time_token_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // GetOneTimeTokenRequest represents a GetOneTimeTokenRequest struct. type GetOneTimeTokenRequest struct { - PaymentProfile GetOneTimeTokenPaymentProfile `json:"payment_profile"` + PaymentProfile GetOneTimeTokenPaymentProfile `json:"payment_profile"` } -// MarshalJSON implements the json.Marshaler interface for GetOneTimeTokenRequest. +// MarshalJSON implements the json.Marshaler interface for GetOneTimeTokenRequest. // It customizes the JSON marshaling process for GetOneTimeTokenRequest objects. func (g *GetOneTimeTokenRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(g.toMap()) + []byte, + error) { + return json.Marshal(g.toMap()) } // toMap converts the GetOneTimeTokenRequest object to a map representation for JSON marshaling. func (g *GetOneTimeTokenRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["payment_profile"] = g.PaymentProfile.toMap() - return structMap + structMap := make(map[string]any) + structMap["payment_profile"] = g.PaymentProfile.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for GetOneTimeTokenRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for GetOneTimeTokenRequest. // It customizes the JSON unmarshaling process for GetOneTimeTokenRequest objects. func (g *GetOneTimeTokenRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - PaymentProfile GetOneTimeTokenPaymentProfile `json:"payment_profile"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - g.PaymentProfile = temp.PaymentProfile - return nil + var temp getOneTimeTokenRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + g.PaymentProfile = *temp.PaymentProfile + return nil +} + +// TODO +type getOneTimeTokenRequest struct { + PaymentProfile *GetOneTimeTokenPaymentProfile `json:"payment_profile"` +} + +func (g *getOneTimeTokenRequest) validate() error { + var errs []string + if g.PaymentProfile == nil { + errs = append(errs, "required field `payment_profile` is missing for type `Get One Time Token Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/group_billing.go b/models/group_billing.go index c8e5bdac..7e85fd8c 100644 --- a/models/group_billing.go +++ b/models/group_billing.go @@ -1,58 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" ) -// GroupBilling represents a GroupBilling struct. +// GroupBilling represents a GroupBilling struct. // Optional attributes related to billing date and accrual. Note: Only applicable for new subscriptions. type GroupBilling struct { - // A flag indicating whether or not to accrue charges on the new subscription. - Accrue *bool `json:"accrue,omitempty"` - // A flag indicating whether or not to align the billing date of the new subscription with the billing date of the primary subscription of the hierarchy's default subscription group. Required to be true if prorate is also true. - AlignDate *bool `json:"align_date,omitempty"` - // A flag indicating whether or not to prorate billing of the new subscription for the current period. A value of true is ignored unless align_date is also true. - Prorate *bool `json:"prorate,omitempty"` + // A flag indicating whether or not to accrue charges on the new subscription. + Accrue *bool `json:"accrue,omitempty"` + // A flag indicating whether or not to align the billing date of the new subscription with the billing date of the primary subscription of the hierarchy's default subscription group. Required to be true if prorate is also true. + AlignDate *bool `json:"align_date,omitempty"` + // A flag indicating whether or not to prorate billing of the new subscription for the current period. A value of true is ignored unless align_date is also true. + Prorate *bool `json:"prorate,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for GroupBilling. +// MarshalJSON implements the json.Marshaler interface for GroupBilling. // It customizes the JSON marshaling process for GroupBilling objects. func (g *GroupBilling) MarshalJSON() ( - []byte, - error) { - return json.Marshal(g.toMap()) + []byte, + error) { + return json.Marshal(g.toMap()) } // toMap converts the GroupBilling object to a map representation for JSON marshaling. func (g *GroupBilling) toMap() map[string]any { - structMap := make(map[string]any) - if g.Accrue != nil { - structMap["accrue"] = g.Accrue - } - if g.AlignDate != nil { - structMap["align_date"] = g.AlignDate - } - if g.Prorate != nil { - structMap["prorate"] = g.Prorate - } - return structMap + structMap := make(map[string]any) + if g.Accrue != nil { + structMap["accrue"] = g.Accrue + } + if g.AlignDate != nil { + structMap["align_date"] = g.AlignDate + } + if g.Prorate != nil { + structMap["prorate"] = g.Prorate + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for GroupBilling. +// UnmarshalJSON implements the json.Unmarshaler interface for GroupBilling. // It customizes the JSON unmarshaling process for GroupBilling objects. func (g *GroupBilling) UnmarshalJSON(input []byte) error { - temp := &struct { - Accrue *bool `json:"accrue,omitempty"` - AlignDate *bool `json:"align_date,omitempty"` - Prorate *bool `json:"prorate,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - g.Accrue = temp.Accrue - g.AlignDate = temp.AlignDate - g.Prorate = temp.Prorate - return nil + var temp groupBilling + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + g.Accrue = temp.Accrue + g.AlignDate = temp.AlignDate + g.Prorate = temp.Prorate + return nil +} + +// TODO +type groupBilling struct { + Accrue *bool `json:"accrue,omitempty"` + AlignDate *bool `json:"align_date,omitempty"` + Prorate *bool `json:"prorate,omitempty"` } diff --git a/models/group_settings.go b/models/group_settings.go index d21cf0b2..b3311c69 100644 --- a/models/group_settings.go +++ b/models/group_settings.go @@ -1,48 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // GroupSettings represents a GroupSettings struct. type GroupSettings struct { - // Attributes of the target customer who will be the responsible payer of the created subscription. Required. - Target GroupTarget `json:"target"` - // Optional attributes related to billing date and accrual. Note: Only applicable for new subscriptions. - Billing *GroupBilling `json:"billing,omitempty"` + // Attributes of the target customer who will be the responsible payer of the created subscription. Required. + Target GroupTarget `json:"target"` + // Optional attributes related to billing date and accrual. Note: Only applicable for new subscriptions. + Billing *GroupBilling `json:"billing,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for GroupSettings. +// MarshalJSON implements the json.Marshaler interface for GroupSettings. // It customizes the JSON marshaling process for GroupSettings objects. func (g *GroupSettings) MarshalJSON() ( - []byte, - error) { - return json.Marshal(g.toMap()) + []byte, + error) { + return json.Marshal(g.toMap()) } // toMap converts the GroupSettings object to a map representation for JSON marshaling. func (g *GroupSettings) toMap() map[string]any { - structMap := make(map[string]any) - structMap["target"] = g.Target.toMap() - if g.Billing != nil { - structMap["billing"] = g.Billing.toMap() - } - return structMap + structMap := make(map[string]any) + structMap["target"] = g.Target.toMap() + if g.Billing != nil { + structMap["billing"] = g.Billing.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for GroupSettings. +// UnmarshalJSON implements the json.Unmarshaler interface for GroupSettings. // It customizes the JSON unmarshaling process for GroupSettings objects. func (g *GroupSettings) UnmarshalJSON(input []byte) error { - temp := &struct { - Target GroupTarget `json:"target"` - Billing *GroupBilling `json:"billing,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - g.Target = temp.Target - g.Billing = temp.Billing - return nil + var temp groupSettings + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + g.Target = *temp.Target + g.Billing = temp.Billing + return nil +} + +// TODO +type groupSettings struct { + Target *GroupTarget `json:"target"` + Billing *GroupBilling `json:"billing,omitempty"` +} + +func (g *groupSettings) validate() error { + var errs []string + if g.Target == nil { + errs = append(errs, "required field `target` is missing for type `Group Settings`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/group_target.go b/models/group_target.go index 00735fa5..da4fd8fd 100644 --- a/models/group_target.go +++ b/models/group_target.go @@ -1,49 +1,69 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) -// GroupTarget represents a GroupTarget struct. +// GroupTarget represents a GroupTarget struct. // Attributes of the target customer who will be the responsible payer of the created subscription. Required. type GroupTarget struct { - // The type of object indicated by the id attribute. - Type GroupTargetType `json:"type"` - // The id of the target customer or subscription to group the existing subscription with. Ignored and should not be included if type is "self" , "parent", or "eldest" - Id *int `json:"id,omitempty"` + // The type of object indicated by the id attribute. + Type GroupTargetType `json:"type"` + // The id of the target customer or subscription to group the existing subscription with. Ignored and should not be included if type is "self" , "parent", or "eldest" + Id *int `json:"id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for GroupTarget. +// MarshalJSON implements the json.Marshaler interface for GroupTarget. // It customizes the JSON marshaling process for GroupTarget objects. func (g *GroupTarget) MarshalJSON() ( - []byte, - error) { - return json.Marshal(g.toMap()) + []byte, + error) { + return json.Marshal(g.toMap()) } // toMap converts the GroupTarget object to a map representation for JSON marshaling. func (g *GroupTarget) toMap() map[string]any { - structMap := make(map[string]any) - structMap["type"] = g.Type - if g.Id != nil { - structMap["id"] = g.Id - } - return structMap + structMap := make(map[string]any) + structMap["type"] = g.Type + if g.Id != nil { + structMap["id"] = g.Id + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for GroupTarget. +// UnmarshalJSON implements the json.Unmarshaler interface for GroupTarget. // It customizes the JSON unmarshaling process for GroupTarget objects. func (g *GroupTarget) UnmarshalJSON(input []byte) error { - temp := &struct { - Type GroupTargetType `json:"type"` - Id *int `json:"id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - g.Type = temp.Type - g.Id = temp.Id - return nil + var temp groupTarget + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + g.Type = *temp.Type + g.Id = temp.Id + return nil +} + +// TODO +type groupTarget struct { + Type *GroupTargetType `json:"type"` + Id *int `json:"id,omitempty"` +} + +func (g *groupTarget) validate() error { + var errs []string + if g.Type == nil { + errs = append(errs, "required field `type` is missing for type `Group Target`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/invoice.go b/models/invoice.go index dc826aae..0bf9b751 100644 --- a/models/invoice.go +++ b/models/invoice.go @@ -1,436 +1,462 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Invoice represents a Invoice struct. type Invoice struct { - Id *int64 `json:"id,omitempty"` - // Unique identifier for the invoice. It is generated automatically by Chargify and has the prefix "inv_" followed by alphanumeric characters. - Uid *string `json:"uid,omitempty"` - // ID of the site to which the invoice belongs. - SiteId *int `json:"site_id,omitempty"` - // ID of the customer to which the invoice belongs. - CustomerId *int `json:"customer_id,omitempty"` - // ID of the subscription that generated the invoice. - SubscriptionId *int `json:"subscription_id,omitempty"` - // A unique, identifying string that appears on the invoice and in places the invoice is referenced. - // While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. - Number *string `json:"number,omitempty"` - // A monotonically increasing number assigned to invoices as they are created. This number is unique within a site and can be used to sort and order invoices. - SequenceNumber *int `json:"sequence_number,omitempty"` - TransactionTime *time.Time `json:"transaction_time,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - // Date the invoice was issued to the customer. This is the date that the invoice was made available for payment. - // The format is `"YYYY-MM-DD"`. - IssueDate *time.Time `json:"issue_date,omitempty"` - // Date the invoice is due. - // The format is `"YYYY-MM-DD"`. - DueDate *time.Time `json:"due_date,omitempty"` - // Date the invoice became fully paid. - // If partial payments are applied to the invoice, this date will not be present until payment has been made in full. - // The format is `"YYYY-MM-DD"`. - PaidDate Optional[time.Time] `json:"paid_date"` - // The current status of the invoice. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. - Status *InvoiceStatus `json:"status,omitempty"` - Role *InvoiceRole `json:"role,omitempty"` - ParentInvoiceId Optional[int] `json:"parent_invoice_id"` - // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. - CollectionMethod *CollectionMethod `json:"collection_method,omitempty"` - // A message that is printed on the invoice when it is marked for remittance collection. It is intended to describe to the customer how they may make payment, and is configured by the merchant. - PaymentInstructions *string `json:"payment_instructions,omitempty"` - // The ISO 4217 currency code (3 character string) representing the currency of invoice transaction. - Currency *string `json:"currency,omitempty"` - // Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values: - // * "none": A normal invoice with no consolidation. - // * "child": An invoice segment which has been combined into a consolidated invoice. - // * "parent": A consolidated invoice, whose contents are composed of invoice segments. - // "Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments. - // See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). - ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` - // For invoices with `consolidation_level` of `child`, this specifies the UID of the parent (consolidated) invoice. - ParentInvoiceUid Optional[string] `json:"parent_invoice_uid"` - SubscriptionGroupId Optional[int] `json:"subscription_group_id"` - // For invoices with `consolidation_level` of `child`, this specifies the number of the parent (consolidated) invoice. - ParentInvoiceNumber Optional[int] `json:"parent_invoice_number"` - // For invoices with `consolidation_level` of `parent`, this specifies the ID of the subscription which was the primary subscription of the subscription group that generated the invoice. - GroupPrimarySubscriptionId Optional[int] `json:"group_primary_subscription_id"` - // The name of the product subscribed when the invoice was generated. - ProductName *string `json:"product_name,omitempty"` - // The name of the product family subscribed when the invoice was generated. - ProductFamilyName *string `json:"product_family_name,omitempty"` - // Information about the seller (merchant) listed on the masthead of the invoice. - Seller *InvoiceSeller `json:"seller,omitempty"` - // Information about the customer who is owner or recipient the invoiced subscription. - Customer *InvoiceCustomer `json:"customer,omitempty"` - Payer *InvoicePayer `json:"payer,omitempty"` - RecipientEmails []string `json:"recipient_emails,omitempty"` - NetTerms *int `json:"net_terms,omitempty"` - // The memo printed on invoices of any collection type. This message is in control of the merchant. - Memo *string `json:"memo,omitempty"` - // The invoice billing address. - BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` - // The invoice shipping address. - ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` - // Subtotal of the invoice, which is the sum of all line items before discounts or taxes. - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - // Total discount applied to the invoice. - DiscountAmount *string `json:"discount_amount,omitempty"` - // Total tax on the invoice. - TaxAmount *string `json:"tax_amount,omitempty"` - // The invoice total, which is `subtotal_amount - discount_amount + tax_amount`.' - TotalAmount *string `json:"total_amount,omitempty"` - // The amount of credit (from credit notes) applied to this invoice. - // Credits offset the amount due from the customer. - CreditAmount *string `json:"credit_amount,omitempty"` - RefundAmount *string `json:"refund_amount,omitempty"` - // The amount paid on the invoice by the customer. - PaidAmount *string `json:"paid_amount,omitempty"` - // Amount due on the invoice, which is `total_amount - credit_amount - paid_amount`. - DueAmount *string `json:"due_amount,omitempty"` - // Line items on the invoice. - LineItems []InvoiceLineItem `json:"line_items,omitempty"` - Discounts []InvoiceDiscount `json:"discounts,omitempty"` - Taxes []InvoiceTax `json:"taxes,omitempty"` - Credits []InvoiceCredit `json:"credits,omitempty"` - Refunds []InvoiceRefund `json:"refunds,omitempty"` - Payments []InvoicePayment `json:"payments,omitempty"` - CustomFields []InvoiceCustomField `json:"custom_fields,omitempty"` - DisplaySettings *InvoiceDisplaySettings `json:"display_settings,omitempty"` - // The public URL of the invoice - PublicUrl *string `json:"public_url,omitempty"` - PreviousBalanceData *InvoicePreviousBalance `json:"previous_balance_data,omitempty"` + Id *int64 `json:"id,omitempty"` + // Unique identifier for the invoice. It is generated automatically by Chargify and has the prefix "inv_" followed by alphanumeric characters. + Uid *string `json:"uid,omitempty"` + // ID of the site to which the invoice belongs. + SiteId *int `json:"site_id,omitempty"` + // ID of the customer to which the invoice belongs. + CustomerId *int `json:"customer_id,omitempty"` + // ID of the subscription that generated the invoice. + SubscriptionId *int `json:"subscription_id,omitempty"` + // A unique, identifying string that appears on the invoice and in places the invoice is referenced. + // While the UID is long and not appropriate to show to customers, the number is usually shorter and consumable by the customer and the merchant alike. + Number *string `json:"number,omitempty"` + // A monotonically increasing number assigned to invoices as they are created. This number is unique within a site and can be used to sort and order invoices. + SequenceNumber *int `json:"sequence_number,omitempty"` + TransactionTime *time.Time `json:"transaction_time,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + // Date the invoice was issued to the customer. This is the date that the invoice was made available for payment. + // The format is `"YYYY-MM-DD"`. + IssueDate *time.Time `json:"issue_date,omitempty"` + // Date the invoice is due. + // The format is `"YYYY-MM-DD"`. + DueDate *time.Time `json:"due_date,omitempty"` + // Date the invoice became fully paid. + // If partial payments are applied to the invoice, this date will not be present until payment has been made in full. + // The format is `"YYYY-MM-DD"`. + PaidDate Optional[time.Time] `json:"paid_date"` + // The current status of the invoice. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. + Status *InvoiceStatus `json:"status,omitempty"` + Role *InvoiceRole `json:"role,omitempty"` + ParentInvoiceId Optional[int] `json:"parent_invoice_id"` + // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. + CollectionMethod *CollectionMethod `json:"collection_method,omitempty"` + // A message that is printed on the invoice when it is marked for remittance collection. It is intended to describe to the customer how they may make payment, and is configured by the merchant. + PaymentInstructions *string `json:"payment_instructions,omitempty"` + // The ISO 4217 currency code (3 character string) representing the currency of invoice transaction. + Currency *string `json:"currency,omitempty"` + // Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values: + // * "none": A normal invoice with no consolidation. + // * "child": An invoice segment which has been combined into a consolidated invoice. + // * "parent": A consolidated invoice, whose contents are composed of invoice segments. + // "Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments. + // See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). + ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` + // For invoices with `consolidation_level` of `child`, this specifies the UID of the parent (consolidated) invoice. + ParentInvoiceUid Optional[string] `json:"parent_invoice_uid"` + SubscriptionGroupId Optional[int] `json:"subscription_group_id"` + // For invoices with `consolidation_level` of `child`, this specifies the number of the parent (consolidated) invoice. + ParentInvoiceNumber Optional[int] `json:"parent_invoice_number"` + // For invoices with `consolidation_level` of `parent`, this specifies the ID of the subscription which was the primary subscription of the subscription group that generated the invoice. + GroupPrimarySubscriptionId Optional[int] `json:"group_primary_subscription_id"` + // The name of the product subscribed when the invoice was generated. + ProductName *string `json:"product_name,omitempty"` + // The name of the product family subscribed when the invoice was generated. + ProductFamilyName *string `json:"product_family_name,omitempty"` + // Information about the seller (merchant) listed on the masthead of the invoice. + Seller *InvoiceSeller `json:"seller,omitempty"` + // Information about the customer who is owner or recipient the invoiced subscription. + Customer *InvoiceCustomer `json:"customer,omitempty"` + Payer *InvoicePayer `json:"payer,omitempty"` + RecipientEmails []string `json:"recipient_emails,omitempty"` + NetTerms *int `json:"net_terms,omitempty"` + // The memo printed on invoices of any collection type. This message is in control of the merchant. + Memo *string `json:"memo,omitempty"` + // The invoice billing address. + BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` + // The invoice shipping address. + ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` + // Subtotal of the invoice, which is the sum of all line items before discounts or taxes. + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + // Total discount applied to the invoice. + DiscountAmount *string `json:"discount_amount,omitempty"` + // Total tax on the invoice. + TaxAmount *string `json:"tax_amount,omitempty"` + // The invoice total, which is `subtotal_amount - discount_amount + tax_amount`.' + TotalAmount *string `json:"total_amount,omitempty"` + // The amount of credit (from credit notes) applied to this invoice. + // Credits offset the amount due from the customer. + CreditAmount *string `json:"credit_amount,omitempty"` + RefundAmount *string `json:"refund_amount,omitempty"` + // The amount paid on the invoice by the customer. + PaidAmount *string `json:"paid_amount,omitempty"` + // Amount due on the invoice, which is `total_amount - credit_amount - paid_amount`. + DueAmount *string `json:"due_amount,omitempty"` + // Line items on the invoice. + LineItems []InvoiceLineItem `json:"line_items,omitempty"` + Discounts []InvoiceDiscount `json:"discounts,omitempty"` + Taxes []InvoiceTax `json:"taxes,omitempty"` + Credits []InvoiceCredit `json:"credits,omitempty"` + Refunds []InvoiceRefund `json:"refunds,omitempty"` + Payments []InvoicePayment `json:"payments,omitempty"` + CustomFields []InvoiceCustomField `json:"custom_fields,omitempty"` + DisplaySettings *InvoiceDisplaySettings `json:"display_settings,omitempty"` + // The public URL of the invoice + PublicUrl *string `json:"public_url,omitempty"` + PreviousBalanceData *InvoicePreviousBalance `json:"previous_balance_data,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Invoice. +// MarshalJSON implements the json.Marshaler interface for Invoice. // It customizes the JSON marshaling process for Invoice objects. func (i *Invoice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the Invoice object to a map representation for JSON marshaling. func (i *Invoice) toMap() map[string]any { - structMap := make(map[string]any) - if i.Id != nil { - structMap["id"] = i.Id - } - if i.Uid != nil { - structMap["uid"] = i.Uid - } - if i.SiteId != nil { - structMap["site_id"] = i.SiteId - } - if i.CustomerId != nil { - structMap["customer_id"] = i.CustomerId - } - if i.SubscriptionId != nil { - structMap["subscription_id"] = i.SubscriptionId - } - if i.Number != nil { - structMap["number"] = i.Number - } - if i.SequenceNumber != nil { - structMap["sequence_number"] = i.SequenceNumber - } - if i.TransactionTime != nil { - structMap["transaction_time"] = i.TransactionTime.Format(time.RFC3339) - } - if i.CreatedAt != nil { - structMap["created_at"] = i.CreatedAt.Format(time.RFC3339) - } - if i.UpdatedAt != nil { - structMap["updated_at"] = i.UpdatedAt.Format(time.RFC3339) - } - if i.IssueDate != nil { - structMap["issue_date"] = i.IssueDate.Format(DEFAULT_DATE) - } - if i.DueDate != nil { - structMap["due_date"] = i.DueDate.Format(DEFAULT_DATE) - } - if i.PaidDate.IsValueSet() { - var PaidDateVal *string = nil - if i.PaidDate.Value() != nil { - val := i.PaidDate.Value().Format(DEFAULT_DATE) - PaidDateVal = &val - } - structMap["paid_date"] = PaidDateVal - } - if i.Status != nil { - structMap["status"] = i.Status - } - if i.Role != nil { - structMap["role"] = i.Role - } - if i.ParentInvoiceId.IsValueSet() { - structMap["parent_invoice_id"] = i.ParentInvoiceId.Value() - } - if i.CollectionMethod != nil { - structMap["collection_method"] = i.CollectionMethod - } - if i.PaymentInstructions != nil { - structMap["payment_instructions"] = i.PaymentInstructions - } - if i.Currency != nil { - structMap["currency"] = i.Currency - } - if i.ConsolidationLevel != nil { - structMap["consolidation_level"] = i.ConsolidationLevel - } - if i.ParentInvoiceUid.IsValueSet() { - structMap["parent_invoice_uid"] = i.ParentInvoiceUid.Value() - } - if i.SubscriptionGroupId.IsValueSet() { - structMap["subscription_group_id"] = i.SubscriptionGroupId.Value() - } - if i.ParentInvoiceNumber.IsValueSet() { - structMap["parent_invoice_number"] = i.ParentInvoiceNumber.Value() - } - if i.GroupPrimarySubscriptionId.IsValueSet() { - structMap["group_primary_subscription_id"] = i.GroupPrimarySubscriptionId.Value() - } - if i.ProductName != nil { - structMap["product_name"] = i.ProductName - } - if i.ProductFamilyName != nil { - structMap["product_family_name"] = i.ProductFamilyName - } - if i.Seller != nil { - structMap["seller"] = i.Seller.toMap() - } - if i.Customer != nil { - structMap["customer"] = i.Customer.toMap() - } - if i.Payer != nil { - structMap["payer"] = i.Payer.toMap() - } - if i.RecipientEmails != nil { - structMap["recipient_emails"] = i.RecipientEmails - } - if i.NetTerms != nil { - structMap["net_terms"] = i.NetTerms - } - if i.Memo != nil { - structMap["memo"] = i.Memo - } - if i.BillingAddress != nil { - structMap["billing_address"] = i.BillingAddress.toMap() - } - if i.ShippingAddress != nil { - structMap["shipping_address"] = i.ShippingAddress.toMap() - } - if i.SubtotalAmount != nil { - structMap["subtotal_amount"] = i.SubtotalAmount - } - if i.DiscountAmount != nil { - structMap["discount_amount"] = i.DiscountAmount - } - if i.TaxAmount != nil { - structMap["tax_amount"] = i.TaxAmount - } - if i.TotalAmount != nil { - structMap["total_amount"] = i.TotalAmount - } - if i.CreditAmount != nil { - structMap["credit_amount"] = i.CreditAmount - } - if i.RefundAmount != nil { - structMap["refund_amount"] = i.RefundAmount - } - if i.PaidAmount != nil { - structMap["paid_amount"] = i.PaidAmount - } - if i.DueAmount != nil { - structMap["due_amount"] = i.DueAmount - } - if i.LineItems != nil { - structMap["line_items"] = i.LineItems - } - if i.Discounts != nil { - structMap["discounts"] = i.Discounts - } - if i.Taxes != nil { - structMap["taxes"] = i.Taxes - } - if i.Credits != nil { - structMap["credits"] = i.Credits - } - if i.Refunds != nil { - structMap["refunds"] = i.Refunds - } - if i.Payments != nil { - structMap["payments"] = i.Payments - } - if i.CustomFields != nil { - structMap["custom_fields"] = i.CustomFields - } - if i.DisplaySettings != nil { - structMap["display_settings"] = i.DisplaySettings.toMap() - } - if i.PublicUrl != nil { - structMap["public_url"] = i.PublicUrl - } - if i.PreviousBalanceData != nil { - structMap["previous_balance_data"] = i.PreviousBalanceData.toMap() - } - return structMap + structMap := make(map[string]any) + if i.Id != nil { + structMap["id"] = i.Id + } + if i.Uid != nil { + structMap["uid"] = i.Uid + } + if i.SiteId != nil { + structMap["site_id"] = i.SiteId + } + if i.CustomerId != nil { + structMap["customer_id"] = i.CustomerId + } + if i.SubscriptionId != nil { + structMap["subscription_id"] = i.SubscriptionId + } + if i.Number != nil { + structMap["number"] = i.Number + } + if i.SequenceNumber != nil { + structMap["sequence_number"] = i.SequenceNumber + } + if i.TransactionTime != nil { + structMap["transaction_time"] = i.TransactionTime.Format(time.RFC3339) + } + if i.CreatedAt != nil { + structMap["created_at"] = i.CreatedAt.Format(time.RFC3339) + } + if i.UpdatedAt != nil { + structMap["updated_at"] = i.UpdatedAt.Format(time.RFC3339) + } + if i.IssueDate != nil { + structMap["issue_date"] = i.IssueDate.Format(DEFAULT_DATE) + } + if i.DueDate != nil { + structMap["due_date"] = i.DueDate.Format(DEFAULT_DATE) + } + if i.PaidDate.IsValueSet() { + var PaidDateVal *string = nil + if i.PaidDate.Value() != nil { + val := i.PaidDate.Value().Format(DEFAULT_DATE) + PaidDateVal = &val + } + if i.PaidDate.Value() != nil { + structMap["paid_date"] = PaidDateVal + } else { + structMap["paid_date"] = nil + } + } + if i.Status != nil { + structMap["status"] = i.Status + } + if i.Role != nil { + structMap["role"] = i.Role + } + if i.ParentInvoiceId.IsValueSet() { + if i.ParentInvoiceId.Value() != nil { + structMap["parent_invoice_id"] = i.ParentInvoiceId.Value() + } else { + structMap["parent_invoice_id"] = nil + } + } + if i.CollectionMethod != nil { + structMap["collection_method"] = i.CollectionMethod + } + if i.PaymentInstructions != nil { + structMap["payment_instructions"] = i.PaymentInstructions + } + if i.Currency != nil { + structMap["currency"] = i.Currency + } + if i.ConsolidationLevel != nil { + structMap["consolidation_level"] = i.ConsolidationLevel + } + if i.ParentInvoiceUid.IsValueSet() { + if i.ParentInvoiceUid.Value() != nil { + structMap["parent_invoice_uid"] = i.ParentInvoiceUid.Value() + } else { + structMap["parent_invoice_uid"] = nil + } + } + if i.SubscriptionGroupId.IsValueSet() { + if i.SubscriptionGroupId.Value() != nil { + structMap["subscription_group_id"] = i.SubscriptionGroupId.Value() + } else { + structMap["subscription_group_id"] = nil + } + } + if i.ParentInvoiceNumber.IsValueSet() { + if i.ParentInvoiceNumber.Value() != nil { + structMap["parent_invoice_number"] = i.ParentInvoiceNumber.Value() + } else { + structMap["parent_invoice_number"] = nil + } + } + if i.GroupPrimarySubscriptionId.IsValueSet() { + if i.GroupPrimarySubscriptionId.Value() != nil { + structMap["group_primary_subscription_id"] = i.GroupPrimarySubscriptionId.Value() + } else { + structMap["group_primary_subscription_id"] = nil + } + } + if i.ProductName != nil { + structMap["product_name"] = i.ProductName + } + if i.ProductFamilyName != nil { + structMap["product_family_name"] = i.ProductFamilyName + } + if i.Seller != nil { + structMap["seller"] = i.Seller.toMap() + } + if i.Customer != nil { + structMap["customer"] = i.Customer.toMap() + } + if i.Payer != nil { + structMap["payer"] = i.Payer.toMap() + } + if i.RecipientEmails != nil { + structMap["recipient_emails"] = i.RecipientEmails + } + if i.NetTerms != nil { + structMap["net_terms"] = i.NetTerms + } + if i.Memo != nil { + structMap["memo"] = i.Memo + } + if i.BillingAddress != nil { + structMap["billing_address"] = i.BillingAddress.toMap() + } + if i.ShippingAddress != nil { + structMap["shipping_address"] = i.ShippingAddress.toMap() + } + if i.SubtotalAmount != nil { + structMap["subtotal_amount"] = i.SubtotalAmount + } + if i.DiscountAmount != nil { + structMap["discount_amount"] = i.DiscountAmount + } + if i.TaxAmount != nil { + structMap["tax_amount"] = i.TaxAmount + } + if i.TotalAmount != nil { + structMap["total_amount"] = i.TotalAmount + } + if i.CreditAmount != nil { + structMap["credit_amount"] = i.CreditAmount + } + if i.RefundAmount != nil { + structMap["refund_amount"] = i.RefundAmount + } + if i.PaidAmount != nil { + structMap["paid_amount"] = i.PaidAmount + } + if i.DueAmount != nil { + structMap["due_amount"] = i.DueAmount + } + if i.LineItems != nil { + structMap["line_items"] = i.LineItems + } + if i.Discounts != nil { + structMap["discounts"] = i.Discounts + } + if i.Taxes != nil { + structMap["taxes"] = i.Taxes + } + if i.Credits != nil { + structMap["credits"] = i.Credits + } + if i.Refunds != nil { + structMap["refunds"] = i.Refunds + } + if i.Payments != nil { + structMap["payments"] = i.Payments + } + if i.CustomFields != nil { + structMap["custom_fields"] = i.CustomFields + } + if i.DisplaySettings != nil { + structMap["display_settings"] = i.DisplaySettings.toMap() + } + if i.PublicUrl != nil { + structMap["public_url"] = i.PublicUrl + } + if i.PreviousBalanceData != nil { + structMap["previous_balance_data"] = i.PreviousBalanceData.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Invoice. +// UnmarshalJSON implements the json.Unmarshaler interface for Invoice. // It customizes the JSON unmarshaling process for Invoice objects. func (i *Invoice) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int64 `json:"id,omitempty"` - Uid *string `json:"uid,omitempty"` - SiteId *int `json:"site_id,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - Number *string `json:"number,omitempty"` - SequenceNumber *int `json:"sequence_number,omitempty"` - TransactionTime *string `json:"transaction_time,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - IssueDate *string `json:"issue_date,omitempty"` - DueDate *string `json:"due_date,omitempty"` - PaidDate Optional[string] `json:"paid_date"` - Status *InvoiceStatus `json:"status,omitempty"` - Role *InvoiceRole `json:"role,omitempty"` - ParentInvoiceId Optional[int] `json:"parent_invoice_id"` - CollectionMethod *CollectionMethod `json:"collection_method,omitempty"` - PaymentInstructions *string `json:"payment_instructions,omitempty"` - Currency *string `json:"currency,omitempty"` - ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` - ParentInvoiceUid Optional[string] `json:"parent_invoice_uid"` - SubscriptionGroupId Optional[int] `json:"subscription_group_id"` - ParentInvoiceNumber Optional[int] `json:"parent_invoice_number"` - GroupPrimarySubscriptionId Optional[int] `json:"group_primary_subscription_id"` - ProductName *string `json:"product_name,omitempty"` - ProductFamilyName *string `json:"product_family_name,omitempty"` - Seller *InvoiceSeller `json:"seller,omitempty"` - Customer *InvoiceCustomer `json:"customer,omitempty"` - Payer *InvoicePayer `json:"payer,omitempty"` - RecipientEmails []string `json:"recipient_emails,omitempty"` - NetTerms *int `json:"net_terms,omitempty"` - Memo *string `json:"memo,omitempty"` - BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` - ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - TotalAmount *string `json:"total_amount,omitempty"` - CreditAmount *string `json:"credit_amount,omitempty"` - RefundAmount *string `json:"refund_amount,omitempty"` - PaidAmount *string `json:"paid_amount,omitempty"` - DueAmount *string `json:"due_amount,omitempty"` - LineItems []InvoiceLineItem `json:"line_items,omitempty"` - Discounts []InvoiceDiscount `json:"discounts,omitempty"` - Taxes []InvoiceTax `json:"taxes,omitempty"` - Credits []InvoiceCredit `json:"credits,omitempty"` - Refunds []InvoiceRefund `json:"refunds,omitempty"` - Payments []InvoicePayment `json:"payments,omitempty"` - CustomFields []InvoiceCustomField `json:"custom_fields,omitempty"` - DisplaySettings *InvoiceDisplaySettings `json:"display_settings,omitempty"` - PublicUrl *string `json:"public_url,omitempty"` - PreviousBalanceData *InvoicePreviousBalance `json:"previous_balance_data,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Id = temp.Id - i.Uid = temp.Uid - i.SiteId = temp.SiteId - i.CustomerId = temp.CustomerId - i.SubscriptionId = temp.SubscriptionId - i.Number = temp.Number - i.SequenceNumber = temp.SequenceNumber - if temp.TransactionTime != nil { - TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) - if err != nil { - log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) - } - i.TransactionTime = &TransactionTimeVal - } - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - i.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - i.UpdatedAt = &UpdatedAtVal - } - if temp.IssueDate != nil { - IssueDateVal, err := time.Parse(DEFAULT_DATE, *temp.IssueDate) - if err != nil { - log.Fatalf("Cannot Parse issue_date as % s format.", DEFAULT_DATE) - } - i.IssueDate = &IssueDateVal - } - if temp.DueDate != nil { - DueDateVal, err := time.Parse(DEFAULT_DATE, *temp.DueDate) - if err != nil { - log.Fatalf("Cannot Parse due_date as % s format.", DEFAULT_DATE) - } - i.DueDate = &DueDateVal - } - i.PaidDate.ShouldSetValue(temp.PaidDate.IsValueSet()) - if temp.PaidDate.Value() != nil { - PaidDateVal, err := time.Parse(DEFAULT_DATE, (*temp.PaidDate.Value())) - if err != nil { - log.Fatalf("Cannot Parse paid_date as % s format.", DEFAULT_DATE) - } - i.PaidDate.SetValue(&PaidDateVal) - } - i.Status = temp.Status - i.Role = temp.Role - i.ParentInvoiceId = temp.ParentInvoiceId - i.CollectionMethod = temp.CollectionMethod - i.PaymentInstructions = temp.PaymentInstructions - i.Currency = temp.Currency - i.ConsolidationLevel = temp.ConsolidationLevel - i.ParentInvoiceUid = temp.ParentInvoiceUid - i.SubscriptionGroupId = temp.SubscriptionGroupId - i.ParentInvoiceNumber = temp.ParentInvoiceNumber - i.GroupPrimarySubscriptionId = temp.GroupPrimarySubscriptionId - i.ProductName = temp.ProductName - i.ProductFamilyName = temp.ProductFamilyName - i.Seller = temp.Seller - i.Customer = temp.Customer - i.Payer = temp.Payer - i.RecipientEmails = temp.RecipientEmails - i.NetTerms = temp.NetTerms - i.Memo = temp.Memo - i.BillingAddress = temp.BillingAddress - i.ShippingAddress = temp.ShippingAddress - i.SubtotalAmount = temp.SubtotalAmount - i.DiscountAmount = temp.DiscountAmount - i.TaxAmount = temp.TaxAmount - i.TotalAmount = temp.TotalAmount - i.CreditAmount = temp.CreditAmount - i.RefundAmount = temp.RefundAmount - i.PaidAmount = temp.PaidAmount - i.DueAmount = temp.DueAmount - i.LineItems = temp.LineItems - i.Discounts = temp.Discounts - i.Taxes = temp.Taxes - i.Credits = temp.Credits - i.Refunds = temp.Refunds - i.Payments = temp.Payments - i.CustomFields = temp.CustomFields - i.DisplaySettings = temp.DisplaySettings - i.PublicUrl = temp.PublicUrl - i.PreviousBalanceData = temp.PreviousBalanceData - return nil + var temp invoice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Id = temp.Id + i.Uid = temp.Uid + i.SiteId = temp.SiteId + i.CustomerId = temp.CustomerId + i.SubscriptionId = temp.SubscriptionId + i.Number = temp.Number + i.SequenceNumber = temp.SequenceNumber + if temp.TransactionTime != nil { + TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) + if err != nil { + log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) + } + i.TransactionTime = &TransactionTimeVal + } + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + i.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + i.UpdatedAt = &UpdatedAtVal + } + if temp.IssueDate != nil { + IssueDateVal, err := time.Parse(DEFAULT_DATE, *temp.IssueDate) + if err != nil { + log.Fatalf("Cannot Parse issue_date as % s format.", DEFAULT_DATE) + } + i.IssueDate = &IssueDateVal + } + if temp.DueDate != nil { + DueDateVal, err := time.Parse(DEFAULT_DATE, *temp.DueDate) + if err != nil { + log.Fatalf("Cannot Parse due_date as % s format.", DEFAULT_DATE) + } + i.DueDate = &DueDateVal + } + i.PaidDate.ShouldSetValue(temp.PaidDate.IsValueSet()) + if temp.PaidDate.Value() != nil { + PaidDateVal, err := time.Parse(DEFAULT_DATE, (*temp.PaidDate.Value())) + if err != nil { + log.Fatalf("Cannot Parse paid_date as % s format.", DEFAULT_DATE) + } + i.PaidDate.SetValue(&PaidDateVal) + } + i.Status = temp.Status + i.Role = temp.Role + i.ParentInvoiceId = temp.ParentInvoiceId + i.CollectionMethod = temp.CollectionMethod + i.PaymentInstructions = temp.PaymentInstructions + i.Currency = temp.Currency + i.ConsolidationLevel = temp.ConsolidationLevel + i.ParentInvoiceUid = temp.ParentInvoiceUid + i.SubscriptionGroupId = temp.SubscriptionGroupId + i.ParentInvoiceNumber = temp.ParentInvoiceNumber + i.GroupPrimarySubscriptionId = temp.GroupPrimarySubscriptionId + i.ProductName = temp.ProductName + i.ProductFamilyName = temp.ProductFamilyName + i.Seller = temp.Seller + i.Customer = temp.Customer + i.Payer = temp.Payer + i.RecipientEmails = temp.RecipientEmails + i.NetTerms = temp.NetTerms + i.Memo = temp.Memo + i.BillingAddress = temp.BillingAddress + i.ShippingAddress = temp.ShippingAddress + i.SubtotalAmount = temp.SubtotalAmount + i.DiscountAmount = temp.DiscountAmount + i.TaxAmount = temp.TaxAmount + i.TotalAmount = temp.TotalAmount + i.CreditAmount = temp.CreditAmount + i.RefundAmount = temp.RefundAmount + i.PaidAmount = temp.PaidAmount + i.DueAmount = temp.DueAmount + i.LineItems = temp.LineItems + i.Discounts = temp.Discounts + i.Taxes = temp.Taxes + i.Credits = temp.Credits + i.Refunds = temp.Refunds + i.Payments = temp.Payments + i.CustomFields = temp.CustomFields + i.DisplaySettings = temp.DisplaySettings + i.PublicUrl = temp.PublicUrl + i.PreviousBalanceData = temp.PreviousBalanceData + return nil +} + +// TODO +type invoice struct { + Id *int64 `json:"id,omitempty"` + Uid *string `json:"uid,omitempty"` + SiteId *int `json:"site_id,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + Number *string `json:"number,omitempty"` + SequenceNumber *int `json:"sequence_number,omitempty"` + TransactionTime *string `json:"transaction_time,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + IssueDate *string `json:"issue_date,omitempty"` + DueDate *string `json:"due_date,omitempty"` + PaidDate Optional[string] `json:"paid_date"` + Status *InvoiceStatus `json:"status,omitempty"` + Role *InvoiceRole `json:"role,omitempty"` + ParentInvoiceId Optional[int] `json:"parent_invoice_id"` + CollectionMethod *CollectionMethod `json:"collection_method,omitempty"` + PaymentInstructions *string `json:"payment_instructions,omitempty"` + Currency *string `json:"currency,omitempty"` + ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` + ParentInvoiceUid Optional[string] `json:"parent_invoice_uid"` + SubscriptionGroupId Optional[int] `json:"subscription_group_id"` + ParentInvoiceNumber Optional[int] `json:"parent_invoice_number"` + GroupPrimarySubscriptionId Optional[int] `json:"group_primary_subscription_id"` + ProductName *string `json:"product_name,omitempty"` + ProductFamilyName *string `json:"product_family_name,omitempty"` + Seller *InvoiceSeller `json:"seller,omitempty"` + Customer *InvoiceCustomer `json:"customer,omitempty"` + Payer *InvoicePayer `json:"payer,omitempty"` + RecipientEmails []string `json:"recipient_emails,omitempty"` + NetTerms *int `json:"net_terms,omitempty"` + Memo *string `json:"memo,omitempty"` + BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` + ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + TotalAmount *string `json:"total_amount,omitempty"` + CreditAmount *string `json:"credit_amount,omitempty"` + RefundAmount *string `json:"refund_amount,omitempty"` + PaidAmount *string `json:"paid_amount,omitempty"` + DueAmount *string `json:"due_amount,omitempty"` + LineItems []InvoiceLineItem `json:"line_items,omitempty"` + Discounts []InvoiceDiscount `json:"discounts,omitempty"` + Taxes []InvoiceTax `json:"taxes,omitempty"` + Credits []InvoiceCredit `json:"credits,omitempty"` + Refunds []InvoiceRefund `json:"refunds,omitempty"` + Payments []InvoicePayment `json:"payments,omitempty"` + CustomFields []InvoiceCustomField `json:"custom_fields,omitempty"` + DisplaySettings *InvoiceDisplaySettings `json:"display_settings,omitempty"` + PublicUrl *string `json:"public_url,omitempty"` + PreviousBalanceData *InvoicePreviousBalance `json:"previous_balance_data,omitempty"` } diff --git a/models/invoice_address.go b/models/invoice_address.go index 9bf32367..dcbbacf5 100644 --- a/models/invoice_address.go +++ b/models/invoice_address.go @@ -1,72 +1,98 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoiceAddress represents a InvoiceAddress struct. type InvoiceAddress struct { - Street Optional[string] `json:"street"` - Line2 Optional[string] `json:"line2"` - City Optional[string] `json:"city"` - State Optional[string] `json:"state"` - Zip Optional[string] `json:"zip"` - Country Optional[string] `json:"country"` + Street Optional[string] `json:"street"` + Line2 Optional[string] `json:"line2"` + City Optional[string] `json:"city"` + State Optional[string] `json:"state"` + Zip Optional[string] `json:"zip"` + Country Optional[string] `json:"country"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceAddress. +// MarshalJSON implements the json.Marshaler interface for InvoiceAddress. // It customizes the JSON marshaling process for InvoiceAddress objects. func (i *InvoiceAddress) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceAddress object to a map representation for JSON marshaling. func (i *InvoiceAddress) toMap() map[string]any { - structMap := make(map[string]any) - if i.Street.IsValueSet() { - structMap["street"] = i.Street.Value() - } - if i.Line2.IsValueSet() { - structMap["line2"] = i.Line2.Value() - } - if i.City.IsValueSet() { - structMap["city"] = i.City.Value() - } - if i.State.IsValueSet() { - structMap["state"] = i.State.Value() - } - if i.Zip.IsValueSet() { - structMap["zip"] = i.Zip.Value() - } - if i.Country.IsValueSet() { - structMap["country"] = i.Country.Value() - } - return structMap + structMap := make(map[string]any) + if i.Street.IsValueSet() { + if i.Street.Value() != nil { + structMap["street"] = i.Street.Value() + } else { + structMap["street"] = nil + } + } + if i.Line2.IsValueSet() { + if i.Line2.Value() != nil { + structMap["line2"] = i.Line2.Value() + } else { + structMap["line2"] = nil + } + } + if i.City.IsValueSet() { + if i.City.Value() != nil { + structMap["city"] = i.City.Value() + } else { + structMap["city"] = nil + } + } + if i.State.IsValueSet() { + if i.State.Value() != nil { + structMap["state"] = i.State.Value() + } else { + structMap["state"] = nil + } + } + if i.Zip.IsValueSet() { + if i.Zip.Value() != nil { + structMap["zip"] = i.Zip.Value() + } else { + structMap["zip"] = nil + } + } + if i.Country.IsValueSet() { + if i.Country.Value() != nil { + structMap["country"] = i.Country.Value() + } else { + structMap["country"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceAddress. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceAddress. // It customizes the JSON unmarshaling process for InvoiceAddress objects. func (i *InvoiceAddress) UnmarshalJSON(input []byte) error { - temp := &struct { - Street Optional[string] `json:"street"` - Line2 Optional[string] `json:"line2"` - City Optional[string] `json:"city"` - State Optional[string] `json:"state"` - Zip Optional[string] `json:"zip"` - Country Optional[string] `json:"country"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Street = temp.Street - i.Line2 = temp.Line2 - i.City = temp.City - i.State = temp.State - i.Zip = temp.Zip - i.Country = temp.Country - return nil + var temp invoiceAddress + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Street = temp.Street + i.Line2 = temp.Line2 + i.City = temp.City + i.State = temp.State + i.Zip = temp.Zip + i.Country = temp.Country + return nil +} + +// TODO +type invoiceAddress struct { + Street Optional[string] `json:"street"` + Line2 Optional[string] `json:"line2"` + City Optional[string] `json:"city"` + State Optional[string] `json:"state"` + Zip Optional[string] `json:"zip"` + Country Optional[string] `json:"country"` } diff --git a/models/invoice_balance_item.go b/models/invoice_balance_item.go index afdd4ca0..a14f2cca 100644 --- a/models/invoice_balance_item.go +++ b/models/invoice_balance_item.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoiceBalanceItem represents a InvoiceBalanceItem struct. type InvoiceBalanceItem struct { - Uid *string `json:"uid,omitempty"` - Number *string `json:"number,omitempty"` - OutstandingAmount *string `json:"outstanding_amount,omitempty"` + Uid *string `json:"uid,omitempty"` + Number *string `json:"number,omitempty"` + OutstandingAmount *string `json:"outstanding_amount,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceBalanceItem. +// MarshalJSON implements the json.Marshaler interface for InvoiceBalanceItem. // It customizes the JSON marshaling process for InvoiceBalanceItem objects. func (i *InvoiceBalanceItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceBalanceItem object to a map representation for JSON marshaling. func (i *InvoiceBalanceItem) toMap() map[string]any { - structMap := make(map[string]any) - if i.Uid != nil { - structMap["uid"] = i.Uid - } - if i.Number != nil { - structMap["number"] = i.Number - } - if i.OutstandingAmount != nil { - structMap["outstanding_amount"] = i.OutstandingAmount - } - return structMap + structMap := make(map[string]any) + if i.Uid != nil { + structMap["uid"] = i.Uid + } + if i.Number != nil { + structMap["number"] = i.Number + } + if i.OutstandingAmount != nil { + structMap["outstanding_amount"] = i.OutstandingAmount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceBalanceItem. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceBalanceItem. // It customizes the JSON unmarshaling process for InvoiceBalanceItem objects. func (i *InvoiceBalanceItem) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Number *string `json:"number,omitempty"` - OutstandingAmount *string `json:"outstanding_amount,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Uid = temp.Uid - i.Number = temp.Number - i.OutstandingAmount = temp.OutstandingAmount - return nil + var temp invoiceBalanceItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Uid = temp.Uid + i.Number = temp.Number + i.OutstandingAmount = temp.OutstandingAmount + return nil +} + +// TODO +type invoiceBalanceItem struct { + Uid *string `json:"uid,omitempty"` + Number *string `json:"number,omitempty"` + OutstandingAmount *string `json:"outstanding_amount,omitempty"` } diff --git a/models/invoice_credit.go b/models/invoice_credit.go index 48fbfbef..02e9d391 100644 --- a/models/invoice_credit.go +++ b/models/invoice_credit.go @@ -1,86 +1,88 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // InvoiceCredit represents a InvoiceCredit struct. type InvoiceCredit struct { - Uid *string `json:"uid,omitempty"` - CreditNoteNumber *string `json:"credit_note_number,omitempty"` - CreditNoteUid *string `json:"credit_note_uid,omitempty"` - TransactionTime *time.Time `json:"transaction_time,omitempty"` - Memo *string `json:"memo,omitempty"` - OriginalAmount *string `json:"original_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` + Uid *string `json:"uid,omitempty"` + CreditNoteNumber *string `json:"credit_note_number,omitempty"` + CreditNoteUid *string `json:"credit_note_uid,omitempty"` + TransactionTime *time.Time `json:"transaction_time,omitempty"` + Memo *string `json:"memo,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceCredit. +// MarshalJSON implements the json.Marshaler interface for InvoiceCredit. // It customizes the JSON marshaling process for InvoiceCredit objects. func (i *InvoiceCredit) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceCredit object to a map representation for JSON marshaling. func (i *InvoiceCredit) toMap() map[string]any { - structMap := make(map[string]any) - if i.Uid != nil { - structMap["uid"] = i.Uid - } - if i.CreditNoteNumber != nil { - structMap["credit_note_number"] = i.CreditNoteNumber - } - if i.CreditNoteUid != nil { - structMap["credit_note_uid"] = i.CreditNoteUid - } - if i.TransactionTime != nil { - structMap["transaction_time"] = i.TransactionTime.Format(time.RFC3339) - } - if i.Memo != nil { - structMap["memo"] = i.Memo - } - if i.OriginalAmount != nil { - structMap["original_amount"] = i.OriginalAmount - } - if i.AppliedAmount != nil { - structMap["applied_amount"] = i.AppliedAmount - } - return structMap + structMap := make(map[string]any) + if i.Uid != nil { + structMap["uid"] = i.Uid + } + if i.CreditNoteNumber != nil { + structMap["credit_note_number"] = i.CreditNoteNumber + } + if i.CreditNoteUid != nil { + structMap["credit_note_uid"] = i.CreditNoteUid + } + if i.TransactionTime != nil { + structMap["transaction_time"] = i.TransactionTime.Format(time.RFC3339) + } + if i.Memo != nil { + structMap["memo"] = i.Memo + } + if i.OriginalAmount != nil { + structMap["original_amount"] = i.OriginalAmount + } + if i.AppliedAmount != nil { + structMap["applied_amount"] = i.AppliedAmount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceCredit. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceCredit. // It customizes the JSON unmarshaling process for InvoiceCredit objects. func (i *InvoiceCredit) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - CreditNoteNumber *string `json:"credit_note_number,omitempty"` - CreditNoteUid *string `json:"credit_note_uid,omitempty"` - TransactionTime *string `json:"transaction_time,omitempty"` - Memo *string `json:"memo,omitempty"` - OriginalAmount *string `json:"original_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Uid = temp.Uid - i.CreditNoteNumber = temp.CreditNoteNumber - i.CreditNoteUid = temp.CreditNoteUid - if temp.TransactionTime != nil { - TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) - if err != nil { - log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) - } - i.TransactionTime = &TransactionTimeVal - } - i.Memo = temp.Memo - i.OriginalAmount = temp.OriginalAmount - i.AppliedAmount = temp.AppliedAmount - return nil + var temp invoiceCredit + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Uid = temp.Uid + i.CreditNoteNumber = temp.CreditNoteNumber + i.CreditNoteUid = temp.CreditNoteUid + if temp.TransactionTime != nil { + TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) + if err != nil { + log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) + } + i.TransactionTime = &TransactionTimeVal + } + i.Memo = temp.Memo + i.OriginalAmount = temp.OriginalAmount + i.AppliedAmount = temp.AppliedAmount + return nil +} + +// TODO +type invoiceCredit struct { + Uid *string `json:"uid,omitempty"` + CreditNoteNumber *string `json:"credit_note_number,omitempty"` + CreditNoteUid *string `json:"credit_note_uid,omitempty"` + TransactionTime *string `json:"transaction_time,omitempty"` + Memo *string `json:"memo,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` } diff --git a/models/invoice_custom_field.go b/models/invoice_custom_field.go index 14afddf0..c007ebe2 100644 --- a/models/invoice_custom_field.go +++ b/models/invoice_custom_field.go @@ -1,66 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoiceCustomField represents a InvoiceCustomField struct. type InvoiceCustomField struct { - OwnerId *int `json:"owner_id,omitempty"` - OwnerType *CustomFieldOwner `json:"owner_type,omitempty"` - Name *string `json:"name,omitempty"` - Value *string `json:"value,omitempty"` - MetadatumId *int `json:"metadatum_id,omitempty"` + OwnerId *int `json:"owner_id,omitempty"` + OwnerType *CustomFieldOwner `json:"owner_type,omitempty"` + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` + MetadatumId *int `json:"metadatum_id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceCustomField. +// MarshalJSON implements the json.Marshaler interface for InvoiceCustomField. // It customizes the JSON marshaling process for InvoiceCustomField objects. func (i *InvoiceCustomField) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceCustomField object to a map representation for JSON marshaling. func (i *InvoiceCustomField) toMap() map[string]any { - structMap := make(map[string]any) - if i.OwnerId != nil { - structMap["owner_id"] = i.OwnerId - } - if i.OwnerType != nil { - structMap["owner_type"] = i.OwnerType - } - if i.Name != nil { - structMap["name"] = i.Name - } - if i.Value != nil { - structMap["value"] = i.Value - } - if i.MetadatumId != nil { - structMap["metadatum_id"] = i.MetadatumId - } - return structMap + structMap := make(map[string]any) + if i.OwnerId != nil { + structMap["owner_id"] = i.OwnerId + } + if i.OwnerType != nil { + structMap["owner_type"] = i.OwnerType + } + if i.Name != nil { + structMap["name"] = i.Name + } + if i.Value != nil { + structMap["value"] = i.Value + } + if i.MetadatumId != nil { + structMap["metadatum_id"] = i.MetadatumId + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceCustomField. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceCustomField. // It customizes the JSON unmarshaling process for InvoiceCustomField objects. func (i *InvoiceCustomField) UnmarshalJSON(input []byte) error { - temp := &struct { - OwnerId *int `json:"owner_id,omitempty"` - OwnerType *CustomFieldOwner `json:"owner_type,omitempty"` - Name *string `json:"name,omitempty"` - Value *string `json:"value,omitempty"` - MetadatumId *int `json:"metadatum_id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.OwnerId = temp.OwnerId - i.OwnerType = temp.OwnerType - i.Name = temp.Name - i.Value = temp.Value - i.MetadatumId = temp.MetadatumId - return nil + var temp invoiceCustomField + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.OwnerId = temp.OwnerId + i.OwnerType = temp.OwnerType + i.Name = temp.Name + i.Value = temp.Value + i.MetadatumId = temp.MetadatumId + return nil +} + +// TODO +type invoiceCustomField struct { + OwnerId *int `json:"owner_id,omitempty"` + OwnerType *CustomFieldOwner `json:"owner_type,omitempty"` + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` + MetadatumId *int `json:"metadatum_id,omitempty"` } diff --git a/models/invoice_customer.go b/models/invoice_customer.go index 65118c7d..1604daef 100644 --- a/models/invoice_customer.go +++ b/models/invoice_customer.go @@ -1,79 +1,97 @@ package models import ( - "encoding/json" + "encoding/json" ) -// InvoiceCustomer represents a InvoiceCustomer struct. +// InvoiceCustomer represents a InvoiceCustomer struct. // Information about the customer who is owner or recipient the invoiced subscription. type InvoiceCustomer struct { - ChargifyId Optional[int] `json:"chargify_id"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Organization Optional[string] `json:"organization"` - Email *string `json:"email,omitempty"` - VatNumber Optional[string] `json:"vat_number"` - Reference Optional[string] `json:"reference"` + ChargifyId Optional[int] `json:"chargify_id"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Organization Optional[string] `json:"organization"` + Email *string `json:"email,omitempty"` + VatNumber Optional[string] `json:"vat_number"` + Reference Optional[string] `json:"reference"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceCustomer. +// MarshalJSON implements the json.Marshaler interface for InvoiceCustomer. // It customizes the JSON marshaling process for InvoiceCustomer objects. func (i *InvoiceCustomer) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceCustomer object to a map representation for JSON marshaling. func (i *InvoiceCustomer) toMap() map[string]any { - structMap := make(map[string]any) - if i.ChargifyId.IsValueSet() { - structMap["chargify_id"] = i.ChargifyId.Value() - } - if i.FirstName != nil { - structMap["first_name"] = i.FirstName - } - if i.LastName != nil { - structMap["last_name"] = i.LastName - } - if i.Organization.IsValueSet() { - structMap["organization"] = i.Organization.Value() - } - if i.Email != nil { - structMap["email"] = i.Email - } - if i.VatNumber.IsValueSet() { - structMap["vat_number"] = i.VatNumber.Value() - } - if i.Reference.IsValueSet() { - structMap["reference"] = i.Reference.Value() - } - return structMap + structMap := make(map[string]any) + if i.ChargifyId.IsValueSet() { + if i.ChargifyId.Value() != nil { + structMap["chargify_id"] = i.ChargifyId.Value() + } else { + structMap["chargify_id"] = nil + } + } + if i.FirstName != nil { + structMap["first_name"] = i.FirstName + } + if i.LastName != nil { + structMap["last_name"] = i.LastName + } + if i.Organization.IsValueSet() { + if i.Organization.Value() != nil { + structMap["organization"] = i.Organization.Value() + } else { + structMap["organization"] = nil + } + } + if i.Email != nil { + structMap["email"] = i.Email + } + if i.VatNumber.IsValueSet() { + if i.VatNumber.Value() != nil { + structMap["vat_number"] = i.VatNumber.Value() + } else { + structMap["vat_number"] = nil + } + } + if i.Reference.IsValueSet() { + if i.Reference.Value() != nil { + structMap["reference"] = i.Reference.Value() + } else { + structMap["reference"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceCustomer. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceCustomer. // It customizes the JSON unmarshaling process for InvoiceCustomer objects. func (i *InvoiceCustomer) UnmarshalJSON(input []byte) error { - temp := &struct { - ChargifyId Optional[int] `json:"chargify_id"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Organization Optional[string] `json:"organization"` - Email *string `json:"email,omitempty"` - VatNumber Optional[string] `json:"vat_number"` - Reference Optional[string] `json:"reference"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.ChargifyId = temp.ChargifyId - i.FirstName = temp.FirstName - i.LastName = temp.LastName - i.Organization = temp.Organization - i.Email = temp.Email - i.VatNumber = temp.VatNumber - i.Reference = temp.Reference - return nil + var temp invoiceCustomer + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.ChargifyId = temp.ChargifyId + i.FirstName = temp.FirstName + i.LastName = temp.LastName + i.Organization = temp.Organization + i.Email = temp.Email + i.VatNumber = temp.VatNumber + i.Reference = temp.Reference + return nil +} + +// TODO +type invoiceCustomer struct { + ChargifyId Optional[int] `json:"chargify_id"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Organization Optional[string] `json:"organization"` + Email *string `json:"email,omitempty"` + VatNumber Optional[string] `json:"vat_number"` + Reference Optional[string] `json:"reference"` } diff --git a/models/invoice_discount.go b/models/invoice_discount.go index f4fe2843..ecfb94a4 100644 --- a/models/invoice_discount.go +++ b/models/invoice_discount.go @@ -1,108 +1,114 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoiceDiscount represents a InvoiceDiscount struct. type InvoiceDiscount struct { - Uid *string `json:"uid,omitempty"` - Title *string `json:"title,omitempty"` - Description Optional[string] `json:"description"` - Code *string `json:"code,omitempty"` - SourceType *InvoiceDiscountSourceType `json:"source_type,omitempty"` - SourceId *int `json:"source_id,omitempty"` - DiscountType *InvoiceDiscountType `json:"discount_type,omitempty"` - Percentage *string `json:"percentage,omitempty"` - EligibleAmount *string `json:"eligible_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - TransactionId *int `json:"transaction_id,omitempty"` - LineItemBreakouts []InvoiceDiscountBreakout `json:"line_item_breakouts,omitempty"` + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + Description Optional[string] `json:"description"` + Code *string `json:"code,omitempty"` + SourceType *InvoiceDiscountSourceType `json:"source_type,omitempty"` + SourceId *int `json:"source_id,omitempty"` + DiscountType *InvoiceDiscountType `json:"discount_type,omitempty"` + Percentage *string `json:"percentage,omitempty"` + EligibleAmount *string `json:"eligible_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` + TransactionId *int `json:"transaction_id,omitempty"` + LineItemBreakouts []InvoiceDiscountBreakout `json:"line_item_breakouts,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceDiscount. +// MarshalJSON implements the json.Marshaler interface for InvoiceDiscount. // It customizes the JSON marshaling process for InvoiceDiscount objects. func (i *InvoiceDiscount) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceDiscount object to a map representation for JSON marshaling. func (i *InvoiceDiscount) toMap() map[string]any { - structMap := make(map[string]any) - if i.Uid != nil { - structMap["uid"] = i.Uid - } - if i.Title != nil { - structMap["title"] = i.Title - } - if i.Description.IsValueSet() { - structMap["description"] = i.Description.Value() - } - if i.Code != nil { - structMap["code"] = i.Code - } - if i.SourceType != nil { - structMap["source_type"] = i.SourceType - } - if i.SourceId != nil { - structMap["source_id"] = i.SourceId - } - if i.DiscountType != nil { - structMap["discount_type"] = i.DiscountType - } - if i.Percentage != nil { - structMap["percentage"] = i.Percentage - } - if i.EligibleAmount != nil { - structMap["eligible_amount"] = i.EligibleAmount - } - if i.DiscountAmount != nil { - structMap["discount_amount"] = i.DiscountAmount - } - if i.TransactionId != nil { - structMap["transaction_id"] = i.TransactionId - } - if i.LineItemBreakouts != nil { - structMap["line_item_breakouts"] = i.LineItemBreakouts - } - return structMap + structMap := make(map[string]any) + if i.Uid != nil { + structMap["uid"] = i.Uid + } + if i.Title != nil { + structMap["title"] = i.Title + } + if i.Description.IsValueSet() { + if i.Description.Value() != nil { + structMap["description"] = i.Description.Value() + } else { + structMap["description"] = nil + } + } + if i.Code != nil { + structMap["code"] = i.Code + } + if i.SourceType != nil { + structMap["source_type"] = i.SourceType + } + if i.SourceId != nil { + structMap["source_id"] = i.SourceId + } + if i.DiscountType != nil { + structMap["discount_type"] = i.DiscountType + } + if i.Percentage != nil { + structMap["percentage"] = i.Percentage + } + if i.EligibleAmount != nil { + structMap["eligible_amount"] = i.EligibleAmount + } + if i.DiscountAmount != nil { + structMap["discount_amount"] = i.DiscountAmount + } + if i.TransactionId != nil { + structMap["transaction_id"] = i.TransactionId + } + if i.LineItemBreakouts != nil { + structMap["line_item_breakouts"] = i.LineItemBreakouts + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceDiscount. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceDiscount. // It customizes the JSON unmarshaling process for InvoiceDiscount objects. func (i *InvoiceDiscount) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Title *string `json:"title,omitempty"` - Description Optional[string] `json:"description"` - Code *string `json:"code,omitempty"` - SourceType *InvoiceDiscountSourceType `json:"source_type,omitempty"` - SourceId *int `json:"source_id,omitempty"` - DiscountType *InvoiceDiscountType `json:"discount_type,omitempty"` - Percentage *string `json:"percentage,omitempty"` - EligibleAmount *string `json:"eligible_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - TransactionId *int `json:"transaction_id,omitempty"` - LineItemBreakouts []InvoiceDiscountBreakout `json:"line_item_breakouts,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Uid = temp.Uid - i.Title = temp.Title - i.Description = temp.Description - i.Code = temp.Code - i.SourceType = temp.SourceType - i.SourceId = temp.SourceId - i.DiscountType = temp.DiscountType - i.Percentage = temp.Percentage - i.EligibleAmount = temp.EligibleAmount - i.DiscountAmount = temp.DiscountAmount - i.TransactionId = temp.TransactionId - i.LineItemBreakouts = temp.LineItemBreakouts - return nil + var temp invoiceDiscount + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Uid = temp.Uid + i.Title = temp.Title + i.Description = temp.Description + i.Code = temp.Code + i.SourceType = temp.SourceType + i.SourceId = temp.SourceId + i.DiscountType = temp.DiscountType + i.Percentage = temp.Percentage + i.EligibleAmount = temp.EligibleAmount + i.DiscountAmount = temp.DiscountAmount + i.TransactionId = temp.TransactionId + i.LineItemBreakouts = temp.LineItemBreakouts + return nil +} + +// TODO +type invoiceDiscount struct { + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + Description Optional[string] `json:"description"` + Code *string `json:"code,omitempty"` + SourceType *InvoiceDiscountSourceType `json:"source_type,omitempty"` + SourceId *int `json:"source_id,omitempty"` + DiscountType *InvoiceDiscountType `json:"discount_type,omitempty"` + Percentage *string `json:"percentage,omitempty"` + EligibleAmount *string `json:"eligible_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` + TransactionId *int `json:"transaction_id,omitempty"` + LineItemBreakouts []InvoiceDiscountBreakout `json:"line_item_breakouts,omitempty"` } diff --git a/models/invoice_discount_breakout.go b/models/invoice_discount_breakout.go index 0e61b367..71f2501b 100644 --- a/models/invoice_discount_breakout.go +++ b/models/invoice_discount_breakout.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoiceDiscountBreakout represents a InvoiceDiscountBreakout struct. type InvoiceDiscountBreakout struct { - Uid *string `json:"uid,omitempty"` - EligibleAmount *string `json:"eligible_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` + Uid *string `json:"uid,omitempty"` + EligibleAmount *string `json:"eligible_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceDiscountBreakout. +// MarshalJSON implements the json.Marshaler interface for InvoiceDiscountBreakout. // It customizes the JSON marshaling process for InvoiceDiscountBreakout objects. func (i *InvoiceDiscountBreakout) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceDiscountBreakout object to a map representation for JSON marshaling. func (i *InvoiceDiscountBreakout) toMap() map[string]any { - structMap := make(map[string]any) - if i.Uid != nil { - structMap["uid"] = i.Uid - } - if i.EligibleAmount != nil { - structMap["eligible_amount"] = i.EligibleAmount - } - if i.DiscountAmount != nil { - structMap["discount_amount"] = i.DiscountAmount - } - return structMap + structMap := make(map[string]any) + if i.Uid != nil { + structMap["uid"] = i.Uid + } + if i.EligibleAmount != nil { + structMap["eligible_amount"] = i.EligibleAmount + } + if i.DiscountAmount != nil { + structMap["discount_amount"] = i.DiscountAmount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceDiscountBreakout. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceDiscountBreakout. // It customizes the JSON unmarshaling process for InvoiceDiscountBreakout objects. func (i *InvoiceDiscountBreakout) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - EligibleAmount *string `json:"eligible_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Uid = temp.Uid - i.EligibleAmount = temp.EligibleAmount - i.DiscountAmount = temp.DiscountAmount - return nil + var temp invoiceDiscountBreakout + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Uid = temp.Uid + i.EligibleAmount = temp.EligibleAmount + i.DiscountAmount = temp.DiscountAmount + return nil +} + +// TODO +type invoiceDiscountBreakout struct { + Uid *string `json:"uid,omitempty"` + EligibleAmount *string `json:"eligible_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` } diff --git a/models/invoice_display_settings.go b/models/invoice_display_settings.go index 9a464e12..beab07b5 100644 --- a/models/invoice_display_settings.go +++ b/models/invoice_display_settings.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoiceDisplaySettings represents a InvoiceDisplaySettings struct. type InvoiceDisplaySettings struct { - HideZeroSubtotalLines *bool `json:"hide_zero_subtotal_lines,omitempty"` - IncludeDiscountsOnLines *bool `json:"include_discounts_on_lines,omitempty"` + HideZeroSubtotalLines *bool `json:"hide_zero_subtotal_lines,omitempty"` + IncludeDiscountsOnLines *bool `json:"include_discounts_on_lines,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceDisplaySettings. +// MarshalJSON implements the json.Marshaler interface for InvoiceDisplaySettings. // It customizes the JSON marshaling process for InvoiceDisplaySettings objects. func (i *InvoiceDisplaySettings) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceDisplaySettings object to a map representation for JSON marshaling. func (i *InvoiceDisplaySettings) toMap() map[string]any { - structMap := make(map[string]any) - if i.HideZeroSubtotalLines != nil { - structMap["hide_zero_subtotal_lines"] = i.HideZeroSubtotalLines - } - if i.IncludeDiscountsOnLines != nil { - structMap["include_discounts_on_lines"] = i.IncludeDiscountsOnLines - } - return structMap + structMap := make(map[string]any) + if i.HideZeroSubtotalLines != nil { + structMap["hide_zero_subtotal_lines"] = i.HideZeroSubtotalLines + } + if i.IncludeDiscountsOnLines != nil { + structMap["include_discounts_on_lines"] = i.IncludeDiscountsOnLines + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceDisplaySettings. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceDisplaySettings. // It customizes the JSON unmarshaling process for InvoiceDisplaySettings objects. func (i *InvoiceDisplaySettings) UnmarshalJSON(input []byte) error { - temp := &struct { - HideZeroSubtotalLines *bool `json:"hide_zero_subtotal_lines,omitempty"` - IncludeDiscountsOnLines *bool `json:"include_discounts_on_lines,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.HideZeroSubtotalLines = temp.HideZeroSubtotalLines - i.IncludeDiscountsOnLines = temp.IncludeDiscountsOnLines - return nil + var temp invoiceDisplaySettings + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.HideZeroSubtotalLines = temp.HideZeroSubtotalLines + i.IncludeDiscountsOnLines = temp.IncludeDiscountsOnLines + return nil +} + +// TODO +type invoiceDisplaySettings struct { + HideZeroSubtotalLines *bool `json:"hide_zero_subtotal_lines,omitempty"` + IncludeDiscountsOnLines *bool `json:"include_discounts_on_lines,omitempty"` } diff --git a/models/invoice_event.go b/models/invoice_event.go index 622c4452..4d2a4179 100644 --- a/models/invoice_event.go +++ b/models/invoice_event.go @@ -1,76 +1,78 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // InvoiceEvent represents a InvoiceEvent struct. type InvoiceEvent struct { - Id *int `json:"id,omitempty"` - // Invoice Event Type - EventType *InvoiceEventType `json:"event_type,omitempty"` - // The event data is the data that, when combined with the command, results in the output invoice found in the invoice field. - EventData *InvoiceEventData `json:"event_data,omitempty"` - Timestamp *time.Time `json:"timestamp,omitempty"` - Invoice *Invoice `json:"invoice,omitempty"` + Id *int `json:"id,omitempty"` + // Invoice Event Type + EventType *InvoiceEventType `json:"event_type,omitempty"` + // The event data is the data that, when combined with the command, results in the output invoice found in the invoice field. + EventData *InvoiceEventEventData `json:"event_data,omitempty"` + Timestamp *time.Time `json:"timestamp,omitempty"` + Invoice *Invoice `json:"invoice,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceEvent. +// MarshalJSON implements the json.Marshaler interface for InvoiceEvent. // It customizes the JSON marshaling process for InvoiceEvent objects. func (i *InvoiceEvent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceEvent object to a map representation for JSON marshaling. func (i *InvoiceEvent) toMap() map[string]any { - structMap := make(map[string]any) - if i.Id != nil { - structMap["id"] = i.Id - } - if i.EventType != nil { - structMap["event_type"] = i.EventType - } - if i.EventData != nil { - structMap["event_data"] = i.EventData.toMap() - } - if i.Timestamp != nil { - structMap["timestamp"] = i.Timestamp.Format(time.RFC3339) - } - if i.Invoice != nil { - structMap["invoice"] = i.Invoice.toMap() - } - return structMap + structMap := make(map[string]any) + if i.Id != nil { + structMap["id"] = i.Id + } + if i.EventType != nil { + structMap["event_type"] = i.EventType + } + if i.EventData != nil { + structMap["event_data"] = i.EventData.toMap() + } + if i.Timestamp != nil { + structMap["timestamp"] = i.Timestamp.Format(time.RFC3339) + } + if i.Invoice != nil { + structMap["invoice"] = i.Invoice.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceEvent. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceEvent. // It customizes the JSON unmarshaling process for InvoiceEvent objects. func (i *InvoiceEvent) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - EventType *InvoiceEventType `json:"event_type,omitempty"` - EventData *InvoiceEventData `json:"event_data,omitempty"` - Timestamp *string `json:"timestamp,omitempty"` - Invoice *Invoice `json:"invoice,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Id = temp.Id - i.EventType = temp.EventType - i.EventData = temp.EventData - if temp.Timestamp != nil { - TimestampVal, err := time.Parse(time.RFC3339, *temp.Timestamp) - if err != nil { - log.Fatalf("Cannot Parse timestamp as % s format.", time.RFC3339) - } - i.Timestamp = &TimestampVal - } - i.Invoice = temp.Invoice - return nil + var temp invoiceEvent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Id = temp.Id + i.EventType = temp.EventType + i.EventData = temp.EventData + if temp.Timestamp != nil { + TimestampVal, err := time.Parse(time.RFC3339, *temp.Timestamp) + if err != nil { + log.Fatalf("Cannot Parse timestamp as % s format.", time.RFC3339) + } + i.Timestamp = &TimestampVal + } + i.Invoice = temp.Invoice + return nil +} + +// TODO +type invoiceEvent struct { + Id *int `json:"id,omitempty"` + EventType *InvoiceEventType `json:"event_type,omitempty"` + EventData *InvoiceEventEventData `json:"event_data,omitempty"` + Timestamp *string `json:"timestamp,omitempty"` + Invoice *Invoice `json:"invoice,omitempty"` } diff --git a/models/invoice_event_data.go b/models/invoice_event_data.go index 1b4b63c3..44be2f53 100644 --- a/models/invoice_event_data.go +++ b/models/invoice_event_data.go @@ -1,270 +1,280 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) -// InvoiceEventData represents a InvoiceEventData struct. +// InvoiceEventData represents a InvoiceEventData struct. // The event data is the data that, when combined with the command, results in the output invoice found in the invoice field. type InvoiceEventData struct { - // Unique identifier for the credit note application. It is generated automatically by Chargify and has the prefix "cdt_" followed by alphanumeric characters. - Uid *string `json:"uid,omitempty"` - // A unique, identifying string that appears on the credit note and in places it is referenced. - CreditNoteNumber *string `json:"credit_note_number,omitempty"` - // Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. - CreditNoteUid *string `json:"credit_note_uid,omitempty"` - // The full, original amount of the credit note. - OriginalAmount *string `json:"original_amount,omitempty"` - // The amount of the credit note applied to invoice. - AppliedAmount *string `json:"applied_amount,omitempty"` - // The time the credit note was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" - TransactionTime *time.Time `json:"transaction_time,omitempty"` - // The credit note memo. - Memo *string `json:"memo,omitempty"` - // The role of the credit note (e.g. 'general') - Role *string `json:"role,omitempty"` - // Shows whether it was applied to consolidated invoice or not - ConsolidatedInvoice *bool `json:"consolidated_invoice,omitempty"` - // List of credit notes applied to children invoices (if consolidated invoice) - AppliedCreditNotes []AppliedCreditNoteData `json:"applied_credit_notes,omitempty"` - // A unique, identifying string that appears on the debit note and in places it is referenced. - DebitNoteNumber *string `json:"debit_note_number,omitempty"` - // Unique identifier for the debit note. It is generated automatically by Chargify and has the prefix "db_" followed by alphanumeric characters. - DebitNoteUid *string `json:"debit_note_uid,omitempty"` - // A nested data structure detailing the method of payment - PaymentMethod *InvoiceEventPayment1 `json:"payment_method,omitempty"` - // The Chargify id of the original payment - TransactionId *int `json:"transaction_id,omitempty"` - ParentInvoiceNumber Optional[int] `json:"parent_invoice_number"` - RemainingPrepaymentAmount Optional[string] `json:"remaining_prepayment_amount"` - // The flag that shows whether the original payment was a prepayment or not - Prepayment *bool `json:"prepayment,omitempty"` - External *bool `json:"external,omitempty"` - // The previous collection method of the invoice. - FromCollectionMethod *string `json:"from_collection_method,omitempty"` - // The new collection method of the invoice. - ToCollectionMethod *string `json:"to_collection_method,omitempty"` - // Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values: - // * "none": A normal invoice with no consolidation. - // * "child": An invoice segment which has been combined into a consolidated invoice. - // * "parent": A consolidated invoice, whose contents are composed of invoice segments. - // "Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments. - // See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). - ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` - // The status of the invoice before event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. - FromStatus *InvoiceStatus `json:"from_status,omitempty"` - // The status of the invoice after event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. - ToStatus *InvoiceStatus `json:"to_status,omitempty"` - // Amount due on the invoice, which is `total_amount - credit_amount - paid_amount`. - DueAmount *string `json:"due_amount,omitempty"` - // The invoice total, which is `subtotal_amount - discount_amount + tax_amount`.' - TotalAmount *string `json:"total_amount,omitempty"` - // If true, credit was created and applied it to the invoice. - ApplyCredit *bool `json:"apply_credit,omitempty"` - CreditNoteAttributes *CreditNote1 `json:"credit_note_attributes,omitempty"` - // The ID of the payment transaction to be refunded. - PaymentId *int `json:"payment_id,omitempty"` - // The amount of the refund. - RefundAmount *string `json:"refund_amount,omitempty"` - // The ID of the refund transaction. - RefundId *int `json:"refund_id,omitempty"` - // If true, the invoice is an advance invoice. - IsAdvanceInvoice *bool `json:"is_advance_invoice,omitempty"` - // The reason for the void. - Reason *string `json:"reason,omitempty"` + // Unique identifier for the credit note application. It is generated automatically by Chargify and has the prefix "cdt_" followed by alphanumeric characters. + Uid *string `json:"uid,omitempty"` + // A unique, identifying string that appears on the credit note and in places it is referenced. + CreditNoteNumber *string `json:"credit_note_number,omitempty"` + // Unique identifier for the credit note. It is generated automatically by Chargify and has the prefix "cn_" followed by alphanumeric characters. + CreditNoteUid *string `json:"credit_note_uid,omitempty"` + // The full, original amount of the credit note. + OriginalAmount *string `json:"original_amount,omitempty"` + // The amount of the credit note applied to invoice. + AppliedAmount *string `json:"applied_amount,omitempty"` + // The time the credit note was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" + TransactionTime *time.Time `json:"transaction_time,omitempty"` + // The credit note memo. + Memo *string `json:"memo,omitempty"` + // The role of the credit note (e.g. 'general') + Role *string `json:"role,omitempty"` + // Shows whether it was applied to consolidated invoice or not + ConsolidatedInvoice *bool `json:"consolidated_invoice,omitempty"` + // List of credit notes applied to children invoices (if consolidated invoice) + AppliedCreditNotes []AppliedCreditNoteData `json:"applied_credit_notes,omitempty"` + // A unique, identifying string that appears on the debit note and in places it is referenced. + DebitNoteNumber *string `json:"debit_note_number,omitempty"` + // Unique identifier for the debit note. It is generated automatically by Chargify and has the prefix "db_" followed by alphanumeric characters. + DebitNoteUid *string `json:"debit_note_uid,omitempty"` + // A nested data structure detailing the method of payment + PaymentMethod *InvoiceEventDataPaymentMethod `json:"payment_method,omitempty"` + // The Chargify id of the original payment + TransactionId *int `json:"transaction_id,omitempty"` + ParentInvoiceNumber Optional[int] `json:"parent_invoice_number"` + RemainingPrepaymentAmount Optional[string] `json:"remaining_prepayment_amount"` + // The flag that shows whether the original payment was a prepayment or not + Prepayment *bool `json:"prepayment,omitempty"` + External *bool `json:"external,omitempty"` + // The previous collection method of the invoice. + FromCollectionMethod *string `json:"from_collection_method,omitempty"` + // The new collection method of the invoice. + ToCollectionMethod *string `json:"to_collection_method,omitempty"` + // Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values: + // * "none": A normal invoice with no consolidation. + // * "child": An invoice segment which has been combined into a consolidated invoice. + // * "parent": A consolidated invoice, whose contents are composed of invoice segments. + // "Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments. + // See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). + ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` + // The status of the invoice before event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. + FromStatus *InvoiceStatus `json:"from_status,omitempty"` + // The status of the invoice after event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. + ToStatus *InvoiceStatus `json:"to_status,omitempty"` + // Amount due on the invoice, which is `total_amount - credit_amount - paid_amount`. + DueAmount *string `json:"due_amount,omitempty"` + // The invoice total, which is `subtotal_amount - discount_amount + tax_amount`.' + TotalAmount *string `json:"total_amount,omitempty"` + // If true, credit was created and applied it to the invoice. + ApplyCredit *bool `json:"apply_credit,omitempty"` + CreditNoteAttributes *CreditNote1 `json:"credit_note_attributes,omitempty"` + // The ID of the payment transaction to be refunded. + PaymentId *int `json:"payment_id,omitempty"` + // The amount of the refund. + RefundAmount *string `json:"refund_amount,omitempty"` + // The ID of the refund transaction. + RefundId *int `json:"refund_id,omitempty"` + // If true, the invoice is an advance invoice. + IsAdvanceInvoice *bool `json:"is_advance_invoice,omitempty"` + // The reason for the void. + Reason *string `json:"reason,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceEventData. +// MarshalJSON implements the json.Marshaler interface for InvoiceEventData. // It customizes the JSON marshaling process for InvoiceEventData objects. func (i *InvoiceEventData) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceEventData object to a map representation for JSON marshaling. func (i *InvoiceEventData) toMap() map[string]any { - structMap := make(map[string]any) - if i.Uid != nil { - structMap["uid"] = i.Uid - } - if i.CreditNoteNumber != nil { - structMap["credit_note_number"] = i.CreditNoteNumber - } - if i.CreditNoteUid != nil { - structMap["credit_note_uid"] = i.CreditNoteUid - } - if i.OriginalAmount != nil { - structMap["original_amount"] = i.OriginalAmount - } - if i.AppliedAmount != nil { - structMap["applied_amount"] = i.AppliedAmount - } - if i.TransactionTime != nil { - structMap["transaction_time"] = i.TransactionTime.Format(time.RFC3339) - } - if i.Memo != nil { - structMap["memo"] = i.Memo - } - if i.Role != nil { - structMap["role"] = i.Role - } - if i.ConsolidatedInvoice != nil { - structMap["consolidated_invoice"] = i.ConsolidatedInvoice - } - if i.AppliedCreditNotes != nil { - structMap["applied_credit_notes"] = i.AppliedCreditNotes - } - if i.DebitNoteNumber != nil { - structMap["debit_note_number"] = i.DebitNoteNumber - } - if i.DebitNoteUid != nil { - structMap["debit_note_uid"] = i.DebitNoteUid - } - if i.PaymentMethod != nil { - structMap["payment_method"] = i.PaymentMethod.toMap() - } - if i.TransactionId != nil { - structMap["transaction_id"] = i.TransactionId - } - if i.ParentInvoiceNumber.IsValueSet() { - structMap["parent_invoice_number"] = i.ParentInvoiceNumber.Value() - } - if i.RemainingPrepaymentAmount.IsValueSet() { - structMap["remaining_prepayment_amount"] = i.RemainingPrepaymentAmount.Value() - } - if i.Prepayment != nil { - structMap["prepayment"] = i.Prepayment - } - if i.External != nil { - structMap["external"] = i.External - } - if i.FromCollectionMethod != nil { - structMap["from_collection_method"] = i.FromCollectionMethod - } - if i.ToCollectionMethod != nil { - structMap["to_collection_method"] = i.ToCollectionMethod - } - if i.ConsolidationLevel != nil { - structMap["consolidation_level"] = i.ConsolidationLevel - } - if i.FromStatus != nil { - structMap["from_status"] = i.FromStatus - } - if i.ToStatus != nil { - structMap["to_status"] = i.ToStatus - } - if i.DueAmount != nil { - structMap["due_amount"] = i.DueAmount - } - if i.TotalAmount != nil { - structMap["total_amount"] = i.TotalAmount - } - if i.ApplyCredit != nil { - structMap["apply_credit"] = i.ApplyCredit - } - if i.CreditNoteAttributes != nil { - structMap["credit_note_attributes"] = i.CreditNoteAttributes.toMap() - } - if i.PaymentId != nil { - structMap["payment_id"] = i.PaymentId - } - if i.RefundAmount != nil { - structMap["refund_amount"] = i.RefundAmount - } - if i.RefundId != nil { - structMap["refund_id"] = i.RefundId - } - if i.IsAdvanceInvoice != nil { - structMap["is_advance_invoice"] = i.IsAdvanceInvoice - } - if i.Reason != nil { - structMap["reason"] = i.Reason - } - return structMap + structMap := make(map[string]any) + if i.Uid != nil { + structMap["uid"] = i.Uid + } + if i.CreditNoteNumber != nil { + structMap["credit_note_number"] = i.CreditNoteNumber + } + if i.CreditNoteUid != nil { + structMap["credit_note_uid"] = i.CreditNoteUid + } + if i.OriginalAmount != nil { + structMap["original_amount"] = i.OriginalAmount + } + if i.AppliedAmount != nil { + structMap["applied_amount"] = i.AppliedAmount + } + if i.TransactionTime != nil { + structMap["transaction_time"] = i.TransactionTime.Format(time.RFC3339) + } + if i.Memo != nil { + structMap["memo"] = i.Memo + } + if i.Role != nil { + structMap["role"] = i.Role + } + if i.ConsolidatedInvoice != nil { + structMap["consolidated_invoice"] = i.ConsolidatedInvoice + } + if i.AppliedCreditNotes != nil { + structMap["applied_credit_notes"] = i.AppliedCreditNotes + } + if i.DebitNoteNumber != nil { + structMap["debit_note_number"] = i.DebitNoteNumber + } + if i.DebitNoteUid != nil { + structMap["debit_note_uid"] = i.DebitNoteUid + } + if i.PaymentMethod != nil { + structMap["payment_method"] = i.PaymentMethod.toMap() + } + if i.TransactionId != nil { + structMap["transaction_id"] = i.TransactionId + } + if i.ParentInvoiceNumber.IsValueSet() { + if i.ParentInvoiceNumber.Value() != nil { + structMap["parent_invoice_number"] = i.ParentInvoiceNumber.Value() + } else { + structMap["parent_invoice_number"] = nil + } + } + if i.RemainingPrepaymentAmount.IsValueSet() { + if i.RemainingPrepaymentAmount.Value() != nil { + structMap["remaining_prepayment_amount"] = i.RemainingPrepaymentAmount.Value() + } else { + structMap["remaining_prepayment_amount"] = nil + } + } + if i.Prepayment != nil { + structMap["prepayment"] = i.Prepayment + } + if i.External != nil { + structMap["external"] = i.External + } + if i.FromCollectionMethod != nil { + structMap["from_collection_method"] = i.FromCollectionMethod + } + if i.ToCollectionMethod != nil { + structMap["to_collection_method"] = i.ToCollectionMethod + } + if i.ConsolidationLevel != nil { + structMap["consolidation_level"] = i.ConsolidationLevel + } + if i.FromStatus != nil { + structMap["from_status"] = i.FromStatus + } + if i.ToStatus != nil { + structMap["to_status"] = i.ToStatus + } + if i.DueAmount != nil { + structMap["due_amount"] = i.DueAmount + } + if i.TotalAmount != nil { + structMap["total_amount"] = i.TotalAmount + } + if i.ApplyCredit != nil { + structMap["apply_credit"] = i.ApplyCredit + } + if i.CreditNoteAttributes != nil { + structMap["credit_note_attributes"] = i.CreditNoteAttributes.toMap() + } + if i.PaymentId != nil { + structMap["payment_id"] = i.PaymentId + } + if i.RefundAmount != nil { + structMap["refund_amount"] = i.RefundAmount + } + if i.RefundId != nil { + structMap["refund_id"] = i.RefundId + } + if i.IsAdvanceInvoice != nil { + structMap["is_advance_invoice"] = i.IsAdvanceInvoice + } + if i.Reason != nil { + structMap["reason"] = i.Reason + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceEventData. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceEventData. // It customizes the JSON unmarshaling process for InvoiceEventData objects. func (i *InvoiceEventData) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - CreditNoteNumber *string `json:"credit_note_number,omitempty"` - CreditNoteUid *string `json:"credit_note_uid,omitempty"` - OriginalAmount *string `json:"original_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - TransactionTime *string `json:"transaction_time,omitempty"` - Memo *string `json:"memo,omitempty"` - Role *string `json:"role,omitempty"` - ConsolidatedInvoice *bool `json:"consolidated_invoice,omitempty"` - AppliedCreditNotes []AppliedCreditNoteData `json:"applied_credit_notes,omitempty"` - DebitNoteNumber *string `json:"debit_note_number,omitempty"` - DebitNoteUid *string `json:"debit_note_uid,omitempty"` - PaymentMethod *InvoiceEventPayment1 `json:"payment_method,omitempty"` - TransactionId *int `json:"transaction_id,omitempty"` - ParentInvoiceNumber Optional[int] `json:"parent_invoice_number"` - RemainingPrepaymentAmount Optional[string] `json:"remaining_prepayment_amount"` - Prepayment *bool `json:"prepayment,omitempty"` - External *bool `json:"external,omitempty"` - FromCollectionMethod *string `json:"from_collection_method,omitempty"` - ToCollectionMethod *string `json:"to_collection_method,omitempty"` - ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` - FromStatus *InvoiceStatus `json:"from_status,omitempty"` - ToStatus *InvoiceStatus `json:"to_status,omitempty"` - DueAmount *string `json:"due_amount,omitempty"` - TotalAmount *string `json:"total_amount,omitempty"` - ApplyCredit *bool `json:"apply_credit,omitempty"` - CreditNoteAttributes *CreditNote1 `json:"credit_note_attributes,omitempty"` - PaymentId *int `json:"payment_id,omitempty"` - RefundAmount *string `json:"refund_amount,omitempty"` - RefundId *int `json:"refund_id,omitempty"` - IsAdvanceInvoice *bool `json:"is_advance_invoice,omitempty"` - Reason *string `json:"reason,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Uid = temp.Uid - i.CreditNoteNumber = temp.CreditNoteNumber - i.CreditNoteUid = temp.CreditNoteUid - i.OriginalAmount = temp.OriginalAmount - i.AppliedAmount = temp.AppliedAmount - if temp.TransactionTime != nil { - TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) - if err != nil { - log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) - } - i.TransactionTime = &TransactionTimeVal - } - i.Memo = temp.Memo - i.Role = temp.Role - i.ConsolidatedInvoice = temp.ConsolidatedInvoice - i.AppliedCreditNotes = temp.AppliedCreditNotes - i.DebitNoteNumber = temp.DebitNoteNumber - i.DebitNoteUid = temp.DebitNoteUid - i.PaymentMethod = temp.PaymentMethod - i.TransactionId = temp.TransactionId - i.ParentInvoiceNumber = temp.ParentInvoiceNumber - i.RemainingPrepaymentAmount = temp.RemainingPrepaymentAmount - i.Prepayment = temp.Prepayment - i.External = temp.External - i.FromCollectionMethod = temp.FromCollectionMethod - i.ToCollectionMethod = temp.ToCollectionMethod - i.ConsolidationLevel = temp.ConsolidationLevel - i.FromStatus = temp.FromStatus - i.ToStatus = temp.ToStatus - i.DueAmount = temp.DueAmount - i.TotalAmount = temp.TotalAmount - i.ApplyCredit = temp.ApplyCredit - i.CreditNoteAttributes = temp.CreditNoteAttributes - i.PaymentId = temp.PaymentId - i.RefundAmount = temp.RefundAmount - i.RefundId = temp.RefundId - i.IsAdvanceInvoice = temp.IsAdvanceInvoice - i.Reason = temp.Reason - return nil + var temp invoiceEventData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Uid = temp.Uid + i.CreditNoteNumber = temp.CreditNoteNumber + i.CreditNoteUid = temp.CreditNoteUid + i.OriginalAmount = temp.OriginalAmount + i.AppliedAmount = temp.AppliedAmount + if temp.TransactionTime != nil { + TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) + if err != nil { + log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) + } + i.TransactionTime = &TransactionTimeVal + } + i.Memo = temp.Memo + i.Role = temp.Role + i.ConsolidatedInvoice = temp.ConsolidatedInvoice + i.AppliedCreditNotes = temp.AppliedCreditNotes + i.DebitNoteNumber = temp.DebitNoteNumber + i.DebitNoteUid = temp.DebitNoteUid + i.PaymentMethod = temp.PaymentMethod + i.TransactionId = temp.TransactionId + i.ParentInvoiceNumber = temp.ParentInvoiceNumber + i.RemainingPrepaymentAmount = temp.RemainingPrepaymentAmount + i.Prepayment = temp.Prepayment + i.External = temp.External + i.FromCollectionMethod = temp.FromCollectionMethod + i.ToCollectionMethod = temp.ToCollectionMethod + i.ConsolidationLevel = temp.ConsolidationLevel + i.FromStatus = temp.FromStatus + i.ToStatus = temp.ToStatus + i.DueAmount = temp.DueAmount + i.TotalAmount = temp.TotalAmount + i.ApplyCredit = temp.ApplyCredit + i.CreditNoteAttributes = temp.CreditNoteAttributes + i.PaymentId = temp.PaymentId + i.RefundAmount = temp.RefundAmount + i.RefundId = temp.RefundId + i.IsAdvanceInvoice = temp.IsAdvanceInvoice + i.Reason = temp.Reason + return nil +} + +// TODO +type invoiceEventData struct { + Uid *string `json:"uid,omitempty"` + CreditNoteNumber *string `json:"credit_note_number,omitempty"` + CreditNoteUid *string `json:"credit_note_uid,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` + TransactionTime *string `json:"transaction_time,omitempty"` + Memo *string `json:"memo,omitempty"` + Role *string `json:"role,omitempty"` + ConsolidatedInvoice *bool `json:"consolidated_invoice,omitempty"` + AppliedCreditNotes []AppliedCreditNoteData `json:"applied_credit_notes,omitempty"` + DebitNoteNumber *string `json:"debit_note_number,omitempty"` + DebitNoteUid *string `json:"debit_note_uid,omitempty"` + PaymentMethod *InvoiceEventDataPaymentMethod `json:"payment_method,omitempty"` + TransactionId *int `json:"transaction_id,omitempty"` + ParentInvoiceNumber Optional[int] `json:"parent_invoice_number"` + RemainingPrepaymentAmount Optional[string] `json:"remaining_prepayment_amount"` + Prepayment *bool `json:"prepayment,omitempty"` + External *bool `json:"external,omitempty"` + FromCollectionMethod *string `json:"from_collection_method,omitempty"` + ToCollectionMethod *string `json:"to_collection_method,omitempty"` + ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` + FromStatus *InvoiceStatus `json:"from_status,omitempty"` + ToStatus *InvoiceStatus `json:"to_status,omitempty"` + DueAmount *string `json:"due_amount,omitempty"` + TotalAmount *string `json:"total_amount,omitempty"` + ApplyCredit *bool `json:"apply_credit,omitempty"` + CreditNoteAttributes *CreditNote1 `json:"credit_note_attributes,omitempty"` + PaymentId *int `json:"payment_id,omitempty"` + RefundAmount *string `json:"refund_amount,omitempty"` + RefundId *int `json:"refund_id,omitempty"` + IsAdvanceInvoice *bool `json:"is_advance_invoice,omitempty"` + Reason *string `json:"reason,omitempty"` } diff --git a/models/invoice_event_data_payment_method.go b/models/invoice_event_data_payment_method.go new file mode 100644 index 00000000..1d531078 --- /dev/null +++ b/models/invoice_event_data_payment_method.go @@ -0,0 +1,145 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// InvoiceEventDataPaymentMethod represents a InvoiceEventDataPaymentMethod struct. +// This is a container for any-of cases. +type InvoiceEventDataPaymentMethod struct { + value any + isPaymentMethodApplePay bool + isPaymentMethodBankAccount bool + isPaymentMethodCreditCard bool + isPaymentMethodExternal bool + isPaymentMethodPaypal bool +} + +// String converts the InvoiceEventDataPaymentMethod object to a string representation. +func (i InvoiceEventDataPaymentMethod) String() string { + if bytes, err := json.Marshal(i.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for InvoiceEventDataPaymentMethod. +// It customizes the JSON marshaling process for InvoiceEventDataPaymentMethod objects. +func (i *InvoiceEventDataPaymentMethod) MarshalJSON() ( + []byte, + error) { + if i.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.InvoiceEventDataPaymentMethodContainer.From*` functions to initialize the InvoiceEventDataPaymentMethod object.") + } + return json.Marshal(i.toMap()) +} + +// toMap converts the InvoiceEventDataPaymentMethod object to a map representation for JSON marshaling. +func (i *InvoiceEventDataPaymentMethod) toMap() any { + switch obj := i.value.(type) { + case *PaymentMethodApplePay: + return obj.toMap() + case *PaymentMethodBankAccount: + return obj.toMap() + case *PaymentMethodCreditCard: + return obj.toMap() + case *PaymentMethodExternal: + return obj.toMap() + case *PaymentMethodPaypal: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceEventDataPaymentMethod. +// It customizes the JSON unmarshaling process for InvoiceEventDataPaymentMethod objects. +func (i *InvoiceEventDataPaymentMethod) UnmarshalJSON(input []byte) error { + result, err := UnmarshallAnyOf(input, + NewTypeHolder(&PaymentMethodApplePay{}, false, &i.isPaymentMethodApplePay), + NewTypeHolder(&PaymentMethodBankAccount{}, false, &i.isPaymentMethodBankAccount), + NewTypeHolder(&PaymentMethodCreditCard{}, false, &i.isPaymentMethodCreditCard), + NewTypeHolder(&PaymentMethodExternal{}, false, &i.isPaymentMethodExternal), + NewTypeHolder(&PaymentMethodPaypal{}, false, &i.isPaymentMethodPaypal), + ) + + i.value = result + return err +} + +func (i *InvoiceEventDataPaymentMethod) AsPaymentMethodApplePay() ( + *PaymentMethodApplePay, + bool) { + if !i.isPaymentMethodApplePay { + return nil, false + } + return i.value.(*PaymentMethodApplePay), true +} + +func (i *InvoiceEventDataPaymentMethod) AsPaymentMethodBankAccount() ( + *PaymentMethodBankAccount, + bool) { + if !i.isPaymentMethodBankAccount { + return nil, false + } + return i.value.(*PaymentMethodBankAccount), true +} + +func (i *InvoiceEventDataPaymentMethod) AsPaymentMethodCreditCard() ( + *PaymentMethodCreditCard, + bool) { + if !i.isPaymentMethodCreditCard { + return nil, false + } + return i.value.(*PaymentMethodCreditCard), true +} + +func (i *InvoiceEventDataPaymentMethod) AsPaymentMethodExternal() ( + *PaymentMethodExternal, + bool) { + if !i.isPaymentMethodExternal { + return nil, false + } + return i.value.(*PaymentMethodExternal), true +} + +func (i *InvoiceEventDataPaymentMethod) AsPaymentMethodPaypal() ( + *PaymentMethodPaypal, + bool) { + if !i.isPaymentMethodPaypal { + return nil, false + } + return i.value.(*PaymentMethodPaypal), true +} + +// internalInvoiceEventDataPaymentMethod represents a invoiceEventDataPaymentMethod struct. +// This is a container for any-of cases. +type internalInvoiceEventDataPaymentMethod struct{} + +var InvoiceEventDataPaymentMethodContainer internalInvoiceEventDataPaymentMethod + +func (i *internalInvoiceEventDataPaymentMethod) FromPaymentMethodApplePay(val PaymentMethodApplePay) InvoiceEventDataPaymentMethod { + return InvoiceEventDataPaymentMethod{value: &val} +} + +func (i *internalInvoiceEventDataPaymentMethod) FromPaymentMethodBankAccount(val PaymentMethodBankAccount) InvoiceEventDataPaymentMethod { + return InvoiceEventDataPaymentMethod{value: &val} +} + +func (i *internalInvoiceEventDataPaymentMethod) FromPaymentMethodCreditCard(val PaymentMethodCreditCard) InvoiceEventDataPaymentMethod { + return InvoiceEventDataPaymentMethod{value: &val} +} + +func (i *internalInvoiceEventDataPaymentMethod) FromPaymentMethodExternal(val PaymentMethodExternal) InvoiceEventDataPaymentMethod { + return InvoiceEventDataPaymentMethod{value: &val} +} + +func (i *internalInvoiceEventDataPaymentMethod) FromPaymentMethodPaypal(val PaymentMethodPaypal) InvoiceEventDataPaymentMethod { + return InvoiceEventDataPaymentMethod{value: &val} +} diff --git a/models/invoice_event_event_data.go b/models/invoice_event_event_data.go new file mode 100644 index 00000000..53cda4b3 --- /dev/null +++ b/models/invoice_event_event_data.go @@ -0,0 +1,213 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// InvoiceEventEventData represents a InvoiceEventEventData struct. +// This is a container for any-of cases. +type InvoiceEventEventData struct { + value any + isApplyCreditNoteEventData bool + isApplyDebitNoteEventData bool + isApplyPaymentEventData bool + isChangeInvoiceCollectionMethodEventData bool + isIssueInvoiceEventData bool + isRefundInvoiceEventData bool + isRemovePaymentEventData bool + isVoidInvoiceEventData bool + isVoidRemainderEventData bool +} + +// String converts the InvoiceEventEventData object to a string representation. +func (i InvoiceEventEventData) String() string { + if bytes, err := json.Marshal(i.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for InvoiceEventEventData. +// It customizes the JSON marshaling process for InvoiceEventEventData objects. +func (i *InvoiceEventEventData) MarshalJSON() ( + []byte, + error) { + if i.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.InvoiceEventEventDataContainer.From*` functions to initialize the InvoiceEventEventData object.") + } + return json.Marshal(i.toMap()) +} + +// toMap converts the InvoiceEventEventData object to a map representation for JSON marshaling. +func (i *InvoiceEventEventData) toMap() any { + switch obj := i.value.(type) { + case *ApplyCreditNoteEventData: + return obj.toMap() + case *ApplyDebitNoteEventData: + return obj.toMap() + case *ApplyPaymentEventData: + return obj.toMap() + case *ChangeInvoiceCollectionMethodEventData: + return obj.toMap() + case *IssueInvoiceEventData: + return obj.toMap() + case *RefundInvoiceEventData: + return obj.toMap() + case *RemovePaymentEventData: + return obj.toMap() + case *VoidInvoiceEventData: + return obj.toMap() + case *VoidRemainderEventData: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceEventEventData. +// It customizes the JSON unmarshaling process for InvoiceEventEventData objects. +func (i *InvoiceEventEventData) UnmarshalJSON(input []byte) error { + result, err := UnmarshallAnyOf(input, + NewTypeHolder(&ApplyCreditNoteEventData{}, false, &i.isApplyCreditNoteEventData), + NewTypeHolder(&ApplyDebitNoteEventData{}, false, &i.isApplyDebitNoteEventData), + NewTypeHolder(&ApplyPaymentEventData{}, false, &i.isApplyPaymentEventData), + NewTypeHolder(&ChangeInvoiceCollectionMethodEventData{}, false, &i.isChangeInvoiceCollectionMethodEventData), + NewTypeHolder(&IssueInvoiceEventData{}, false, &i.isIssueInvoiceEventData), + NewTypeHolder(&RefundInvoiceEventData{}, false, &i.isRefundInvoiceEventData), + NewTypeHolder(&RemovePaymentEventData{}, false, &i.isRemovePaymentEventData), + NewTypeHolder(&VoidInvoiceEventData{}, false, &i.isVoidInvoiceEventData), + NewTypeHolder(&VoidRemainderEventData{}, false, &i.isVoidRemainderEventData), + ) + + i.value = result + return err +} + +func (i *InvoiceEventEventData) AsApplyCreditNoteEventData() ( + *ApplyCreditNoteEventData, + bool) { + if !i.isApplyCreditNoteEventData { + return nil, false + } + return i.value.(*ApplyCreditNoteEventData), true +} + +func (i *InvoiceEventEventData) AsApplyDebitNoteEventData() ( + *ApplyDebitNoteEventData, + bool) { + if !i.isApplyDebitNoteEventData { + return nil, false + } + return i.value.(*ApplyDebitNoteEventData), true +} + +func (i *InvoiceEventEventData) AsApplyPaymentEventData() ( + *ApplyPaymentEventData, + bool) { + if !i.isApplyPaymentEventData { + return nil, false + } + return i.value.(*ApplyPaymentEventData), true +} + +func (i *InvoiceEventEventData) AsChangeInvoiceCollectionMethodEventData() ( + *ChangeInvoiceCollectionMethodEventData, + bool) { + if !i.isChangeInvoiceCollectionMethodEventData { + return nil, false + } + return i.value.(*ChangeInvoiceCollectionMethodEventData), true +} + +func (i *InvoiceEventEventData) AsIssueInvoiceEventData() ( + *IssueInvoiceEventData, + bool) { + if !i.isIssueInvoiceEventData { + return nil, false + } + return i.value.(*IssueInvoiceEventData), true +} + +func (i *InvoiceEventEventData) AsRefundInvoiceEventData() ( + *RefundInvoiceEventData, + bool) { + if !i.isRefundInvoiceEventData { + return nil, false + } + return i.value.(*RefundInvoiceEventData), true +} + +func (i *InvoiceEventEventData) AsRemovePaymentEventData() ( + *RemovePaymentEventData, + bool) { + if !i.isRemovePaymentEventData { + return nil, false + } + return i.value.(*RemovePaymentEventData), true +} + +func (i *InvoiceEventEventData) AsVoidInvoiceEventData() ( + *VoidInvoiceEventData, + bool) { + if !i.isVoidInvoiceEventData { + return nil, false + } + return i.value.(*VoidInvoiceEventData), true +} + +func (i *InvoiceEventEventData) AsVoidRemainderEventData() ( + *VoidRemainderEventData, + bool) { + if !i.isVoidRemainderEventData { + return nil, false + } + return i.value.(*VoidRemainderEventData), true +} + +// internalInvoiceEventEventData represents a invoiceEventEventData struct. +// This is a container for any-of cases. +type internalInvoiceEventEventData struct{} + +var InvoiceEventEventDataContainer internalInvoiceEventEventData + +func (i *internalInvoiceEventEventData) FromApplyCreditNoteEventData(val ApplyCreditNoteEventData) InvoiceEventEventData { + return InvoiceEventEventData{value: &val} +} + +func (i *internalInvoiceEventEventData) FromApplyDebitNoteEventData(val ApplyDebitNoteEventData) InvoiceEventEventData { + return InvoiceEventEventData{value: &val} +} + +func (i *internalInvoiceEventEventData) FromApplyPaymentEventData(val ApplyPaymentEventData) InvoiceEventEventData { + return InvoiceEventEventData{value: &val} +} + +func (i *internalInvoiceEventEventData) FromChangeInvoiceCollectionMethodEventData(val ChangeInvoiceCollectionMethodEventData) InvoiceEventEventData { + return InvoiceEventEventData{value: &val} +} + +func (i *internalInvoiceEventEventData) FromIssueInvoiceEventData(val IssueInvoiceEventData) InvoiceEventEventData { + return InvoiceEventEventData{value: &val} +} + +func (i *internalInvoiceEventEventData) FromRefundInvoiceEventData(val RefundInvoiceEventData) InvoiceEventEventData { + return InvoiceEventEventData{value: &val} +} + +func (i *internalInvoiceEventEventData) FromRemovePaymentEventData(val RemovePaymentEventData) InvoiceEventEventData { + return InvoiceEventEventData{value: &val} +} + +func (i *internalInvoiceEventEventData) FromVoidInvoiceEventData(val VoidInvoiceEventData) InvoiceEventEventData { + return InvoiceEventEventData{value: &val} +} + +func (i *internalInvoiceEventEventData) FromVoidRemainderEventData(val VoidRemainderEventData) InvoiceEventEventData { + return InvoiceEventEventData{value: &val} +} diff --git a/models/invoice_event_payment.go b/models/invoice_event_payment.go index 97332bc4..4520f71c 100644 --- a/models/invoice_event_payment.go +++ b/models/invoice_event_payment.go @@ -1,110 +1,124 @@ -/* -Package advancedbilling - -This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). */ package models import ( - "encoding/json" + "encoding/json" ) -// InvoiceEventPayment represents a InvoiceEventPayment struct. +// InvoiceEventPayment represents a InvoiceEventPayment struct. // A nested data structure detailing the method of payment type InvoiceEventPayment struct { - Type *string `json:"type,omitempty"` - MaskedAccountNumber *string `json:"masked_account_number,omitempty"` - MaskedRoutingNumber *string `json:"masked_routing_number,omitempty"` - CardBrand *string `json:"card_brand,omitempty"` - CardExpiration *string `json:"card_expiration,omitempty"` - LastFour Optional[string] `json:"last_four"` - MaskedCardNumber *string `json:"masked_card_number,omitempty"` - Details Optional[string] `json:"details"` - Kind *string `json:"kind,omitempty"` - Memo Optional[string] `json:"memo"` - Email *string `json:"email,omitempty"` + Type *string `json:"type,omitempty"` + MaskedAccountNumber *string `json:"masked_account_number,omitempty"` + MaskedRoutingNumber *string `json:"masked_routing_number,omitempty"` + CardBrand *string `json:"card_brand,omitempty"` + CardExpiration *string `json:"card_expiration,omitempty"` + LastFour Optional[string] `json:"last_four"` + MaskedCardNumber *string `json:"masked_card_number,omitempty"` + Details Optional[string] `json:"details"` + Kind *string `json:"kind,omitempty"` + Memo Optional[string] `json:"memo"` + Email *string `json:"email,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceEventPayment. +// MarshalJSON implements the json.Marshaler interface for InvoiceEventPayment. // It customizes the JSON marshaling process for InvoiceEventPayment objects. func (i *InvoiceEventPayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceEventPayment object to a map representation for JSON marshaling. func (i *InvoiceEventPayment) toMap() map[string]any { - structMap := make(map[string]any) - if i.Type != nil { - structMap["type"] = *i.Type - } else { - structMap["type"] = "Invoice Event Payment" - } - if i.MaskedAccountNumber != nil { - structMap["masked_account_number"] = i.MaskedAccountNumber - } - if i.MaskedRoutingNumber != nil { - structMap["masked_routing_number"] = i.MaskedRoutingNumber - } - if i.CardBrand != nil { - structMap["card_brand"] = i.CardBrand - } - if i.CardExpiration != nil { - structMap["card_expiration"] = i.CardExpiration - } - if i.LastFour.IsValueSet() { - structMap["last_four"] = i.LastFour.Value() - } - if i.MaskedCardNumber != nil { - structMap["masked_card_number"] = i.MaskedCardNumber - } - if i.Details.IsValueSet() { - structMap["details"] = i.Details.Value() - } - if i.Kind != nil { - structMap["kind"] = i.Kind - } - if i.Memo.IsValueSet() { - structMap["memo"] = i.Memo.Value() - } - if i.Email != nil { - structMap["email"] = i.Email - } - return structMap + structMap := make(map[string]any) + if i.Type != nil { + structMap["type"] = *i.Type + } else { + structMap["type"] = "Invoice Event Payment" + } + if i.MaskedAccountNumber != nil { + structMap["masked_account_number"] = i.MaskedAccountNumber + } + if i.MaskedRoutingNumber != nil { + structMap["masked_routing_number"] = i.MaskedRoutingNumber + } + if i.CardBrand != nil { + structMap["card_brand"] = i.CardBrand + } + if i.CardExpiration != nil { + structMap["card_expiration"] = i.CardExpiration + } + if i.LastFour.IsValueSet() { + if i.LastFour.Value() != nil { + structMap["last_four"] = i.LastFour.Value() + } else { + structMap["last_four"] = nil + } + } + if i.MaskedCardNumber != nil { + structMap["masked_card_number"] = i.MaskedCardNumber + } + if i.Details.IsValueSet() { + if i.Details.Value() != nil { + structMap["details"] = i.Details.Value() + } else { + structMap["details"] = nil + } + } + if i.Kind != nil { + structMap["kind"] = i.Kind + } + if i.Memo.IsValueSet() { + if i.Memo.Value() != nil { + structMap["memo"] = i.Memo.Value() + } else { + structMap["memo"] = nil + } + } + if i.Email != nil { + structMap["email"] = i.Email + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceEventPayment. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceEventPayment. // It customizes the JSON unmarshaling process for InvoiceEventPayment objects. func (i *InvoiceEventPayment) UnmarshalJSON(input []byte) error { - temp := &struct { - Type *string `json:"type,omitempty"` - MaskedAccountNumber *string `json:"masked_account_number,omitempty"` - MaskedRoutingNumber *string `json:"masked_routing_number,omitempty"` - CardBrand *string `json:"card_brand,omitempty"` - CardExpiration *string `json:"card_expiration,omitempty"` - LastFour Optional[string] `json:"last_four"` - MaskedCardNumber *string `json:"masked_card_number,omitempty"` - Details Optional[string] `json:"details"` - Kind *string `json:"kind,omitempty"` - Memo Optional[string] `json:"memo"` - Email *string `json:"email,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Type = temp.Type - i.MaskedAccountNumber = temp.MaskedAccountNumber - i.MaskedRoutingNumber = temp.MaskedRoutingNumber - i.CardBrand = temp.CardBrand - i.CardExpiration = temp.CardExpiration - i.LastFour = temp.LastFour - i.MaskedCardNumber = temp.MaskedCardNumber - i.Details = temp.Details - i.Kind = temp.Kind - i.Memo = temp.Memo - i.Email = temp.Email - return nil + var temp invoiceEventPayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Type = temp.Type + i.MaskedAccountNumber = temp.MaskedAccountNumber + i.MaskedRoutingNumber = temp.MaskedRoutingNumber + i.CardBrand = temp.CardBrand + i.CardExpiration = temp.CardExpiration + i.LastFour = temp.LastFour + i.MaskedCardNumber = temp.MaskedCardNumber + i.Details = temp.Details + i.Kind = temp.Kind + i.Memo = temp.Memo + i.Email = temp.Email + return nil +} + +// TODO +type invoiceEventPayment struct { + Type *string `json:"type,omitempty"` + MaskedAccountNumber *string `json:"masked_account_number,omitempty"` + MaskedRoutingNumber *string `json:"masked_routing_number,omitempty"` + CardBrand *string `json:"card_brand,omitempty"` + CardExpiration *string `json:"card_expiration,omitempty"` + LastFour Optional[string] `json:"last_four"` + MaskedCardNumber *string `json:"masked_card_number,omitempty"` + Details Optional[string] `json:"details"` + Kind *string `json:"kind,omitempty"` + Memo Optional[string] `json:"memo"` + Email *string `json:"email,omitempty"` } diff --git a/models/invoice_event_payment_1.go b/models/invoice_event_payment_1.go index 8ca8d60d..d53b1e7d 100644 --- a/models/invoice_event_payment_1.go +++ b/models/invoice_event_payment_1.go @@ -1,89 +1,136 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) -// InvoiceEventPayment1 represents a InvoiceEventPayment1 struct. +// InvoiceEventPayment1 represents a InvoiceEventPayment1 struct. // A nested data structure detailing the method of payment type InvoiceEventPayment1 struct { - Type *string `json:"type,omitempty"` - MaskedAccountNumber string `json:"masked_account_number"` - MaskedRoutingNumber string `json:"masked_routing_number"` - CardBrand string `json:"card_brand"` - CardExpiration *string `json:"card_expiration,omitempty"` - LastFour Optional[string] `json:"last_four"` - MaskedCardNumber string `json:"masked_card_number"` - Details *string `json:"details"` - Kind string `json:"kind"` - Memo *string `json:"memo"` - Email string `json:"email"` + Type *string `json:"type,omitempty"` + MaskedAccountNumber string `json:"masked_account_number"` + MaskedRoutingNumber string `json:"masked_routing_number"` + CardBrand string `json:"card_brand"` + CardExpiration *string `json:"card_expiration,omitempty"` + LastFour Optional[string] `json:"last_four"` + MaskedCardNumber string `json:"masked_card_number"` + Details *string `json:"details"` + Kind string `json:"kind"` + Memo *string `json:"memo"` + Email string `json:"email"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceEventPayment1. +// MarshalJSON implements the json.Marshaler interface for InvoiceEventPayment1. // It customizes the JSON marshaling process for InvoiceEventPayment1 objects. func (i *InvoiceEventPayment1) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceEventPayment1 object to a map representation for JSON marshaling. func (i *InvoiceEventPayment1) toMap() map[string]any { - structMap := make(map[string]any) - if i.Type != nil { - structMap["type"] = *i.Type - } else { - structMap["type"] = "Invoice Event Payment1" - } - structMap["masked_account_number"] = i.MaskedAccountNumber - structMap["masked_routing_number"] = i.MaskedRoutingNumber - structMap["card_brand"] = i.CardBrand - if i.CardExpiration != nil { - structMap["card_expiration"] = i.CardExpiration - } - if i.LastFour.IsValueSet() { - structMap["last_four"] = i.LastFour.Value() - } - structMap["masked_card_number"] = i.MaskedCardNumber - structMap["details"] = i.Details - structMap["kind"] = i.Kind - structMap["memo"] = i.Memo - structMap["email"] = i.Email - return structMap + structMap := make(map[string]any) + if i.Type != nil { + structMap["type"] = *i.Type + } else { + structMap["type"] = "Invoice Event Payment1" + } + structMap["masked_account_number"] = i.MaskedAccountNumber + structMap["masked_routing_number"] = i.MaskedRoutingNumber + structMap["card_brand"] = i.CardBrand + if i.CardExpiration != nil { + structMap["card_expiration"] = i.CardExpiration + } + if i.LastFour.IsValueSet() { + if i.LastFour.Value() != nil { + structMap["last_four"] = i.LastFour.Value() + } else { + structMap["last_four"] = nil + } + } + structMap["masked_card_number"] = i.MaskedCardNumber + if i.Details != nil { + structMap["details"] = i.Details + } else { + structMap["details"] = nil + } + structMap["kind"] = i.Kind + if i.Memo != nil { + structMap["memo"] = i.Memo + } else { + structMap["memo"] = nil + } + structMap["email"] = i.Email + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceEventPayment1. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceEventPayment1. // It customizes the JSON unmarshaling process for InvoiceEventPayment1 objects. func (i *InvoiceEventPayment1) UnmarshalJSON(input []byte) error { - temp := &struct { - Type *string `json:"type,omitempty"` - MaskedAccountNumber string `json:"masked_account_number"` - MaskedRoutingNumber string `json:"masked_routing_number"` - CardBrand string `json:"card_brand"` - CardExpiration *string `json:"card_expiration,omitempty"` - LastFour Optional[string] `json:"last_four"` - MaskedCardNumber string `json:"masked_card_number"` - Details *string `json:"details"` - Kind string `json:"kind"` - Memo *string `json:"memo"` - Email string `json:"email"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Type = temp.Type - i.MaskedAccountNumber = temp.MaskedAccountNumber - i.MaskedRoutingNumber = temp.MaskedRoutingNumber - i.CardBrand = temp.CardBrand - i.CardExpiration = temp.CardExpiration - i.LastFour = temp.LastFour - i.MaskedCardNumber = temp.MaskedCardNumber - i.Details = temp.Details - i.Kind = temp.Kind - i.Memo = temp.Memo - i.Email = temp.Email - return nil + var temp invoiceEventPayment1 + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + i.Type = temp.Type + i.MaskedAccountNumber = *temp.MaskedAccountNumber + i.MaskedRoutingNumber = *temp.MaskedRoutingNumber + i.CardBrand = *temp.CardBrand + i.CardExpiration = temp.CardExpiration + i.LastFour = temp.LastFour + i.MaskedCardNumber = *temp.MaskedCardNumber + i.Details = temp.Details + i.Kind = *temp.Kind + i.Memo = temp.Memo + i.Email = *temp.Email + return nil +} + +// TODO +type invoiceEventPayment1 struct { + Type *string `json:"type,omitempty"` + MaskedAccountNumber *string `json:"masked_account_number"` + MaskedRoutingNumber *string `json:"masked_routing_number"` + CardBrand *string `json:"card_brand"` + CardExpiration *string `json:"card_expiration,omitempty"` + LastFour Optional[string] `json:"last_four"` + MaskedCardNumber *string `json:"masked_card_number"` + Details *string `json:"details"` + Kind *string `json:"kind"` + Memo *string `json:"memo"` + Email *string `json:"email"` +} + +func (i *invoiceEventPayment1) validate() error { + var errs []string + if i.MaskedAccountNumber == nil { + errs = append(errs, "required field `masked_account_number` is missing for type `Invoice Event Payment1`") + } + if i.MaskedRoutingNumber == nil { + errs = append(errs, "required field `masked_routing_number` is missing for type `Invoice Event Payment1`") + } + if i.CardBrand == nil { + errs = append(errs, "required field `card_brand` is missing for type `Invoice Event Payment1`") + } + if i.MaskedCardNumber == nil { + errs = append(errs, "required field `masked_card_number` is missing for type `Invoice Event Payment1`") + } + if i.Kind == nil { + errs = append(errs, "required field `kind` is missing for type `Invoice Event Payment1`") + } + if i.Email == nil { + errs = append(errs, "required field `email` is missing for type `Invoice Event Payment1`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/invoice_event_payment_2.go b/models/invoice_event_payment_2.go new file mode 100644 index 00000000..8529fc03 --- /dev/null +++ b/models/invoice_event_payment_2.go @@ -0,0 +1,145 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// InvoiceEventPayment2 represents a InvoiceEventPayment2 struct. +// A nested data structure detailing the method of payment +type InvoiceEventPayment2 struct { + value any + isPaymentMethodApplePay bool + isPaymentMethodBankAccount bool + isPaymentMethodCreditCard bool + isPaymentMethodExternal bool + isPaymentMethodPaypal bool +} + +// String converts the InvoiceEventPayment2 object to a string representation. +func (i InvoiceEventPayment2) String() string { + if bytes, err := json.Marshal(i.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for InvoiceEventPayment2. +// It customizes the JSON marshaling process for InvoiceEventPayment2 objects. +func (i *InvoiceEventPayment2) MarshalJSON() ( + []byte, + error) { + if i.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.InvoiceEventPaymentContainer.From*` functions to initialize the InvoiceEventPayment2 object.") + } + return json.Marshal(i.toMap()) +} + +// toMap converts the InvoiceEventPayment2 object to a map representation for JSON marshaling. +func (i *InvoiceEventPayment2) toMap() any { + switch obj := i.value.(type) { + case *PaymentMethodApplePay: + return obj.toMap() + case *PaymentMethodBankAccount: + return obj.toMap() + case *PaymentMethodCreditCard: + return obj.toMap() + case *PaymentMethodExternal: + return obj.toMap() + case *PaymentMethodPaypal: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceEventPayment2. +// It customizes the JSON unmarshaling process for InvoiceEventPayment2 objects. +func (i *InvoiceEventPayment2) UnmarshalJSON(input []byte) error { + result, err := UnmarshallAnyOfWithDiscriminator(input, "type", + NewTypeHolderDiscriminator(&PaymentMethodApplePay{}, false, &i.isPaymentMethodApplePay, "apple_pay"), + NewTypeHolderDiscriminator(&PaymentMethodBankAccount{}, false, &i.isPaymentMethodBankAccount, "bank_account"), + NewTypeHolderDiscriminator(&PaymentMethodCreditCard{}, false, &i.isPaymentMethodCreditCard, "credit_card"), + NewTypeHolderDiscriminator(&PaymentMethodExternal{}, false, &i.isPaymentMethodExternal, "external"), + NewTypeHolderDiscriminator(&PaymentMethodPaypal{}, false, &i.isPaymentMethodPaypal, "paypal_account"), + ) + + i.value = result + return err +} + +func (i *InvoiceEventPayment2) AsPaymentMethodApplePay() ( + *PaymentMethodApplePay, + bool) { + if !i.isPaymentMethodApplePay { + return nil, false + } + return i.value.(*PaymentMethodApplePay), true +} + +func (i *InvoiceEventPayment2) AsPaymentMethodBankAccount() ( + *PaymentMethodBankAccount, + bool) { + if !i.isPaymentMethodBankAccount { + return nil, false + } + return i.value.(*PaymentMethodBankAccount), true +} + +func (i *InvoiceEventPayment2) AsPaymentMethodCreditCard() ( + *PaymentMethodCreditCard, + bool) { + if !i.isPaymentMethodCreditCard { + return nil, false + } + return i.value.(*PaymentMethodCreditCard), true +} + +func (i *InvoiceEventPayment2) AsPaymentMethodExternal() ( + *PaymentMethodExternal, + bool) { + if !i.isPaymentMethodExternal { + return nil, false + } + return i.value.(*PaymentMethodExternal), true +} + +func (i *InvoiceEventPayment2) AsPaymentMethodPaypal() ( + *PaymentMethodPaypal, + bool) { + if !i.isPaymentMethodPaypal { + return nil, false + } + return i.value.(*PaymentMethodPaypal), true +} + +// internalInvoiceEventPayment2 represents a invoiceEventPayment2 struct. +// A nested data structure detailing the method of payment +type internalInvoiceEventPayment2 struct{} + +var InvoiceEventPaymentContainer internalInvoiceEventPayment2 + +func (i *internalInvoiceEventPayment2) FromPaymentMethodApplePay(val PaymentMethodApplePay) InvoiceEventPayment2 { + return InvoiceEventPayment2{value: &val} +} + +func (i *internalInvoiceEventPayment2) FromPaymentMethodBankAccount(val PaymentMethodBankAccount) InvoiceEventPayment2 { + return InvoiceEventPayment2{value: &val} +} + +func (i *internalInvoiceEventPayment2) FromPaymentMethodCreditCard(val PaymentMethodCreditCard) InvoiceEventPayment2 { + return InvoiceEventPayment2{value: &val} +} + +func (i *internalInvoiceEventPayment2) FromPaymentMethodExternal(val PaymentMethodExternal) InvoiceEventPayment2 { + return InvoiceEventPayment2{value: &val} +} + +func (i *internalInvoiceEventPayment2) FromPaymentMethodPaypal(val PaymentMethodPaypal) InvoiceEventPayment2 { + return InvoiceEventPayment2{value: &val} +} diff --git a/models/invoice_issued.go b/models/invoice_issued.go new file mode 100644 index 00000000..6e6e322c --- /dev/null +++ b/models/invoice_issued.go @@ -0,0 +1,172 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// InvoiceIssued represents a InvoiceIssued struct. +type InvoiceIssued struct { + Uid string `json:"uid"` + Number string `json:"number"` + Role string `json:"role"` + DueDate time.Time `json:"due_date"` + IssueDate time.Time `json:"issue_date"` + PaidDate time.Time `json:"paid_date"` + DueAmount string `json:"due_amount"` + PaidAmount string `json:"paid_amount"` + TaxAmount string `json:"tax_amount"` + RefundAmount string `json:"refund_amount"` + TotalAmount string `json:"total_amount"` + StatusAmount string `json:"status_amount"` + ProductName string `json:"product_name"` + ConsolidationLevel string `json:"consolidation_level"` + LineItems []InvoiceLineItemEventData `json:"line_items"` +} + +// MarshalJSON implements the json.Marshaler interface for InvoiceIssued. +// It customizes the JSON marshaling process for InvoiceIssued objects. +func (i *InvoiceIssued) MarshalJSON() ( + []byte, + error) { + return json.Marshal(i.toMap()) +} + +// toMap converts the InvoiceIssued object to a map representation for JSON marshaling. +func (i *InvoiceIssued) toMap() map[string]any { + structMap := make(map[string]any) + structMap["uid"] = i.Uid + structMap["number"] = i.Number + structMap["role"] = i.Role + structMap["due_date"] = i.DueDate.Format(DEFAULT_DATE) + structMap["issue_date"] = i.IssueDate.Format(DEFAULT_DATE) + structMap["paid_date"] = i.PaidDate.Format(DEFAULT_DATE) + structMap["due_amount"] = i.DueAmount + structMap["paid_amount"] = i.PaidAmount + structMap["tax_amount"] = i.TaxAmount + structMap["refund_amount"] = i.RefundAmount + structMap["total_amount"] = i.TotalAmount + structMap["status_amount"] = i.StatusAmount + structMap["product_name"] = i.ProductName + structMap["consolidation_level"] = i.ConsolidationLevel + structMap["line_items"] = i.LineItems + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceIssued. +// It customizes the JSON unmarshaling process for InvoiceIssued objects. +func (i *InvoiceIssued) UnmarshalJSON(input []byte) error { + var temp invoiceIssued + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + i.Uid = *temp.Uid + i.Number = *temp.Number + i.Role = *temp.Role + DueDateVal, err := time.Parse(DEFAULT_DATE, *temp.DueDate) + if err != nil { + log.Fatalf("Cannot Parse due_date as % s format.", DEFAULT_DATE) + } + i.DueDate = DueDateVal + IssueDateVal, err := time.Parse(DEFAULT_DATE, *temp.IssueDate) + if err != nil { + log.Fatalf("Cannot Parse issue_date as % s format.", DEFAULT_DATE) + } + i.IssueDate = IssueDateVal + PaidDateVal, err := time.Parse(DEFAULT_DATE, *temp.PaidDate) + if err != nil { + log.Fatalf("Cannot Parse paid_date as % s format.", DEFAULT_DATE) + } + i.PaidDate = PaidDateVal + i.DueAmount = *temp.DueAmount + i.PaidAmount = *temp.PaidAmount + i.TaxAmount = *temp.TaxAmount + i.RefundAmount = *temp.RefundAmount + i.TotalAmount = *temp.TotalAmount + i.StatusAmount = *temp.StatusAmount + i.ProductName = *temp.ProductName + i.ConsolidationLevel = *temp.ConsolidationLevel + i.LineItems = *temp.LineItems + return nil +} + +// TODO +type invoiceIssued struct { + Uid *string `json:"uid"` + Number *string `json:"number"` + Role *string `json:"role"` + DueDate *string `json:"due_date"` + IssueDate *string `json:"issue_date"` + PaidDate *string `json:"paid_date"` + DueAmount *string `json:"due_amount"` + PaidAmount *string `json:"paid_amount"` + TaxAmount *string `json:"tax_amount"` + RefundAmount *string `json:"refund_amount"` + TotalAmount *string `json:"total_amount"` + StatusAmount *string `json:"status_amount"` + ProductName *string `json:"product_name"` + ConsolidationLevel *string `json:"consolidation_level"` + LineItems *[]InvoiceLineItemEventData `json:"line_items"` +} + +func (i *invoiceIssued) validate() error { + var errs []string + if i.Uid == nil { + errs = append(errs, "required field `uid` is missing for type `Invoice Issued`") + } + if i.Number == nil { + errs = append(errs, "required field `number` is missing for type `Invoice Issued`") + } + if i.Role == nil { + errs = append(errs, "required field `role` is missing for type `Invoice Issued`") + } + if i.DueDate == nil { + errs = append(errs, "required field `due_date` is missing for type `Invoice Issued`") + } + if i.IssueDate == nil { + errs = append(errs, "required field `issue_date` is missing for type `Invoice Issued`") + } + if i.PaidDate == nil { + errs = append(errs, "required field `paid_date` is missing for type `Invoice Issued`") + } + if i.DueAmount == nil { + errs = append(errs, "required field `due_amount` is missing for type `Invoice Issued`") + } + if i.PaidAmount == nil { + errs = append(errs, "required field `paid_amount` is missing for type `Invoice Issued`") + } + if i.TaxAmount == nil { + errs = append(errs, "required field `tax_amount` is missing for type `Invoice Issued`") + } + if i.RefundAmount == nil { + errs = append(errs, "required field `refund_amount` is missing for type `Invoice Issued`") + } + if i.TotalAmount == nil { + errs = append(errs, "required field `total_amount` is missing for type `Invoice Issued`") + } + if i.StatusAmount == nil { + errs = append(errs, "required field `status_amount` is missing for type `Invoice Issued`") + } + if i.ProductName == nil { + errs = append(errs, "required field `product_name` is missing for type `Invoice Issued`") + } + if i.ConsolidationLevel == nil { + errs = append(errs, "required field `consolidation_level` is missing for type `Invoice Issued`") + } + if i.LineItems == nil { + errs = append(errs, "required field `line_items` is missing for type `Invoice Issued`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/invoice_line_item.go b/models/invoice_line_item.go index 4469664e..31565c8a 100644 --- a/models/invoice_line_item.go +++ b/models/invoice_line_item.go @@ -1,212 +1,238 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // InvoiceLineItem represents a InvoiceLineItem struct. type InvoiceLineItem struct { - // Unique identifier for the line item. Useful when cross-referencing the line against individual discounts in the `discounts` or `taxes` lists. - Uid *string `json:"uid,omitempty"` - // A short descriptor for the charge or item represented by this line. - Title *string `json:"title,omitempty"` - // Detailed description for the charge or item represented by this line. May include proration details in plain text. - // Note: this string may contain line breaks that are hints for the best display format on the invoice. - Description *string `json:"description,omitempty"` - // The quantity or count of units billed by the line item. - // This is a decimal number represented as a string. (See "About Decimal Numbers".) - Quantity *string `json:"quantity,omitempty"` - // The price per unit for the line item. - // When tiered pricing was used (i.e. not every unit was actually priced at the same price) this will be the blended average cost per unit and the `tiered_unit_price` field will be set to `true`. - UnitPrice *string `json:"unit_price,omitempty"` - // The line subtotal, generally calculated as `quantity * unit_price`. This is the canonical amount of record for the line - when rounding differences are in play, `subtotal_amount` takes precedence over the value derived from `quantity * unit_price` (which may not have the proper precision to exactly equal this amount). - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - // The approximate discount applied to just this line. - // The value is approximated in cases where rounding errors make it difficult to apportion exactly a total discount among many lines. Several lines may have been summed prior to applying the discount to arrive at `discount_amount` for the invoice - backing that out to the discount on a single line may introduce rounding or precision errors. - DiscountAmount *string `json:"discount_amount,omitempty"` - // The approximate tax applied to just this line. - // The value is approximated in cases where rounding errors make it difficult to apportion exactly a total tax among many lines. Several lines may have been summed prior to applying the tax rate to arrive at `tax_amount` for the invoice - backing that out to the tax on a single line may introduce rounding or precision errors. - TaxAmount *string `json:"tax_amount,omitempty"` - // The non-canonical total amount for the line. - // `subtotal_amount` is the canonical amount for a line. The invoice `total_amount` is derived from the sum of the line `subtotal_amount`s and discounts or taxes applied thereafter. Therefore, due to rounding or precision errors, the sum of line `total_amount`s may not equal the invoice `total_amount`. - TotalAmount *string `json:"total_amount,omitempty"` - // When `true`, indicates that the actual pricing scheme for the line was tiered, so the `unit_price` shown is the blended average for all units. - TieredUnitPrice *bool `json:"tiered_unit_price,omitempty"` - // Start date for the period covered by this line. The format is `"YYYY-MM-DD"`. - // * For periodic charges paid in advance, this date will match the billing date, and the end date will be in the future. - // * For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the previous billing, and the end date will be the current billing date. - // * For non-periodic charges, this date and the end date will match. - PeriodRangeStart *time.Time `json:"period_range_start,omitempty"` - // End date for the period covered by this line. The format is `"YYYY-MM-DD"`. - // * For periodic charges paid in advance, this date will match the next (future) billing date. - // * For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the current billing date. - // * For non-periodic charges, this date and the start date will match. - PeriodRangeEnd *time.Time `json:"period_range_end,omitempty"` - TransactionId *int `json:"transaction_id,omitempty"` - // The ID of the product subscribed when the charge was made. - // This may be set even for component charges, so true product-only (non-component) charges will also have a nil `component_id`. - ProductId Optional[int] `json:"product_id"` - // The version of the product subscribed when the charge was made. - ProductVersion Optional[int] `json:"product_version"` - // The ID of the component being billed. Will be `nil` for non-component charges. - ComponentId Optional[int] `json:"component_id"` - // The price point ID of the component being billed. Will be `nil` for non-component charges. - PricePointId Optional[int] `json:"price_point_id"` - Hide *bool `json:"hide,omitempty"` - ComponentCostData Optional[InvoiceLineItemComponentCostData] `json:"component_cost_data"` - // The price point ID of the line item's product - ProductPricePointId Optional[int] `json:"product_price_point_id"` - CustomItem *bool `json:"custom_item,omitempty"` - Kind *string `json:"kind,omitempty"` + // Unique identifier for the line item. Useful when cross-referencing the line against individual discounts in the `discounts` or `taxes` lists. + Uid *string `json:"uid,omitempty"` + // A short descriptor for the charge or item represented by this line. + Title *string `json:"title,omitempty"` + // Detailed description for the charge or item represented by this line. May include proration details in plain text. + // Note: this string may contain line breaks that are hints for the best display format on the invoice. + Description *string `json:"description,omitempty"` + // The quantity or count of units billed by the line item. + // This is a decimal number represented as a string. (See "About Decimal Numbers".) + Quantity *string `json:"quantity,omitempty"` + // The price per unit for the line item. + // When tiered pricing was used (i.e. not every unit was actually priced at the same price) this will be the blended average cost per unit and the `tiered_unit_price` field will be set to `true`. + UnitPrice *string `json:"unit_price,omitempty"` + // The line subtotal, generally calculated as `quantity * unit_price`. This is the canonical amount of record for the line - when rounding differences are in play, `subtotal_amount` takes precedence over the value derived from `quantity * unit_price` (which may not have the proper precision to exactly equal this amount). + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + // The approximate discount applied to just this line. + // The value is approximated in cases where rounding errors make it difficult to apportion exactly a total discount among many lines. Several lines may have been summed prior to applying the discount to arrive at `discount_amount` for the invoice - backing that out to the discount on a single line may introduce rounding or precision errors. + DiscountAmount *string `json:"discount_amount,omitempty"` + // The approximate tax applied to just this line. + // The value is approximated in cases where rounding errors make it difficult to apportion exactly a total tax among many lines. Several lines may have been summed prior to applying the tax rate to arrive at `tax_amount` for the invoice - backing that out to the tax on a single line may introduce rounding or precision errors. + TaxAmount *string `json:"tax_amount,omitempty"` + // The non-canonical total amount for the line. + // `subtotal_amount` is the canonical amount for a line. The invoice `total_amount` is derived from the sum of the line `subtotal_amount`s and discounts or taxes applied thereafter. Therefore, due to rounding or precision errors, the sum of line `total_amount`s may not equal the invoice `total_amount`. + TotalAmount *string `json:"total_amount,omitempty"` + // When `true`, indicates that the actual pricing scheme for the line was tiered, so the `unit_price` shown is the blended average for all units. + TieredUnitPrice *bool `json:"tiered_unit_price,omitempty"` + // Start date for the period covered by this line. The format is `"YYYY-MM-DD"`. + // * For periodic charges paid in advance, this date will match the billing date, and the end date will be in the future. + // * For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the previous billing, and the end date will be the current billing date. + // * For non-periodic charges, this date and the end date will match. + PeriodRangeStart *time.Time `json:"period_range_start,omitempty"` + // End date for the period covered by this line. The format is `"YYYY-MM-DD"`. + // * For periodic charges paid in advance, this date will match the next (future) billing date. + // * For periodic charges paid in arrears (e.g. metered charges), this date will be the date of the current billing date. + // * For non-periodic charges, this date and the start date will match. + PeriodRangeEnd *time.Time `json:"period_range_end,omitempty"` + TransactionId *int `json:"transaction_id,omitempty"` + // The ID of the product subscribed when the charge was made. + // This may be set even for component charges, so true product-only (non-component) charges will also have a nil `component_id`. + ProductId Optional[int] `json:"product_id"` + // The version of the product subscribed when the charge was made. + ProductVersion Optional[int] `json:"product_version"` + // The ID of the component being billed. Will be `nil` for non-component charges. + ComponentId Optional[int] `json:"component_id"` + // The price point ID of the component being billed. Will be `nil` for non-component charges. + PricePointId Optional[int] `json:"price_point_id"` + Hide *bool `json:"hide,omitempty"` + ComponentCostData Optional[InvoiceLineItemComponentCostData2] `json:"component_cost_data"` + // The price point ID of the line item's product + ProductPricePointId Optional[int] `json:"product_price_point_id"` + CustomItem *bool `json:"custom_item,omitempty"` + Kind *string `json:"kind,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceLineItem. +// MarshalJSON implements the json.Marshaler interface for InvoiceLineItem. // It customizes the JSON marshaling process for InvoiceLineItem objects. func (i *InvoiceLineItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceLineItem object to a map representation for JSON marshaling. func (i *InvoiceLineItem) toMap() map[string]any { - structMap := make(map[string]any) - if i.Uid != nil { - structMap["uid"] = i.Uid - } - if i.Title != nil { - structMap["title"] = i.Title - } - if i.Description != nil { - structMap["description"] = i.Description - } - if i.Quantity != nil { - structMap["quantity"] = i.Quantity - } - if i.UnitPrice != nil { - structMap["unit_price"] = i.UnitPrice - } - if i.SubtotalAmount != nil { - structMap["subtotal_amount"] = i.SubtotalAmount - } - if i.DiscountAmount != nil { - structMap["discount_amount"] = i.DiscountAmount - } - if i.TaxAmount != nil { - structMap["tax_amount"] = i.TaxAmount - } - if i.TotalAmount != nil { - structMap["total_amount"] = i.TotalAmount - } - if i.TieredUnitPrice != nil { - structMap["tiered_unit_price"] = i.TieredUnitPrice - } - if i.PeriodRangeStart != nil { - structMap["period_range_start"] = i.PeriodRangeStart.Format(DEFAULT_DATE) - } - if i.PeriodRangeEnd != nil { - structMap["period_range_end"] = i.PeriodRangeEnd.Format(DEFAULT_DATE) - } - if i.TransactionId != nil { - structMap["transaction_id"] = i.TransactionId - } - if i.ProductId.IsValueSet() { - structMap["product_id"] = i.ProductId.Value() - } - if i.ProductVersion.IsValueSet() { - structMap["product_version"] = i.ProductVersion.Value() - } - if i.ComponentId.IsValueSet() { - structMap["component_id"] = i.ComponentId.Value() - } - if i.PricePointId.IsValueSet() { - structMap["price_point_id"] = i.PricePointId.Value() - } - if i.Hide != nil { - structMap["hide"] = i.Hide - } - if i.ComponentCostData.IsValueSet() { - structMap["component_cost_data"] = i.ComponentCostData.Value() - } - if i.ProductPricePointId.IsValueSet() { - structMap["product_price_point_id"] = i.ProductPricePointId.Value() - } - if i.CustomItem != nil { - structMap["custom_item"] = i.CustomItem - } - if i.Kind != nil { - structMap["kind"] = i.Kind - } - return structMap + structMap := make(map[string]any) + if i.Uid != nil { + structMap["uid"] = i.Uid + } + if i.Title != nil { + structMap["title"] = i.Title + } + if i.Description != nil { + structMap["description"] = i.Description + } + if i.Quantity != nil { + structMap["quantity"] = i.Quantity + } + if i.UnitPrice != nil { + structMap["unit_price"] = i.UnitPrice + } + if i.SubtotalAmount != nil { + structMap["subtotal_amount"] = i.SubtotalAmount + } + if i.DiscountAmount != nil { + structMap["discount_amount"] = i.DiscountAmount + } + if i.TaxAmount != nil { + structMap["tax_amount"] = i.TaxAmount + } + if i.TotalAmount != nil { + structMap["total_amount"] = i.TotalAmount + } + if i.TieredUnitPrice != nil { + structMap["tiered_unit_price"] = i.TieredUnitPrice + } + if i.PeriodRangeStart != nil { + structMap["period_range_start"] = i.PeriodRangeStart.Format(DEFAULT_DATE) + } + if i.PeriodRangeEnd != nil { + structMap["period_range_end"] = i.PeriodRangeEnd.Format(DEFAULT_DATE) + } + if i.TransactionId != nil { + structMap["transaction_id"] = i.TransactionId + } + if i.ProductId.IsValueSet() { + if i.ProductId.Value() != nil { + structMap["product_id"] = i.ProductId.Value() + } else { + structMap["product_id"] = nil + } + } + if i.ProductVersion.IsValueSet() { + if i.ProductVersion.Value() != nil { + structMap["product_version"] = i.ProductVersion.Value() + } else { + structMap["product_version"] = nil + } + } + if i.ComponentId.IsValueSet() { + if i.ComponentId.Value() != nil { + structMap["component_id"] = i.ComponentId.Value() + } else { + structMap["component_id"] = nil + } + } + if i.PricePointId.IsValueSet() { + if i.PricePointId.Value() != nil { + structMap["price_point_id"] = i.PricePointId.Value() + } else { + structMap["price_point_id"] = nil + } + } + if i.Hide != nil { + structMap["hide"] = i.Hide + } + if i.ComponentCostData.IsValueSet() { + if i.ComponentCostData.Value() != nil { + structMap["component_cost_data"] = i.ComponentCostData.Value().toMap() + } else { + structMap["component_cost_data"] = nil + } + } + if i.ProductPricePointId.IsValueSet() { + if i.ProductPricePointId.Value() != nil { + structMap["product_price_point_id"] = i.ProductPricePointId.Value() + } else { + structMap["product_price_point_id"] = nil + } + } + if i.CustomItem != nil { + structMap["custom_item"] = i.CustomItem + } + if i.Kind != nil { + structMap["kind"] = i.Kind + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceLineItem. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceLineItem. // It customizes the JSON unmarshaling process for InvoiceLineItem objects. func (i *InvoiceLineItem) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Title *string `json:"title,omitempty"` - Description *string `json:"description,omitempty"` - Quantity *string `json:"quantity,omitempty"` - UnitPrice *string `json:"unit_price,omitempty"` - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - TotalAmount *string `json:"total_amount,omitempty"` - TieredUnitPrice *bool `json:"tiered_unit_price,omitempty"` - PeriodRangeStart *string `json:"period_range_start,omitempty"` - PeriodRangeEnd *string `json:"period_range_end,omitempty"` - TransactionId *int `json:"transaction_id,omitempty"` - ProductId Optional[int] `json:"product_id"` - ProductVersion Optional[int] `json:"product_version"` - ComponentId Optional[int] `json:"component_id"` - PricePointId Optional[int] `json:"price_point_id"` - Hide *bool `json:"hide,omitempty"` - ComponentCostData Optional[InvoiceLineItemComponentCostData] `json:"component_cost_data"` - ProductPricePointId Optional[int] `json:"product_price_point_id"` - CustomItem *bool `json:"custom_item,omitempty"` - Kind *string `json:"kind,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Uid = temp.Uid - i.Title = temp.Title - i.Description = temp.Description - i.Quantity = temp.Quantity - i.UnitPrice = temp.UnitPrice - i.SubtotalAmount = temp.SubtotalAmount - i.DiscountAmount = temp.DiscountAmount - i.TaxAmount = temp.TaxAmount - i.TotalAmount = temp.TotalAmount - i.TieredUnitPrice = temp.TieredUnitPrice - if temp.PeriodRangeStart != nil { - PeriodRangeStartVal, err := time.Parse(DEFAULT_DATE, *temp.PeriodRangeStart) - if err != nil { - log.Fatalf("Cannot Parse period_range_start as % s format.", DEFAULT_DATE) - } - i.PeriodRangeStart = &PeriodRangeStartVal - } - if temp.PeriodRangeEnd != nil { - PeriodRangeEndVal, err := time.Parse(DEFAULT_DATE, *temp.PeriodRangeEnd) - if err != nil { - log.Fatalf("Cannot Parse period_range_end as % s format.", DEFAULT_DATE) - } - i.PeriodRangeEnd = &PeriodRangeEndVal - } - i.TransactionId = temp.TransactionId - i.ProductId = temp.ProductId - i.ProductVersion = temp.ProductVersion - i.ComponentId = temp.ComponentId - i.PricePointId = temp.PricePointId - i.Hide = temp.Hide - i.ComponentCostData = temp.ComponentCostData - i.ProductPricePointId = temp.ProductPricePointId - i.CustomItem = temp.CustomItem - i.Kind = temp.Kind - return nil + var temp invoiceLineItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Uid = temp.Uid + i.Title = temp.Title + i.Description = temp.Description + i.Quantity = temp.Quantity + i.UnitPrice = temp.UnitPrice + i.SubtotalAmount = temp.SubtotalAmount + i.DiscountAmount = temp.DiscountAmount + i.TaxAmount = temp.TaxAmount + i.TotalAmount = temp.TotalAmount + i.TieredUnitPrice = temp.TieredUnitPrice + if temp.PeriodRangeStart != nil { + PeriodRangeStartVal, err := time.Parse(DEFAULT_DATE, *temp.PeriodRangeStart) + if err != nil { + log.Fatalf("Cannot Parse period_range_start as % s format.", DEFAULT_DATE) + } + i.PeriodRangeStart = &PeriodRangeStartVal + } + if temp.PeriodRangeEnd != nil { + PeriodRangeEndVal, err := time.Parse(DEFAULT_DATE, *temp.PeriodRangeEnd) + if err != nil { + log.Fatalf("Cannot Parse period_range_end as % s format.", DEFAULT_DATE) + } + i.PeriodRangeEnd = &PeriodRangeEndVal + } + i.TransactionId = temp.TransactionId + i.ProductId = temp.ProductId + i.ProductVersion = temp.ProductVersion + i.ComponentId = temp.ComponentId + i.PricePointId = temp.PricePointId + i.Hide = temp.Hide + i.ComponentCostData = temp.ComponentCostData + i.ProductPricePointId = temp.ProductPricePointId + i.CustomItem = temp.CustomItem + i.Kind = temp.Kind + return nil +} + +// TODO +type invoiceLineItem struct { + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + Description *string `json:"description,omitempty"` + Quantity *string `json:"quantity,omitempty"` + UnitPrice *string `json:"unit_price,omitempty"` + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + TotalAmount *string `json:"total_amount,omitempty"` + TieredUnitPrice *bool `json:"tiered_unit_price,omitempty"` + PeriodRangeStart *string `json:"period_range_start,omitempty"` + PeriodRangeEnd *string `json:"period_range_end,omitempty"` + TransactionId *int `json:"transaction_id,omitempty"` + ProductId Optional[int] `json:"product_id"` + ProductVersion Optional[int] `json:"product_version"` + ComponentId Optional[int] `json:"component_id"` + PricePointId Optional[int] `json:"price_point_id"` + Hide *bool `json:"hide,omitempty"` + ComponentCostData Optional[InvoiceLineItemComponentCostData2] `json:"component_cost_data"` + ProductPricePointId Optional[int] `json:"product_price_point_id"` + CustomItem *bool `json:"custom_item,omitempty"` + Kind *string `json:"kind,omitempty"` } diff --git a/models/invoice_line_item_component_cost_data.go b/models/invoice_line_item_component_cost_data.go index a391e31a..bba7b8c0 100644 --- a/models/invoice_line_item_component_cost_data.go +++ b/models/invoice_line_item_component_cost_data.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoiceLineItemComponentCostData represents a InvoiceLineItemComponentCostData struct. type InvoiceLineItemComponentCostData struct { - Rates []ComponentCostData `json:"rates,omitempty"` + Rates []ComponentCostData `json:"rates,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceLineItemComponentCostData. +// MarshalJSON implements the json.Marshaler interface for InvoiceLineItemComponentCostData. // It customizes the JSON marshaling process for InvoiceLineItemComponentCostData objects. func (i *InvoiceLineItemComponentCostData) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceLineItemComponentCostData object to a map representation for JSON marshaling. func (i *InvoiceLineItemComponentCostData) toMap() map[string]any { - structMap := make(map[string]any) - if i.Rates != nil { - structMap["rates"] = i.Rates - } - return structMap + structMap := make(map[string]any) + if i.Rates != nil { + structMap["rates"] = i.Rates + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceLineItemComponentCostData. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceLineItemComponentCostData. // It customizes the JSON unmarshaling process for InvoiceLineItemComponentCostData objects. func (i *InvoiceLineItemComponentCostData) UnmarshalJSON(input []byte) error { - temp := &struct { - Rates []ComponentCostData `json:"rates,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Rates = temp.Rates - return nil + var temp invoiceLineItemComponentCostData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Rates = temp.Rates + return nil +} + +// TODO +type invoiceLineItemComponentCostData struct { + Rates []ComponentCostData `json:"rates,omitempty"` } diff --git a/models/invoice_line_item_component_cost_data_2.go b/models/invoice_line_item_component_cost_data_2.go new file mode 100644 index 00000000..b39c9769 --- /dev/null +++ b/models/invoice_line_item_component_cost_data_2.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// InvoiceLineItemComponentCostData2 represents a InvoiceLineItemComponentCostData2 struct. +// This is a container for one-of cases. +type InvoiceLineItemComponentCostData2 struct { + value any + isInvoiceLineItemComponentCostData bool +} + +// String converts the InvoiceLineItemComponentCostData2 object to a string representation. +func (i InvoiceLineItemComponentCostData2) String() string { + if bytes, err := json.Marshal(i.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for InvoiceLineItemComponentCostData2. +// It customizes the JSON marshaling process for InvoiceLineItemComponentCostData2 objects. +func (i *InvoiceLineItemComponentCostData2) MarshalJSON() ( + []byte, + error) { + if i.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.InvoiceLineItemComponentCostData2Container.From*` functions to initialize the InvoiceLineItemComponentCostData2 object.") + } + return json.Marshal(i.toMap()) +} + +// toMap converts the InvoiceLineItemComponentCostData2 object to a map representation for JSON marshaling. +func (i *InvoiceLineItemComponentCostData2) toMap() any { + switch obj := i.value.(type) { + case *InvoiceLineItemComponentCostData: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceLineItemComponentCostData2. +// It customizes the JSON unmarshaling process for InvoiceLineItemComponentCostData2 objects. +func (i *InvoiceLineItemComponentCostData2) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&InvoiceLineItemComponentCostData{}, false, &i.isInvoiceLineItemComponentCostData), + ) + + i.value = result + return err +} + +func (i *InvoiceLineItemComponentCostData2) AsInvoiceLineItemComponentCostData() ( + *InvoiceLineItemComponentCostData, + bool) { + if !i.isInvoiceLineItemComponentCostData { + return nil, false + } + return i.value.(*InvoiceLineItemComponentCostData), true +} + +// internalInvoiceLineItemComponentCostData2 represents a invoiceLineItemComponentCostData2 struct. +// This is a container for one-of cases. +type internalInvoiceLineItemComponentCostData2 struct{} + +var InvoiceLineItemComponentCostData2Container internalInvoiceLineItemComponentCostData2 + +func (i *internalInvoiceLineItemComponentCostData2) FromInvoiceLineItemComponentCostData(val InvoiceLineItemComponentCostData) InvoiceLineItemComponentCostData2 { + return InvoiceLineItemComponentCostData2{value: &val} +} diff --git a/models/invoice_line_item_event_data.go b/models/invoice_line_item_event_data.go new file mode 100644 index 00000000..a0712d03 --- /dev/null +++ b/models/invoice_line_item_event_data.go @@ -0,0 +1,190 @@ +package models + +import ( + "encoding/json" +) + +// InvoiceLineItemEventData represents a InvoiceLineItemEventData struct. +type InvoiceLineItemEventData struct { + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + Description *string `json:"description,omitempty"` + Quantity *int `json:"quantity,omitempty"` + QuantityDelta Optional[int] `json:"quantity_delta"` + UnitPrice *string `json:"unit_price,omitempty"` + PeriodRangeStart *string `json:"period_range_start,omitempty"` + PeriodRangeEnd *string `json:"period_range_end,omitempty"` + Amount *string `json:"amount,omitempty"` + LineReferences *string `json:"line_references,omitempty"` + PricingDetailsIndex Optional[int] `json:"pricing_details_index"` + PricingDetails []InvoiceLineItemPricingDetail `json:"pricing_details,omitempty"` + TaxCode Optional[string] `json:"tax_code"` + TaxAmount *string `json:"tax_amount,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductPricePointId Optional[int] `json:"product_price_point_id"` + PricePointId Optional[int] `json:"price_point_id"` + ComponentId Optional[int] `json:"component_id"` + BillingScheduleItemId Optional[int] `json:"billing_schedule_item_id"` + CustomItem Optional[bool] `json:"custom_item"` +} + +// MarshalJSON implements the json.Marshaler interface for InvoiceLineItemEventData. +// It customizes the JSON marshaling process for InvoiceLineItemEventData objects. +func (i *InvoiceLineItemEventData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(i.toMap()) +} + +// toMap converts the InvoiceLineItemEventData object to a map representation for JSON marshaling. +func (i *InvoiceLineItemEventData) toMap() map[string]any { + structMap := make(map[string]any) + if i.Uid != nil { + structMap["uid"] = i.Uid + } + if i.Title != nil { + structMap["title"] = i.Title + } + if i.Description != nil { + structMap["description"] = i.Description + } + if i.Quantity != nil { + structMap["quantity"] = i.Quantity + } + if i.QuantityDelta.IsValueSet() { + if i.QuantityDelta.Value() != nil { + structMap["quantity_delta"] = i.QuantityDelta.Value() + } else { + structMap["quantity_delta"] = nil + } + } + if i.UnitPrice != nil { + structMap["unit_price"] = i.UnitPrice + } + if i.PeriodRangeStart != nil { + structMap["period_range_start"] = i.PeriodRangeStart + } + if i.PeriodRangeEnd != nil { + structMap["period_range_end"] = i.PeriodRangeEnd + } + if i.Amount != nil { + structMap["amount"] = i.Amount + } + if i.LineReferences != nil { + structMap["line_references"] = i.LineReferences + } + if i.PricingDetailsIndex.IsValueSet() { + if i.PricingDetailsIndex.Value() != nil { + structMap["pricing_details_index"] = i.PricingDetailsIndex.Value() + } else { + structMap["pricing_details_index"] = nil + } + } + if i.PricingDetails != nil { + structMap["pricing_details"] = i.PricingDetails + } + if i.TaxCode.IsValueSet() { + if i.TaxCode.Value() != nil { + structMap["tax_code"] = i.TaxCode.Value() + } else { + structMap["tax_code"] = nil + } + } + if i.TaxAmount != nil { + structMap["tax_amount"] = i.TaxAmount + } + if i.ProductId != nil { + structMap["product_id"] = i.ProductId + } + if i.ProductPricePointId.IsValueSet() { + if i.ProductPricePointId.Value() != nil { + structMap["product_price_point_id"] = i.ProductPricePointId.Value() + } else { + structMap["product_price_point_id"] = nil + } + } + if i.PricePointId.IsValueSet() { + if i.PricePointId.Value() != nil { + structMap["price_point_id"] = i.PricePointId.Value() + } else { + structMap["price_point_id"] = nil + } + } + if i.ComponentId.IsValueSet() { + if i.ComponentId.Value() != nil { + structMap["component_id"] = i.ComponentId.Value() + } else { + structMap["component_id"] = nil + } + } + if i.BillingScheduleItemId.IsValueSet() { + if i.BillingScheduleItemId.Value() != nil { + structMap["billing_schedule_item_id"] = i.BillingScheduleItemId.Value() + } else { + structMap["billing_schedule_item_id"] = nil + } + } + if i.CustomItem.IsValueSet() { + if i.CustomItem.Value() != nil { + structMap["custom_item"] = i.CustomItem.Value() + } else { + structMap["custom_item"] = nil + } + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceLineItemEventData. +// It customizes the JSON unmarshaling process for InvoiceLineItemEventData objects. +func (i *InvoiceLineItemEventData) UnmarshalJSON(input []byte) error { + var temp invoiceLineItemEventData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Uid = temp.Uid + i.Title = temp.Title + i.Description = temp.Description + i.Quantity = temp.Quantity + i.QuantityDelta = temp.QuantityDelta + i.UnitPrice = temp.UnitPrice + i.PeriodRangeStart = temp.PeriodRangeStart + i.PeriodRangeEnd = temp.PeriodRangeEnd + i.Amount = temp.Amount + i.LineReferences = temp.LineReferences + i.PricingDetailsIndex = temp.PricingDetailsIndex + i.PricingDetails = temp.PricingDetails + i.TaxCode = temp.TaxCode + i.TaxAmount = temp.TaxAmount + i.ProductId = temp.ProductId + i.ProductPricePointId = temp.ProductPricePointId + i.PricePointId = temp.PricePointId + i.ComponentId = temp.ComponentId + i.BillingScheduleItemId = temp.BillingScheduleItemId + i.CustomItem = temp.CustomItem + return nil +} + +// TODO +type invoiceLineItemEventData struct { + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + Description *string `json:"description,omitempty"` + Quantity *int `json:"quantity,omitempty"` + QuantityDelta Optional[int] `json:"quantity_delta"` + UnitPrice *string `json:"unit_price,omitempty"` + PeriodRangeStart *string `json:"period_range_start,omitempty"` + PeriodRangeEnd *string `json:"period_range_end,omitempty"` + Amount *string `json:"amount,omitempty"` + LineReferences *string `json:"line_references,omitempty"` + PricingDetailsIndex Optional[int] `json:"pricing_details_index"` + PricingDetails []InvoiceLineItemPricingDetail `json:"pricing_details,omitempty"` + TaxCode Optional[string] `json:"tax_code"` + TaxAmount *string `json:"tax_amount,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductPricePointId Optional[int] `json:"product_price_point_id"` + PricePointId Optional[int] `json:"price_point_id"` + ComponentId Optional[int] `json:"component_id"` + BillingScheduleItemId Optional[int] `json:"billing_schedule_item_id"` + CustomItem Optional[bool] `json:"custom_item"` +} diff --git a/models/invoice_line_item_pricing_detail.go b/models/invoice_line_item_pricing_detail.go new file mode 100644 index 00000000..28cd969f --- /dev/null +++ b/models/invoice_line_item_pricing_detail.go @@ -0,0 +1,50 @@ +package models + +import ( + "encoding/json" +) + +// InvoiceLineItemPricingDetail represents a InvoiceLineItemPricingDetail struct. +type InvoiceLineItemPricingDetail struct { + Label *string `json:"label,omitempty"` + Amount *string `json:"amount,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for InvoiceLineItemPricingDetail. +// It customizes the JSON marshaling process for InvoiceLineItemPricingDetail objects. +func (i *InvoiceLineItemPricingDetail) MarshalJSON() ( + []byte, + error) { + return json.Marshal(i.toMap()) +} + +// toMap converts the InvoiceLineItemPricingDetail object to a map representation for JSON marshaling. +func (i *InvoiceLineItemPricingDetail) toMap() map[string]any { + structMap := make(map[string]any) + if i.Label != nil { + structMap["label"] = i.Label + } + if i.Amount != nil { + structMap["amount"] = i.Amount + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceLineItemPricingDetail. +// It customizes the JSON unmarshaling process for InvoiceLineItemPricingDetail objects. +func (i *InvoiceLineItemPricingDetail) UnmarshalJSON(input []byte) error { + var temp invoiceLineItemPricingDetail + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Label = temp.Label + i.Amount = temp.Amount + return nil +} + +// TODO +type invoiceLineItemPricingDetail struct { + Label *string `json:"label,omitempty"` + Amount *string `json:"amount,omitempty"` +} diff --git a/models/invoice_payer.go b/models/invoice_payer.go index 1a93b0f0..80cf97cf 100644 --- a/models/invoice_payer.go +++ b/models/invoice_payer.go @@ -1,72 +1,82 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoicePayer represents a InvoicePayer struct. type InvoicePayer struct { - ChargifyId *int `json:"chargify_id,omitempty"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Organization Optional[string] `json:"organization"` - Email *string `json:"email,omitempty"` - VatNumber Optional[string] `json:"vat_number"` + ChargifyId *int `json:"chargify_id,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Organization Optional[string] `json:"organization"` + Email *string `json:"email,omitempty"` + VatNumber Optional[string] `json:"vat_number"` } -// MarshalJSON implements the json.Marshaler interface for InvoicePayer. +// MarshalJSON implements the json.Marshaler interface for InvoicePayer. // It customizes the JSON marshaling process for InvoicePayer objects. func (i *InvoicePayer) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoicePayer object to a map representation for JSON marshaling. func (i *InvoicePayer) toMap() map[string]any { - structMap := make(map[string]any) - if i.ChargifyId != nil { - structMap["chargify_id"] = i.ChargifyId - } - if i.FirstName != nil { - structMap["first_name"] = i.FirstName - } - if i.LastName != nil { - structMap["last_name"] = i.LastName - } - if i.Organization.IsValueSet() { - structMap["organization"] = i.Organization.Value() - } - if i.Email != nil { - structMap["email"] = i.Email - } - if i.VatNumber.IsValueSet() { - structMap["vat_number"] = i.VatNumber.Value() - } - return structMap + structMap := make(map[string]any) + if i.ChargifyId != nil { + structMap["chargify_id"] = i.ChargifyId + } + if i.FirstName != nil { + structMap["first_name"] = i.FirstName + } + if i.LastName != nil { + structMap["last_name"] = i.LastName + } + if i.Organization.IsValueSet() { + if i.Organization.Value() != nil { + structMap["organization"] = i.Organization.Value() + } else { + structMap["organization"] = nil + } + } + if i.Email != nil { + structMap["email"] = i.Email + } + if i.VatNumber.IsValueSet() { + if i.VatNumber.Value() != nil { + structMap["vat_number"] = i.VatNumber.Value() + } else { + structMap["vat_number"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePayer. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePayer. // It customizes the JSON unmarshaling process for InvoicePayer objects. func (i *InvoicePayer) UnmarshalJSON(input []byte) error { - temp := &struct { - ChargifyId *int `json:"chargify_id,omitempty"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Organization Optional[string] `json:"organization"` - Email *string `json:"email,omitempty"` - VatNumber Optional[string] `json:"vat_number"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.ChargifyId = temp.ChargifyId - i.FirstName = temp.FirstName - i.LastName = temp.LastName - i.Organization = temp.Organization - i.Email = temp.Email - i.VatNumber = temp.VatNumber - return nil + var temp invoicePayer + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.ChargifyId = temp.ChargifyId + i.FirstName = temp.FirstName + i.LastName = temp.LastName + i.Organization = temp.Organization + i.Email = temp.Email + i.VatNumber = temp.VatNumber + return nil +} + +// TODO +type invoicePayer struct { + ChargifyId *int `json:"chargify_id,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Organization Optional[string] `json:"organization"` + Email *string `json:"email,omitempty"` + VatNumber Optional[string] `json:"vat_number"` } diff --git a/models/invoice_payer_change.go b/models/invoice_payer_change.go index 483a66d9..85abb1b6 100644 --- a/models/invoice_payer_change.go +++ b/models/invoice_payer_change.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoicePayerChange represents a InvoicePayerChange struct. type InvoicePayerChange struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Organization *string `json:"organization,omitempty"` - Email *string `json:"email,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Organization *string `json:"organization,omitempty"` + Email *string `json:"email,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoicePayerChange. +// MarshalJSON implements the json.Marshaler interface for InvoicePayerChange. // It customizes the JSON marshaling process for InvoicePayerChange objects. func (i *InvoicePayerChange) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoicePayerChange object to a map representation for JSON marshaling. func (i *InvoicePayerChange) toMap() map[string]any { - structMap := make(map[string]any) - if i.FirstName != nil { - structMap["first_name"] = i.FirstName - } - if i.LastName != nil { - structMap["last_name"] = i.LastName - } - if i.Organization != nil { - structMap["organization"] = i.Organization - } - if i.Email != nil { - structMap["email"] = i.Email - } - return structMap + structMap := make(map[string]any) + if i.FirstName != nil { + structMap["first_name"] = i.FirstName + } + if i.LastName != nil { + structMap["last_name"] = i.LastName + } + if i.Organization != nil { + structMap["organization"] = i.Organization + } + if i.Email != nil { + structMap["email"] = i.Email + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePayerChange. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePayerChange. // It customizes the JSON unmarshaling process for InvoicePayerChange objects. func (i *InvoicePayerChange) UnmarshalJSON(input []byte) error { - temp := &struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Organization *string `json:"organization,omitempty"` - Email *string `json:"email,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.FirstName = temp.FirstName - i.LastName = temp.LastName - i.Organization = temp.Organization - i.Email = temp.Email - return nil + var temp invoicePayerChange + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.FirstName = temp.FirstName + i.LastName = temp.LastName + i.Organization = temp.Organization + i.Email = temp.Email + return nil +} + +// TODO +type invoicePayerChange struct { + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Organization *string `json:"organization,omitempty"` + Email *string `json:"email,omitempty"` } diff --git a/models/invoice_payment.go b/models/invoice_payment.go index ebbac256..6b175a5c 100644 --- a/models/invoice_payment.go +++ b/models/invoice_payment.go @@ -1,105 +1,115 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // InvoicePayment represents a InvoicePayment struct. type InvoicePayment struct { - TransactionTime *time.Time `json:"transaction_time,omitempty"` - Memo *string `json:"memo,omitempty"` - OriginalAmount *string `json:"original_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - PaymentMethod *InvoicePaymentMethod `json:"payment_method,omitempty"` - TransactionId *int `json:"transaction_id,omitempty"` - Prepayment *bool `json:"prepayment,omitempty"` - GatewayHandle Optional[string] `json:"gateway_handle"` - GatewayUsed *string `json:"gateway_used,omitempty"` - // The transaction ID for the payment as returned from the payment gateway - GatewayTransactionId Optional[string] `json:"gateway_transaction_id"` + TransactionTime *time.Time `json:"transaction_time,omitempty"` + Memo *string `json:"memo,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` + PaymentMethod *InvoicePaymentMethod `json:"payment_method,omitempty"` + TransactionId *int `json:"transaction_id,omitempty"` + Prepayment *bool `json:"prepayment,omitempty"` + GatewayHandle Optional[string] `json:"gateway_handle"` + GatewayUsed *string `json:"gateway_used,omitempty"` + // The transaction ID for the payment as returned from the payment gateway + GatewayTransactionId Optional[string] `json:"gateway_transaction_id"` } -// MarshalJSON implements the json.Marshaler interface for InvoicePayment. +// MarshalJSON implements the json.Marshaler interface for InvoicePayment. // It customizes the JSON marshaling process for InvoicePayment objects. func (i *InvoicePayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoicePayment object to a map representation for JSON marshaling. func (i *InvoicePayment) toMap() map[string]any { - structMap := make(map[string]any) - if i.TransactionTime != nil { - structMap["transaction_time"] = i.TransactionTime.Format(time.RFC3339) - } - if i.Memo != nil { - structMap["memo"] = i.Memo - } - if i.OriginalAmount != nil { - structMap["original_amount"] = i.OriginalAmount - } - if i.AppliedAmount != nil { - structMap["applied_amount"] = i.AppliedAmount - } - if i.PaymentMethod != nil { - structMap["payment_method"] = i.PaymentMethod.toMap() - } - if i.TransactionId != nil { - structMap["transaction_id"] = i.TransactionId - } - if i.Prepayment != nil { - structMap["prepayment"] = i.Prepayment - } - if i.GatewayHandle.IsValueSet() { - structMap["gateway_handle"] = i.GatewayHandle.Value() - } - if i.GatewayUsed != nil { - structMap["gateway_used"] = i.GatewayUsed - } - if i.GatewayTransactionId.IsValueSet() { - structMap["gateway_transaction_id"] = i.GatewayTransactionId.Value() - } - return structMap + structMap := make(map[string]any) + if i.TransactionTime != nil { + structMap["transaction_time"] = i.TransactionTime.Format(time.RFC3339) + } + if i.Memo != nil { + structMap["memo"] = i.Memo + } + if i.OriginalAmount != nil { + structMap["original_amount"] = i.OriginalAmount + } + if i.AppliedAmount != nil { + structMap["applied_amount"] = i.AppliedAmount + } + if i.PaymentMethod != nil { + structMap["payment_method"] = i.PaymentMethod.toMap() + } + if i.TransactionId != nil { + structMap["transaction_id"] = i.TransactionId + } + if i.Prepayment != nil { + structMap["prepayment"] = i.Prepayment + } + if i.GatewayHandle.IsValueSet() { + if i.GatewayHandle.Value() != nil { + structMap["gateway_handle"] = i.GatewayHandle.Value() + } else { + structMap["gateway_handle"] = nil + } + } + if i.GatewayUsed != nil { + structMap["gateway_used"] = i.GatewayUsed + } + if i.GatewayTransactionId.IsValueSet() { + if i.GatewayTransactionId.Value() != nil { + structMap["gateway_transaction_id"] = i.GatewayTransactionId.Value() + } else { + structMap["gateway_transaction_id"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePayment. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePayment. // It customizes the JSON unmarshaling process for InvoicePayment objects. func (i *InvoicePayment) UnmarshalJSON(input []byte) error { - temp := &struct { - TransactionTime *string `json:"transaction_time,omitempty"` - Memo *string `json:"memo,omitempty"` - OriginalAmount *string `json:"original_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - PaymentMethod *InvoicePaymentMethod `json:"payment_method,omitempty"` - TransactionId *int `json:"transaction_id,omitempty"` - Prepayment *bool `json:"prepayment,omitempty"` - GatewayHandle Optional[string] `json:"gateway_handle"` - GatewayUsed *string `json:"gateway_used,omitempty"` - GatewayTransactionId Optional[string] `json:"gateway_transaction_id"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - if temp.TransactionTime != nil { - TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) - if err != nil { - log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) - } - i.TransactionTime = &TransactionTimeVal - } - i.Memo = temp.Memo - i.OriginalAmount = temp.OriginalAmount - i.AppliedAmount = temp.AppliedAmount - i.PaymentMethod = temp.PaymentMethod - i.TransactionId = temp.TransactionId - i.Prepayment = temp.Prepayment - i.GatewayHandle = temp.GatewayHandle - i.GatewayUsed = temp.GatewayUsed - i.GatewayTransactionId = temp.GatewayTransactionId - return nil + var temp invoicePayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + if temp.TransactionTime != nil { + TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) + if err != nil { + log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) + } + i.TransactionTime = &TransactionTimeVal + } + i.Memo = temp.Memo + i.OriginalAmount = temp.OriginalAmount + i.AppliedAmount = temp.AppliedAmount + i.PaymentMethod = temp.PaymentMethod + i.TransactionId = temp.TransactionId + i.Prepayment = temp.Prepayment + i.GatewayHandle = temp.GatewayHandle + i.GatewayUsed = temp.GatewayUsed + i.GatewayTransactionId = temp.GatewayTransactionId + return nil +} + +// TODO +type invoicePayment struct { + TransactionTime *string `json:"transaction_time,omitempty"` + Memo *string `json:"memo,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` + PaymentMethod *InvoicePaymentMethod `json:"payment_method,omitempty"` + TransactionId *int `json:"transaction_id,omitempty"` + Prepayment *bool `json:"prepayment,omitempty"` + GatewayHandle Optional[string] `json:"gateway_handle"` + GatewayUsed *string `json:"gateway_used,omitempty"` + GatewayTransactionId Optional[string] `json:"gateway_transaction_id"` } diff --git a/models/invoice_payment_application.go b/models/invoice_payment_application.go index 15668962..dec87e32 100644 --- a/models/invoice_payment_application.go +++ b/models/invoice_payment_application.go @@ -1,57 +1,59 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoicePaymentApplication represents a InvoicePaymentApplication struct. type InvoicePaymentApplication struct { - // Unique identifier for the paid invoice. It has the prefix "inv_" followed by alphanumeric characters. - InvoiceUid *string `json:"invoice_uid,omitempty"` - // Unique identifier for the payment. It has the prefix "pmt_" followed by alphanumeric characters. - ApplicationUid *string `json:"application_uid,omitempty"` - // Dollar amount of the paid invoice. - AppliedAmount *string `json:"applied_amount,omitempty"` + // Unique identifier for the paid invoice. It has the prefix "inv_" followed by alphanumeric characters. + InvoiceUid *string `json:"invoice_uid,omitempty"` + // Unique identifier for the payment. It has the prefix "pmt_" followed by alphanumeric characters. + ApplicationUid *string `json:"application_uid,omitempty"` + // Dollar amount of the paid invoice. + AppliedAmount *string `json:"applied_amount,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoicePaymentApplication. +// MarshalJSON implements the json.Marshaler interface for InvoicePaymentApplication. // It customizes the JSON marshaling process for InvoicePaymentApplication objects. func (i *InvoicePaymentApplication) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoicePaymentApplication object to a map representation for JSON marshaling. func (i *InvoicePaymentApplication) toMap() map[string]any { - structMap := make(map[string]any) - if i.InvoiceUid != nil { - structMap["invoice_uid"] = i.InvoiceUid - } - if i.ApplicationUid != nil { - structMap["application_uid"] = i.ApplicationUid - } - if i.AppliedAmount != nil { - structMap["applied_amount"] = i.AppliedAmount - } - return structMap + structMap := make(map[string]any) + if i.InvoiceUid != nil { + structMap["invoice_uid"] = i.InvoiceUid + } + if i.ApplicationUid != nil { + structMap["application_uid"] = i.ApplicationUid + } + if i.AppliedAmount != nil { + structMap["applied_amount"] = i.AppliedAmount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePaymentApplication. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePaymentApplication. // It customizes the JSON unmarshaling process for InvoicePaymentApplication objects. func (i *InvoicePaymentApplication) UnmarshalJSON(input []byte) error { - temp := &struct { - InvoiceUid *string `json:"invoice_uid,omitempty"` - ApplicationUid *string `json:"application_uid,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.InvoiceUid = temp.InvoiceUid - i.ApplicationUid = temp.ApplicationUid - i.AppliedAmount = temp.AppliedAmount - return nil + var temp invoicePaymentApplication + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.InvoiceUid = temp.InvoiceUid + i.ApplicationUid = temp.ApplicationUid + i.AppliedAmount = temp.AppliedAmount + return nil +} + +// TODO +type invoicePaymentApplication struct { + InvoiceUid *string `json:"invoice_uid,omitempty"` + ApplicationUid *string `json:"application_uid,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` } diff --git a/models/invoice_payment_method.go b/models/invoice_payment_method.go index e58ef307..fbeb0030 100644 --- a/models/invoice_payment_method.go +++ b/models/invoice_payment_method.go @@ -1,84 +1,90 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoicePaymentMethod represents a InvoicePaymentMethod struct. type InvoicePaymentMethod struct { - Details *string `json:"details,omitempty"` - Kind *string `json:"kind,omitempty"` - Memo *string `json:"memo,omitempty"` - Type *string `json:"type,omitempty"` - CardBrand *string `json:"card_brand,omitempty"` - CardExpiration *string `json:"card_expiration,omitempty"` - LastFour Optional[string] `json:"last_four"` - MaskedCardNumber *string `json:"masked_card_number,omitempty"` + Details *string `json:"details,omitempty"` + Kind *string `json:"kind,omitempty"` + Memo *string `json:"memo,omitempty"` + Type *string `json:"type,omitempty"` + CardBrand *string `json:"card_brand,omitempty"` + CardExpiration *string `json:"card_expiration,omitempty"` + LastFour Optional[string] `json:"last_four"` + MaskedCardNumber *string `json:"masked_card_number,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoicePaymentMethod. +// MarshalJSON implements the json.Marshaler interface for InvoicePaymentMethod. // It customizes the JSON marshaling process for InvoicePaymentMethod objects. func (i *InvoicePaymentMethod) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoicePaymentMethod object to a map representation for JSON marshaling. func (i *InvoicePaymentMethod) toMap() map[string]any { - structMap := make(map[string]any) - if i.Details != nil { - structMap["details"] = i.Details - } - if i.Kind != nil { - structMap["kind"] = i.Kind - } - if i.Memo != nil { - structMap["memo"] = i.Memo - } - if i.Type != nil { - structMap["type"] = i.Type - } - if i.CardBrand != nil { - structMap["card_brand"] = i.CardBrand - } - if i.CardExpiration != nil { - structMap["card_expiration"] = i.CardExpiration - } - if i.LastFour.IsValueSet() { - structMap["last_four"] = i.LastFour.Value() - } - if i.MaskedCardNumber != nil { - structMap["masked_card_number"] = i.MaskedCardNumber - } - return structMap + structMap := make(map[string]any) + if i.Details != nil { + structMap["details"] = i.Details + } + if i.Kind != nil { + structMap["kind"] = i.Kind + } + if i.Memo != nil { + structMap["memo"] = i.Memo + } + if i.Type != nil { + structMap["type"] = i.Type + } + if i.CardBrand != nil { + structMap["card_brand"] = i.CardBrand + } + if i.CardExpiration != nil { + structMap["card_expiration"] = i.CardExpiration + } + if i.LastFour.IsValueSet() { + if i.LastFour.Value() != nil { + structMap["last_four"] = i.LastFour.Value() + } else { + structMap["last_four"] = nil + } + } + if i.MaskedCardNumber != nil { + structMap["masked_card_number"] = i.MaskedCardNumber + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePaymentMethod. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePaymentMethod. // It customizes the JSON unmarshaling process for InvoicePaymentMethod objects. func (i *InvoicePaymentMethod) UnmarshalJSON(input []byte) error { - temp := &struct { - Details *string `json:"details,omitempty"` - Kind *string `json:"kind,omitempty"` - Memo *string `json:"memo,omitempty"` - Type *string `json:"type,omitempty"` - CardBrand *string `json:"card_brand,omitempty"` - CardExpiration *string `json:"card_expiration,omitempty"` - LastFour Optional[string] `json:"last_four"` - MaskedCardNumber *string `json:"masked_card_number,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Details = temp.Details - i.Kind = temp.Kind - i.Memo = temp.Memo - i.Type = temp.Type - i.CardBrand = temp.CardBrand - i.CardExpiration = temp.CardExpiration - i.LastFour = temp.LastFour - i.MaskedCardNumber = temp.MaskedCardNumber - return nil + var temp invoicePaymentMethod + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Details = temp.Details + i.Kind = temp.Kind + i.Memo = temp.Memo + i.Type = temp.Type + i.CardBrand = temp.CardBrand + i.CardExpiration = temp.CardExpiration + i.LastFour = temp.LastFour + i.MaskedCardNumber = temp.MaskedCardNumber + return nil +} + +// TODO +type invoicePaymentMethod struct { + Details *string `json:"details,omitempty"` + Kind *string `json:"kind,omitempty"` + Memo *string `json:"memo,omitempty"` + Type *string `json:"type,omitempty"` + CardBrand *string `json:"card_brand,omitempty"` + CardExpiration *string `json:"card_expiration,omitempty"` + LastFour Optional[string] `json:"last_four"` + MaskedCardNumber *string `json:"masked_card_number,omitempty"` } diff --git a/models/invoice_pre_payment.go b/models/invoice_pre_payment.go index 2d03d401..c1e89e29 100644 --- a/models/invoice_pre_payment.go +++ b/models/invoice_pre_payment.go @@ -1,57 +1,59 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoicePrePayment represents a InvoicePrePayment struct. type InvoicePrePayment struct { - // The subscription id for the prepayment account - SubscriptionId *int `json:"subscription_id,omitempty"` - // The amount in cents of the prepayment that was created as a result of this payment. - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - // The total balance of the prepayment account for this subscription including any prior prepayments - EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` + // The subscription id for the prepayment account + SubscriptionId *int `json:"subscription_id,omitempty"` + // The amount in cents of the prepayment that was created as a result of this payment. + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + // The total balance of the prepayment account for this subscription including any prior prepayments + EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoicePrePayment. +// MarshalJSON implements the json.Marshaler interface for InvoicePrePayment. // It customizes the JSON marshaling process for InvoicePrePayment objects. func (i *InvoicePrePayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoicePrePayment object to a map representation for JSON marshaling. func (i *InvoicePrePayment) toMap() map[string]any { - structMap := make(map[string]any) - if i.SubscriptionId != nil { - structMap["subscription_id"] = i.SubscriptionId - } - if i.AmountInCents != nil { - structMap["amount_in_cents"] = i.AmountInCents - } - if i.EndingBalanceInCents != nil { - structMap["ending_balance_in_cents"] = i.EndingBalanceInCents - } - return structMap + structMap := make(map[string]any) + if i.SubscriptionId != nil { + structMap["subscription_id"] = i.SubscriptionId + } + if i.AmountInCents != nil { + structMap["amount_in_cents"] = i.AmountInCents + } + if i.EndingBalanceInCents != nil { + structMap["ending_balance_in_cents"] = i.EndingBalanceInCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePrePayment. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePrePayment. // It customizes the JSON unmarshaling process for InvoicePrePayment objects. func (i *InvoicePrePayment) UnmarshalJSON(input []byte) error { - temp := &struct { - SubscriptionId *int `json:"subscription_id,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.SubscriptionId = temp.SubscriptionId - i.AmountInCents = temp.AmountInCents - i.EndingBalanceInCents = temp.EndingBalanceInCents - return nil + var temp invoicePrePayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.SubscriptionId = temp.SubscriptionId + i.AmountInCents = temp.AmountInCents + i.EndingBalanceInCents = temp.EndingBalanceInCents + return nil +} + +// TODO +type invoicePrePayment struct { + SubscriptionId *int `json:"subscription_id,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` } diff --git a/models/invoice_previous_balance.go b/models/invoice_previous_balance.go index 3b8fdc54..06c3aef5 100644 --- a/models/invoice_previous_balance.go +++ b/models/invoice_previous_balance.go @@ -1,56 +1,58 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // InvoicePreviousBalance represents a InvoicePreviousBalance struct. type InvoicePreviousBalance struct { - CapturedAt *time.Time `json:"captured_at,omitempty"` - Invoices []InvoiceBalanceItem `json:"invoices,omitempty"` + CapturedAt *time.Time `json:"captured_at,omitempty"` + Invoices []InvoiceBalanceItem `json:"invoices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoicePreviousBalance. +// MarshalJSON implements the json.Marshaler interface for InvoicePreviousBalance. // It customizes the JSON marshaling process for InvoicePreviousBalance objects. func (i *InvoicePreviousBalance) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoicePreviousBalance object to a map representation for JSON marshaling. func (i *InvoicePreviousBalance) toMap() map[string]any { - structMap := make(map[string]any) - if i.CapturedAt != nil { - structMap["captured_at"] = i.CapturedAt.Format(time.RFC3339) - } - if i.Invoices != nil { - structMap["invoices"] = i.Invoices - } - return structMap + structMap := make(map[string]any) + if i.CapturedAt != nil { + structMap["captured_at"] = i.CapturedAt.Format(time.RFC3339) + } + if i.Invoices != nil { + structMap["invoices"] = i.Invoices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePreviousBalance. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoicePreviousBalance. // It customizes the JSON unmarshaling process for InvoicePreviousBalance objects. func (i *InvoicePreviousBalance) UnmarshalJSON(input []byte) error { - temp := &struct { - CapturedAt *string `json:"captured_at,omitempty"` - Invoices []InvoiceBalanceItem `json:"invoices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - if temp.CapturedAt != nil { - CapturedAtVal, err := time.Parse(time.RFC3339, *temp.CapturedAt) - if err != nil { - log.Fatalf("Cannot Parse captured_at as % s format.", time.RFC3339) - } - i.CapturedAt = &CapturedAtVal - } - i.Invoices = temp.Invoices - return nil + var temp invoicePreviousBalance + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + if temp.CapturedAt != nil { + CapturedAtVal, err := time.Parse(time.RFC3339, *temp.CapturedAt) + if err != nil { + log.Fatalf("Cannot Parse captured_at as % s format.", time.RFC3339) + } + i.CapturedAt = &CapturedAtVal + } + i.Invoices = temp.Invoices + return nil +} + +// TODO +type invoicePreviousBalance struct { + CapturedAt *string `json:"captured_at,omitempty"` + Invoices []InvoiceBalanceItem `json:"invoices,omitempty"` } diff --git a/models/invoice_refund.go b/models/invoice_refund.go index 0189a1c9..af27bd44 100644 --- a/models/invoice_refund.go +++ b/models/invoice_refund.go @@ -1,85 +1,95 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoiceRefund represents a InvoiceRefund struct. type InvoiceRefund struct { - TransactionId *int `json:"transaction_id,omitempty"` - PaymentId *int `json:"payment_id,omitempty"` - Memo *string `json:"memo,omitempty"` - OriginalAmount *string `json:"original_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - // The transaction ID for the refund as returned from the payment gateway - GatewayTransactionId Optional[string] `json:"gateway_transaction_id"` - GatewayUsed *string `json:"gateway_used,omitempty"` - GatewayHandle Optional[string] `json:"gateway_handle"` + TransactionId *int `json:"transaction_id,omitempty"` + PaymentId *int `json:"payment_id,omitempty"` + Memo *string `json:"memo,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` + // The transaction ID for the refund as returned from the payment gateway + GatewayTransactionId Optional[string] `json:"gateway_transaction_id"` + GatewayUsed *string `json:"gateway_used,omitempty"` + GatewayHandle Optional[string] `json:"gateway_handle"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceRefund. +// MarshalJSON implements the json.Marshaler interface for InvoiceRefund. // It customizes the JSON marshaling process for InvoiceRefund objects. func (i *InvoiceRefund) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceRefund object to a map representation for JSON marshaling. func (i *InvoiceRefund) toMap() map[string]any { - structMap := make(map[string]any) - if i.TransactionId != nil { - structMap["transaction_id"] = i.TransactionId - } - if i.PaymentId != nil { - structMap["payment_id"] = i.PaymentId - } - if i.Memo != nil { - structMap["memo"] = i.Memo - } - if i.OriginalAmount != nil { - structMap["original_amount"] = i.OriginalAmount - } - if i.AppliedAmount != nil { - structMap["applied_amount"] = i.AppliedAmount - } - if i.GatewayTransactionId.IsValueSet() { - structMap["gateway_transaction_id"] = i.GatewayTransactionId.Value() - } - if i.GatewayUsed != nil { - structMap["gateway_used"] = i.GatewayUsed - } - if i.GatewayHandle.IsValueSet() { - structMap["gateway_handle"] = i.GatewayHandle.Value() - } - return structMap + structMap := make(map[string]any) + if i.TransactionId != nil { + structMap["transaction_id"] = i.TransactionId + } + if i.PaymentId != nil { + structMap["payment_id"] = i.PaymentId + } + if i.Memo != nil { + structMap["memo"] = i.Memo + } + if i.OriginalAmount != nil { + structMap["original_amount"] = i.OriginalAmount + } + if i.AppliedAmount != nil { + structMap["applied_amount"] = i.AppliedAmount + } + if i.GatewayTransactionId.IsValueSet() { + if i.GatewayTransactionId.Value() != nil { + structMap["gateway_transaction_id"] = i.GatewayTransactionId.Value() + } else { + structMap["gateway_transaction_id"] = nil + } + } + if i.GatewayUsed != nil { + structMap["gateway_used"] = i.GatewayUsed + } + if i.GatewayHandle.IsValueSet() { + if i.GatewayHandle.Value() != nil { + structMap["gateway_handle"] = i.GatewayHandle.Value() + } else { + structMap["gateway_handle"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceRefund. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceRefund. // It customizes the JSON unmarshaling process for InvoiceRefund objects. func (i *InvoiceRefund) UnmarshalJSON(input []byte) error { - temp := &struct { - TransactionId *int `json:"transaction_id,omitempty"` - PaymentId *int `json:"payment_id,omitempty"` - Memo *string `json:"memo,omitempty"` - OriginalAmount *string `json:"original_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - GatewayTransactionId Optional[string] `json:"gateway_transaction_id"` - GatewayUsed *string `json:"gateway_used,omitempty"` - GatewayHandle Optional[string] `json:"gateway_handle"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.TransactionId = temp.TransactionId - i.PaymentId = temp.PaymentId - i.Memo = temp.Memo - i.OriginalAmount = temp.OriginalAmount - i.AppliedAmount = temp.AppliedAmount - i.GatewayTransactionId = temp.GatewayTransactionId - i.GatewayUsed = temp.GatewayUsed - i.GatewayHandle = temp.GatewayHandle - return nil + var temp invoiceRefund + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.TransactionId = temp.TransactionId + i.PaymentId = temp.PaymentId + i.Memo = temp.Memo + i.OriginalAmount = temp.OriginalAmount + i.AppliedAmount = temp.AppliedAmount + i.GatewayTransactionId = temp.GatewayTransactionId + i.GatewayUsed = temp.GatewayUsed + i.GatewayHandle = temp.GatewayHandle + return nil +} + +// TODO +type invoiceRefund struct { + TransactionId *int `json:"transaction_id,omitempty"` + PaymentId *int `json:"payment_id,omitempty"` + Memo *string `json:"memo,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` + GatewayTransactionId Optional[string] `json:"gateway_transaction_id"` + GatewayUsed *string `json:"gateway_used,omitempty"` + GatewayHandle Optional[string] `json:"gateway_handle"` } diff --git a/models/invoice_response.go b/models/invoice_response.go index e97fb61d..3657c0ac 100644 --- a/models/invoice_response.go +++ b/models/invoice_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // InvoiceResponse represents a InvoiceResponse struct. type InvoiceResponse struct { - Invoice Invoice `json:"invoice"` + Invoice Invoice `json:"invoice"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceResponse. +// MarshalJSON implements the json.Marshaler interface for InvoiceResponse. // It customizes the JSON marshaling process for InvoiceResponse objects. func (i *InvoiceResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceResponse object to a map representation for JSON marshaling. func (i *InvoiceResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["invoice"] = i.Invoice.toMap() - return structMap + structMap := make(map[string]any) + structMap["invoice"] = i.Invoice.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceResponse. // It customizes the JSON unmarshaling process for InvoiceResponse objects. func (i *InvoiceResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Invoice Invoice `json:"invoice"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Invoice = temp.Invoice - return nil + var temp invoiceResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + i.Invoice = *temp.Invoice + return nil +} + +// TODO +type invoiceResponse struct { + Invoice *Invoice `json:"invoice"` +} + +func (i *invoiceResponse) validate() error { + var errs []string + if i.Invoice == nil { + errs = append(errs, "required field `invoice` is missing for type `Invoice Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/invoice_seller.go b/models/invoice_seller.go index 36213800..b700e7db 100644 --- a/models/invoice_seller.go +++ b/models/invoice_seller.go @@ -1,61 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" ) -// InvoiceSeller represents a InvoiceSeller struct. +// InvoiceSeller represents a InvoiceSeller struct. // Information about the seller (merchant) listed on the masthead of the invoice. type InvoiceSeller struct { - Name *string `json:"name,omitempty"` - Address *InvoiceAddress `json:"address,omitempty"` - Phone *string `json:"phone,omitempty"` - LogoUrl Optional[string] `json:"logo_url"` + Name *string `json:"name,omitempty"` + Address *InvoiceAddress `json:"address,omitempty"` + Phone *string `json:"phone,omitempty"` + LogoUrl Optional[string] `json:"logo_url"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceSeller. +// MarshalJSON implements the json.Marshaler interface for InvoiceSeller. // It customizes the JSON marshaling process for InvoiceSeller objects. func (i *InvoiceSeller) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceSeller object to a map representation for JSON marshaling. func (i *InvoiceSeller) toMap() map[string]any { - structMap := make(map[string]any) - if i.Name != nil { - structMap["name"] = i.Name - } - if i.Address != nil { - structMap["address"] = i.Address.toMap() - } - if i.Phone != nil { - structMap["phone"] = i.Phone - } - if i.LogoUrl.IsValueSet() { - structMap["logo_url"] = i.LogoUrl.Value() - } - return structMap + structMap := make(map[string]any) + if i.Name != nil { + structMap["name"] = i.Name + } + if i.Address != nil { + structMap["address"] = i.Address.toMap() + } + if i.Phone != nil { + structMap["phone"] = i.Phone + } + if i.LogoUrl.IsValueSet() { + if i.LogoUrl.Value() != nil { + structMap["logo_url"] = i.LogoUrl.Value() + } else { + structMap["logo_url"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceSeller. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceSeller. // It customizes the JSON unmarshaling process for InvoiceSeller objects. func (i *InvoiceSeller) UnmarshalJSON(input []byte) error { - temp := &struct { - Name *string `json:"name,omitempty"` - Address *InvoiceAddress `json:"address,omitempty"` - Phone *string `json:"phone,omitempty"` - LogoUrl Optional[string] `json:"logo_url"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Name = temp.Name - i.Address = temp.Address - i.Phone = temp.Phone - i.LogoUrl = temp.LogoUrl - return nil + var temp invoiceSeller + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Name = temp.Name + i.Address = temp.Address + i.Phone = temp.Phone + i.LogoUrl = temp.LogoUrl + return nil +} + +// TODO +type invoiceSeller struct { + Name *string `json:"name,omitempty"` + Address *InvoiceAddress `json:"address,omitempty"` + Phone *string `json:"phone,omitempty"` + LogoUrl Optional[string] `json:"logo_url"` } diff --git a/models/invoice_tax.go b/models/invoice_tax.go index fb6037d2..741590dc 100644 --- a/models/invoice_tax.go +++ b/models/invoice_tax.go @@ -1,102 +1,108 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoiceTax represents a InvoiceTax struct. type InvoiceTax struct { - Uid *string `json:"uid,omitempty"` - Title *string `json:"title,omitempty"` - Description Optional[string] `json:"description"` - SourceType *ProformaInvoiceTaxSourceType `json:"source_type,omitempty"` - SourceId *int `json:"source_id,omitempty"` - Percentage *string `json:"percentage,omitempty"` - TaxableAmount *string `json:"taxable_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - TransactionId *int `json:"transaction_id,omitempty"` - LineItemBreakouts []InvoiceTaxBreakout `json:"line_item_breakouts,omitempty"` - TaxComponentBreakouts []InvoiceTaxComponentBreakout `json:"tax_component_breakouts,omitempty"` + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + Description Optional[string] `json:"description"` + SourceType *ProformaInvoiceTaxSourceType `json:"source_type,omitempty"` + SourceId *int `json:"source_id,omitempty"` + Percentage *string `json:"percentage,omitempty"` + TaxableAmount *string `json:"taxable_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + TransactionId *int `json:"transaction_id,omitempty"` + LineItemBreakouts []InvoiceTaxBreakout `json:"line_item_breakouts,omitempty"` + TaxComponentBreakouts []InvoiceTaxComponentBreakout `json:"tax_component_breakouts,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceTax. +// MarshalJSON implements the json.Marshaler interface for InvoiceTax. // It customizes the JSON marshaling process for InvoiceTax objects. func (i *InvoiceTax) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceTax object to a map representation for JSON marshaling. func (i *InvoiceTax) toMap() map[string]any { - structMap := make(map[string]any) - if i.Uid != nil { - structMap["uid"] = i.Uid - } - if i.Title != nil { - structMap["title"] = i.Title - } - if i.Description.IsValueSet() { - structMap["description"] = i.Description.Value() - } - if i.SourceType != nil { - structMap["source_type"] = i.SourceType - } - if i.SourceId != nil { - structMap["source_id"] = i.SourceId - } - if i.Percentage != nil { - structMap["percentage"] = i.Percentage - } - if i.TaxableAmount != nil { - structMap["taxable_amount"] = i.TaxableAmount - } - if i.TaxAmount != nil { - structMap["tax_amount"] = i.TaxAmount - } - if i.TransactionId != nil { - structMap["transaction_id"] = i.TransactionId - } - if i.LineItemBreakouts != nil { - structMap["line_item_breakouts"] = i.LineItemBreakouts - } - if i.TaxComponentBreakouts != nil { - structMap["tax_component_breakouts"] = i.TaxComponentBreakouts - } - return structMap + structMap := make(map[string]any) + if i.Uid != nil { + structMap["uid"] = i.Uid + } + if i.Title != nil { + structMap["title"] = i.Title + } + if i.Description.IsValueSet() { + if i.Description.Value() != nil { + structMap["description"] = i.Description.Value() + } else { + structMap["description"] = nil + } + } + if i.SourceType != nil { + structMap["source_type"] = i.SourceType + } + if i.SourceId != nil { + structMap["source_id"] = i.SourceId + } + if i.Percentage != nil { + structMap["percentage"] = i.Percentage + } + if i.TaxableAmount != nil { + structMap["taxable_amount"] = i.TaxableAmount + } + if i.TaxAmount != nil { + structMap["tax_amount"] = i.TaxAmount + } + if i.TransactionId != nil { + structMap["transaction_id"] = i.TransactionId + } + if i.LineItemBreakouts != nil { + structMap["line_item_breakouts"] = i.LineItemBreakouts + } + if i.TaxComponentBreakouts != nil { + structMap["tax_component_breakouts"] = i.TaxComponentBreakouts + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceTax. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceTax. // It customizes the JSON unmarshaling process for InvoiceTax objects. func (i *InvoiceTax) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Title *string `json:"title,omitempty"` - Description Optional[string] `json:"description"` - SourceType *ProformaInvoiceTaxSourceType `json:"source_type,omitempty"` - SourceId *int `json:"source_id,omitempty"` - Percentage *string `json:"percentage,omitempty"` - TaxableAmount *string `json:"taxable_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - TransactionId *int `json:"transaction_id,omitempty"` - LineItemBreakouts []InvoiceTaxBreakout `json:"line_item_breakouts,omitempty"` - TaxComponentBreakouts []InvoiceTaxComponentBreakout `json:"tax_component_breakouts,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Uid = temp.Uid - i.Title = temp.Title - i.Description = temp.Description - i.SourceType = temp.SourceType - i.SourceId = temp.SourceId - i.Percentage = temp.Percentage - i.TaxableAmount = temp.TaxableAmount - i.TaxAmount = temp.TaxAmount - i.TransactionId = temp.TransactionId - i.LineItemBreakouts = temp.LineItemBreakouts - i.TaxComponentBreakouts = temp.TaxComponentBreakouts - return nil + var temp invoiceTax + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Uid = temp.Uid + i.Title = temp.Title + i.Description = temp.Description + i.SourceType = temp.SourceType + i.SourceId = temp.SourceId + i.Percentage = temp.Percentage + i.TaxableAmount = temp.TaxableAmount + i.TaxAmount = temp.TaxAmount + i.TransactionId = temp.TransactionId + i.LineItemBreakouts = temp.LineItemBreakouts + i.TaxComponentBreakouts = temp.TaxComponentBreakouts + return nil +} + +// TODO +type invoiceTax struct { + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + Description Optional[string] `json:"description"` + SourceType *ProformaInvoiceTaxSourceType `json:"source_type,omitempty"` + SourceId *int `json:"source_id,omitempty"` + Percentage *string `json:"percentage,omitempty"` + TaxableAmount *string `json:"taxable_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + TransactionId *int `json:"transaction_id,omitempty"` + LineItemBreakouts []InvoiceTaxBreakout `json:"line_item_breakouts,omitempty"` + TaxComponentBreakouts []InvoiceTaxComponentBreakout `json:"tax_component_breakouts,omitempty"` } diff --git a/models/invoice_tax_breakout.go b/models/invoice_tax_breakout.go index 342a7869..6cf05417 100644 --- a/models/invoice_tax_breakout.go +++ b/models/invoice_tax_breakout.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoiceTaxBreakout represents a InvoiceTaxBreakout struct. type InvoiceTaxBreakout struct { - Uid *string `json:"uid,omitempty"` - TaxableAmount *string `json:"taxable_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - TaxExemptAmount *string `json:"tax_exempt_amount,omitempty"` + Uid *string `json:"uid,omitempty"` + TaxableAmount *string `json:"taxable_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + TaxExemptAmount *string `json:"tax_exempt_amount,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceTaxBreakout. +// MarshalJSON implements the json.Marshaler interface for InvoiceTaxBreakout. // It customizes the JSON marshaling process for InvoiceTaxBreakout objects. func (i *InvoiceTaxBreakout) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceTaxBreakout object to a map representation for JSON marshaling. func (i *InvoiceTaxBreakout) toMap() map[string]any { - structMap := make(map[string]any) - if i.Uid != nil { - structMap["uid"] = i.Uid - } - if i.TaxableAmount != nil { - structMap["taxable_amount"] = i.TaxableAmount - } - if i.TaxAmount != nil { - structMap["tax_amount"] = i.TaxAmount - } - if i.TaxExemptAmount != nil { - structMap["tax_exempt_amount"] = i.TaxExemptAmount - } - return structMap + structMap := make(map[string]any) + if i.Uid != nil { + structMap["uid"] = i.Uid + } + if i.TaxableAmount != nil { + structMap["taxable_amount"] = i.TaxableAmount + } + if i.TaxAmount != nil { + structMap["tax_amount"] = i.TaxAmount + } + if i.TaxExemptAmount != nil { + structMap["tax_exempt_amount"] = i.TaxExemptAmount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceTaxBreakout. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceTaxBreakout. // It customizes the JSON unmarshaling process for InvoiceTaxBreakout objects. func (i *InvoiceTaxBreakout) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - TaxableAmount *string `json:"taxable_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - TaxExemptAmount *string `json:"tax_exempt_amount,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Uid = temp.Uid - i.TaxableAmount = temp.TaxableAmount - i.TaxAmount = temp.TaxAmount - i.TaxExemptAmount = temp.TaxExemptAmount - return nil + var temp invoiceTaxBreakout + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Uid = temp.Uid + i.TaxableAmount = temp.TaxableAmount + i.TaxAmount = temp.TaxAmount + i.TaxExemptAmount = temp.TaxExemptAmount + return nil +} + +// TODO +type invoiceTaxBreakout struct { + Uid *string `json:"uid,omitempty"` + TaxableAmount *string `json:"taxable_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + TaxExemptAmount *string `json:"tax_exempt_amount,omitempty"` } diff --git a/models/invoice_tax_component_breakout.go b/models/invoice_tax_component_breakout.go index c0a24dea..b1be6779 100644 --- a/models/invoice_tax_component_breakout.go +++ b/models/invoice_tax_component_breakout.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // InvoiceTaxComponentBreakout represents a InvoiceTaxComponentBreakout struct. type InvoiceTaxComponentBreakout struct { - TaxRuleId *int `json:"tax_rule_id,omitempty"` - Percentage *string `json:"percentage,omitempty"` - CountryCode *string `json:"country_code,omitempty"` - SubdivisionCode *string `json:"subdivision_code,omitempty"` + TaxRuleId *int `json:"tax_rule_id,omitempty"` + Percentage *string `json:"percentage,omitempty"` + CountryCode *string `json:"country_code,omitempty"` + SubdivisionCode *string `json:"subdivision_code,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for InvoiceTaxComponentBreakout. +// MarshalJSON implements the json.Marshaler interface for InvoiceTaxComponentBreakout. // It customizes the JSON marshaling process for InvoiceTaxComponentBreakout objects. func (i *InvoiceTaxComponentBreakout) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the InvoiceTaxComponentBreakout object to a map representation for JSON marshaling. func (i *InvoiceTaxComponentBreakout) toMap() map[string]any { - structMap := make(map[string]any) - if i.TaxRuleId != nil { - structMap["tax_rule_id"] = i.TaxRuleId - } - if i.Percentage != nil { - structMap["percentage"] = i.Percentage - } - if i.CountryCode != nil { - structMap["country_code"] = i.CountryCode - } - if i.SubdivisionCode != nil { - structMap["subdivision_code"] = i.SubdivisionCode - } - return structMap + structMap := make(map[string]any) + if i.TaxRuleId != nil { + structMap["tax_rule_id"] = i.TaxRuleId + } + if i.Percentage != nil { + structMap["percentage"] = i.Percentage + } + if i.CountryCode != nil { + structMap["country_code"] = i.CountryCode + } + if i.SubdivisionCode != nil { + structMap["subdivision_code"] = i.SubdivisionCode + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceTaxComponentBreakout. +// UnmarshalJSON implements the json.Unmarshaler interface for InvoiceTaxComponentBreakout. // It customizes the JSON unmarshaling process for InvoiceTaxComponentBreakout objects. func (i *InvoiceTaxComponentBreakout) UnmarshalJSON(input []byte) error { - temp := &struct { - TaxRuleId *int `json:"tax_rule_id,omitempty"` - Percentage *string `json:"percentage,omitempty"` - CountryCode *string `json:"country_code,omitempty"` - SubdivisionCode *string `json:"subdivision_code,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.TaxRuleId = temp.TaxRuleId - i.Percentage = temp.Percentage - i.CountryCode = temp.CountryCode - i.SubdivisionCode = temp.SubdivisionCode - return nil + var temp invoiceTaxComponentBreakout + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.TaxRuleId = temp.TaxRuleId + i.Percentage = temp.Percentage + i.CountryCode = temp.CountryCode + i.SubdivisionCode = temp.SubdivisionCode + return nil +} + +// TODO +type invoiceTaxComponentBreakout struct { + TaxRuleId *int `json:"tax_rule_id,omitempty"` + Percentage *string `json:"percentage,omitempty"` + CountryCode *string `json:"country_code,omitempty"` + SubdivisionCode *string `json:"subdivision_code,omitempty"` } diff --git a/models/issue_advance_invoice_request.go b/models/issue_advance_invoice_request.go index fe6baedf..6c9c6a02 100644 --- a/models/issue_advance_invoice_request.go +++ b/models/issue_advance_invoice_request.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // IssueAdvanceInvoiceRequest represents a IssueAdvanceInvoiceRequest struct. type IssueAdvanceInvoiceRequest struct { - Force *bool `json:"force,omitempty"` + Force *bool `json:"force,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for IssueAdvanceInvoiceRequest. +// MarshalJSON implements the json.Marshaler interface for IssueAdvanceInvoiceRequest. // It customizes the JSON marshaling process for IssueAdvanceInvoiceRequest objects. func (i *IssueAdvanceInvoiceRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the IssueAdvanceInvoiceRequest object to a map representation for JSON marshaling. func (i *IssueAdvanceInvoiceRequest) toMap() map[string]any { - structMap := make(map[string]any) - if i.Force != nil { - structMap["force"] = i.Force - } - return structMap + structMap := make(map[string]any) + if i.Force != nil { + structMap["force"] = i.Force + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for IssueAdvanceInvoiceRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for IssueAdvanceInvoiceRequest. // It customizes the JSON unmarshaling process for IssueAdvanceInvoiceRequest objects. func (i *IssueAdvanceInvoiceRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Force *bool `json:"force,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Force = temp.Force - return nil + var temp issueAdvanceInvoiceRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Force = temp.Force + return nil +} + +// TODO +type issueAdvanceInvoiceRequest struct { + Force *bool `json:"force,omitempty"` } diff --git a/models/issue_invoice_event_data.go b/models/issue_invoice_event_data.go new file mode 100644 index 00000000..5036b8d2 --- /dev/null +++ b/models/issue_invoice_event_data.go @@ -0,0 +1,99 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// IssueInvoiceEventData represents a IssueInvoiceEventData struct. +// Example schema for an `issue_invoice` event +type IssueInvoiceEventData struct { + // Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values: + // * "none": A normal invoice with no consolidation. + // * "child": An invoice segment which has been combined into a consolidated invoice. + // * "parent": A consolidated invoice, whose contents are composed of invoice segments. + // "Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments. + // See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). + ConsolidationLevel InvoiceConsolidationLevel `json:"consolidation_level"` + // The status of the invoice before event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. + FromStatus InvoiceStatus `json:"from_status"` + // The status of the invoice after event occurence. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. + ToStatus InvoiceStatus `json:"to_status"` + // Amount due on the invoice, which is `total_amount - credit_amount - paid_amount`. + DueAmount string `json:"due_amount"` + // The invoice total, which is `subtotal_amount - discount_amount + tax_amount`.' + TotalAmount string `json:"total_amount"` +} + +// MarshalJSON implements the json.Marshaler interface for IssueInvoiceEventData. +// It customizes the JSON marshaling process for IssueInvoiceEventData objects. +func (i *IssueInvoiceEventData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(i.toMap()) +} + +// toMap converts the IssueInvoiceEventData object to a map representation for JSON marshaling. +func (i *IssueInvoiceEventData) toMap() map[string]any { + structMap := make(map[string]any) + structMap["consolidation_level"] = i.ConsolidationLevel + structMap["from_status"] = i.FromStatus + structMap["to_status"] = i.ToStatus + structMap["due_amount"] = i.DueAmount + structMap["total_amount"] = i.TotalAmount + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for IssueInvoiceEventData. +// It customizes the JSON unmarshaling process for IssueInvoiceEventData objects. +func (i *IssueInvoiceEventData) UnmarshalJSON(input []byte) error { + var temp issueInvoiceEventData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + i.ConsolidationLevel = *temp.ConsolidationLevel + i.FromStatus = *temp.FromStatus + i.ToStatus = *temp.ToStatus + i.DueAmount = *temp.DueAmount + i.TotalAmount = *temp.TotalAmount + return nil +} + +// TODO +type issueInvoiceEventData struct { + ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level"` + FromStatus *InvoiceStatus `json:"from_status"` + ToStatus *InvoiceStatus `json:"to_status"` + DueAmount *string `json:"due_amount"` + TotalAmount *string `json:"total_amount"` +} + +func (i *issueInvoiceEventData) validate() error { + var errs []string + if i.ConsolidationLevel == nil { + errs = append(errs, "required field `consolidation_level` is missing for type `Issue Invoice Event Data`") + } + if i.FromStatus == nil { + errs = append(errs, "required field `from_status` is missing for type `Issue Invoice Event Data`") + } + if i.ToStatus == nil { + errs = append(errs, "required field `to_status` is missing for type `Issue Invoice Event Data`") + } + if i.DueAmount == nil { + errs = append(errs, "required field `due_amount` is missing for type `Issue Invoice Event Data`") + } + if i.TotalAmount == nil { + errs = append(errs, "required field `total_amount` is missing for type `Issue Invoice Event Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/issue_invoice_request.go b/models/issue_invoice_request.go index cab77206..c0255c42 100644 --- a/models/issue_invoice_request.go +++ b/models/issue_invoice_request.go @@ -1,46 +1,48 @@ package models import ( - "encoding/json" + "encoding/json" ) // IssueInvoiceRequest represents a IssueInvoiceRequest struct. type IssueInvoiceRequest struct { - // Action taken when payment for an invoice fails: - // - `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. - // - `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. - // - `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). - OnFailedPayment *FailedPaymentAction `json:"on_failed_payment,omitempty"` + // Action taken when payment for an invoice fails: + // - `leave_open_invoice` - prepayments and credits applied to invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history. This is the default option. + // - `rollback_to_pending` - prepayments and credits not applied; invoice remains in "pending" status; no email sent to the customer; payment failure recorded in the invoice history. + // - `initiate_dunning` - prepayments and credits applied to the invoice; invoice status set to "open"; email sent to the customer for the issued invoice (if setting applies); payment failure recorded in the invoice history; subscription will most likely go into "past_due" or "canceled" state (depending upon net terms and dunning settings). + OnFailedPayment *FailedPaymentAction `json:"on_failed_payment,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for IssueInvoiceRequest. +// MarshalJSON implements the json.Marshaler interface for IssueInvoiceRequest. // It customizes the JSON marshaling process for IssueInvoiceRequest objects. func (i *IssueInvoiceRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the IssueInvoiceRequest object to a map representation for JSON marshaling. func (i *IssueInvoiceRequest) toMap() map[string]any { - structMap := make(map[string]any) - if i.OnFailedPayment != nil { - structMap["on_failed_payment"] = i.OnFailedPayment - } - return structMap + structMap := make(map[string]any) + if i.OnFailedPayment != nil { + structMap["on_failed_payment"] = i.OnFailedPayment + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for IssueInvoiceRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for IssueInvoiceRequest. // It customizes the JSON unmarshaling process for IssueInvoiceRequest objects. func (i *IssueInvoiceRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - OnFailedPayment *FailedPaymentAction `json:"on_failed_payment,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.OnFailedPayment = temp.OnFailedPayment - return nil + var temp issueInvoiceRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.OnFailedPayment = temp.OnFailedPayment + return nil +} + +// TODO +type issueInvoiceRequest struct { + OnFailedPayment *FailedPaymentAction `json:"on_failed_payment,omitempty"` } diff --git a/models/issue_service_credit.go b/models/issue_service_credit.go index ad25dcb5..a7987300 100644 --- a/models/issue_service_credit.go +++ b/models/issue_service_credit.go @@ -1,44 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // IssueServiceCredit represents a IssueServiceCredit struct. type IssueServiceCredit struct { - Amount interface{} `json:"amount"` - Memo string `json:"memo"` + Amount IssueServiceCreditAmount `json:"amount"` + Memo string `json:"memo"` } -// MarshalJSON implements the json.Marshaler interface for IssueServiceCredit. +// MarshalJSON implements the json.Marshaler interface for IssueServiceCredit. // It customizes the JSON marshaling process for IssueServiceCredit objects. func (i *IssueServiceCredit) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the IssueServiceCredit object to a map representation for JSON marshaling. func (i *IssueServiceCredit) toMap() map[string]any { - structMap := make(map[string]any) - structMap["amount"] = i.Amount - structMap["memo"] = i.Memo - return structMap + structMap := make(map[string]any) + structMap["amount"] = i.Amount.toMap() + structMap["memo"] = i.Memo + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for IssueServiceCredit. +// UnmarshalJSON implements the json.Unmarshaler interface for IssueServiceCredit. // It customizes the JSON unmarshaling process for IssueServiceCredit objects. func (i *IssueServiceCredit) UnmarshalJSON(input []byte) error { - temp := &struct { - Amount interface{} `json:"amount"` - Memo string `json:"memo"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.Amount = temp.Amount - i.Memo = temp.Memo - return nil + var temp issueServiceCredit + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + i.Amount = *temp.Amount + i.Memo = *temp.Memo + return nil +} + +// TODO +type issueServiceCredit struct { + Amount *IssueServiceCreditAmount `json:"amount"` + Memo *string `json:"memo"` +} + +func (i *issueServiceCredit) validate() error { + var errs []string + if i.Amount == nil { + errs = append(errs, "required field `amount` is missing for type `Issue Service Credit`") + } + if i.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Issue Service Credit`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/issue_service_credit_amount.go b/models/issue_service_credit_amount.go new file mode 100644 index 00000000..c2944f81 --- /dev/null +++ b/models/issue_service_credit_amount.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// IssueServiceCreditAmount represents a IssueServiceCreditAmount struct. +// This is a container for one-of cases. +type IssueServiceCreditAmount struct { + value any + isPrecision bool + isString bool +} + +// String converts the IssueServiceCreditAmount object to a string representation. +func (i IssueServiceCreditAmount) String() string { + if bytes, err := json.Marshal(i.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for IssueServiceCreditAmount. +// It customizes the JSON marshaling process for IssueServiceCreditAmount objects. +func (i *IssueServiceCreditAmount) MarshalJSON() ( + []byte, + error) { + if i.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.IssueServiceCreditAmountContainer.From*` functions to initialize the IssueServiceCreditAmount object.") + } + return json.Marshal(i.toMap()) +} + +// toMap converts the IssueServiceCreditAmount object to a map representation for JSON marshaling. +func (i *IssueServiceCreditAmount) toMap() any { + switch obj := i.value.(type) { + case *float64: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for IssueServiceCreditAmount. +// It customizes the JSON unmarshaling process for IssueServiceCreditAmount objects. +func (i *IssueServiceCreditAmount) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(float64), false, &i.isPrecision), + NewTypeHolder(new(string), false, &i.isString), + ) + + i.value = result + return err +} + +func (i *IssueServiceCreditAmount) AsPrecision() ( + *float64, + bool) { + if !i.isPrecision { + return nil, false + } + return i.value.(*float64), true +} + +func (i *IssueServiceCreditAmount) AsString() ( + *string, + bool) { + if !i.isString { + return nil, false + } + return i.value.(*string), true +} + +// internalIssueServiceCreditAmount represents a issueServiceCreditAmount struct. +// This is a container for one-of cases. +type internalIssueServiceCreditAmount struct{} + +var IssueServiceCreditAmountContainer internalIssueServiceCreditAmount + +func (i *internalIssueServiceCreditAmount) FromPrecision(val float64) IssueServiceCreditAmount { + return IssueServiceCreditAmount{value: &val} +} + +func (i *internalIssueServiceCreditAmount) FromString(val string) IssueServiceCreditAmount { + return IssueServiceCreditAmount{value: &val} +} diff --git a/models/issue_service_credit_request.go b/models/issue_service_credit_request.go index 28d21a75..6049b719 100644 --- a/models/issue_service_credit_request.go +++ b/models/issue_service_credit_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // IssueServiceCreditRequest represents a IssueServiceCreditRequest struct. type IssueServiceCreditRequest struct { - ServiceCredit IssueServiceCredit `json:"service_credit"` + ServiceCredit IssueServiceCredit `json:"service_credit"` } -// MarshalJSON implements the json.Marshaler interface for IssueServiceCreditRequest. +// MarshalJSON implements the json.Marshaler interface for IssueServiceCreditRequest. // It customizes the JSON marshaling process for IssueServiceCreditRequest objects. func (i *IssueServiceCreditRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(i.toMap()) + []byte, + error) { + return json.Marshal(i.toMap()) } // toMap converts the IssueServiceCreditRequest object to a map representation for JSON marshaling. func (i *IssueServiceCreditRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["service_credit"] = i.ServiceCredit.toMap() - return structMap + structMap := make(map[string]any) + structMap["service_credit"] = i.ServiceCredit.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for IssueServiceCreditRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for IssueServiceCreditRequest. // It customizes the JSON unmarshaling process for IssueServiceCreditRequest objects. func (i *IssueServiceCreditRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - ServiceCredit IssueServiceCredit `json:"service_credit"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - i.ServiceCredit = temp.ServiceCredit - return nil + var temp issueServiceCreditRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + i.ServiceCredit = *temp.ServiceCredit + return nil +} + +// TODO +type issueServiceCreditRequest struct { + ServiceCredit *IssueServiceCredit `json:"service_credit"` +} + +func (i *issueServiceCreditRequest) validate() error { + var errs []string + if i.ServiceCredit == nil { + errs = append(errs, "required field `service_credit` is missing for type `Issue Service Credit Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/item_price_point_changed.go b/models/item_price_point_changed.go new file mode 100644 index 00000000..1ea88f60 --- /dev/null +++ b/models/item_price_point_changed.go @@ -0,0 +1,95 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ItemPricePointChanged represents a ItemPricePointChanged struct. +type ItemPricePointChanged struct { + ItemId int `json:"item_id"` + ItemType string `json:"item_type"` + ItemHandle string `json:"item_handle"` + ItemName string `json:"item_name"` + PreviousPricePoint ItemPricePointData `json:"previous_price_point"` + CurrentPricePoint ItemPricePointData `json:"current_price_point"` +} + +// MarshalJSON implements the json.Marshaler interface for ItemPricePointChanged. +// It customizes the JSON marshaling process for ItemPricePointChanged objects. +func (i *ItemPricePointChanged) MarshalJSON() ( + []byte, + error) { + return json.Marshal(i.toMap()) +} + +// toMap converts the ItemPricePointChanged object to a map representation for JSON marshaling. +func (i *ItemPricePointChanged) toMap() map[string]any { + structMap := make(map[string]any) + structMap["item_id"] = i.ItemId + structMap["item_type"] = i.ItemType + structMap["item_handle"] = i.ItemHandle + structMap["item_name"] = i.ItemName + structMap["previous_price_point"] = i.PreviousPricePoint.toMap() + structMap["current_price_point"] = i.CurrentPricePoint.toMap() + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ItemPricePointChanged. +// It customizes the JSON unmarshaling process for ItemPricePointChanged objects. +func (i *ItemPricePointChanged) UnmarshalJSON(input []byte) error { + var temp itemPricePointChanged + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + i.ItemId = *temp.ItemId + i.ItemType = *temp.ItemType + i.ItemHandle = *temp.ItemHandle + i.ItemName = *temp.ItemName + i.PreviousPricePoint = *temp.PreviousPricePoint + i.CurrentPricePoint = *temp.CurrentPricePoint + return nil +} + +// TODO +type itemPricePointChanged struct { + ItemId *int `json:"item_id"` + ItemType *string `json:"item_type"` + ItemHandle *string `json:"item_handle"` + ItemName *string `json:"item_name"` + PreviousPricePoint *ItemPricePointData `json:"previous_price_point"` + CurrentPricePoint *ItemPricePointData `json:"current_price_point"` +} + +func (i *itemPricePointChanged) validate() error { + var errs []string + if i.ItemId == nil { + errs = append(errs, "required field `item_id` is missing for type `Item Price Point Changed`") + } + if i.ItemType == nil { + errs = append(errs, "required field `item_type` is missing for type `Item Price Point Changed`") + } + if i.ItemHandle == nil { + errs = append(errs, "required field `item_handle` is missing for type `Item Price Point Changed`") + } + if i.ItemName == nil { + errs = append(errs, "required field `item_name` is missing for type `Item Price Point Changed`") + } + if i.PreviousPricePoint == nil { + errs = append(errs, "required field `previous_price_point` is missing for type `Item Price Point Changed`") + } + if i.CurrentPricePoint == nil { + errs = append(errs, "required field `current_price_point` is missing for type `Item Price Point Changed`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/item_price_point_data.go b/models/item_price_point_data.go new file mode 100644 index 00000000..72acbeca --- /dev/null +++ b/models/item_price_point_data.go @@ -0,0 +1,56 @@ +package models + +import ( + "encoding/json" +) + +// ItemPricePointData represents a ItemPricePointData struct. +type ItemPricePointData struct { + Id *int `json:"id,omitempty"` + Handle *string `json:"handle,omitempty"` + Name *string `json:"name,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for ItemPricePointData. +// It customizes the JSON marshaling process for ItemPricePointData objects. +func (i *ItemPricePointData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(i.toMap()) +} + +// toMap converts the ItemPricePointData object to a map representation for JSON marshaling. +func (i *ItemPricePointData) toMap() map[string]any { + structMap := make(map[string]any) + if i.Id != nil { + structMap["id"] = i.Id + } + if i.Handle != nil { + structMap["handle"] = i.Handle + } + if i.Name != nil { + structMap["name"] = i.Name + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ItemPricePointData. +// It customizes the JSON unmarshaling process for ItemPricePointData objects. +func (i *ItemPricePointData) UnmarshalJSON(input []byte) error { + var temp itemPricePointData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + i.Id = temp.Id + i.Handle = temp.Handle + i.Name = temp.Name + return nil +} + +// TODO +type itemPricePointData struct { + Id *int `json:"id,omitempty"` + Handle *string `json:"handle,omitempty"` + Name *string `json:"name,omitempty"` +} diff --git a/models/list_components_price_points_response.go b/models/list_components_price_points_response.go index 9da3dd47..fec13671 100644 --- a/models/list_components_price_points_response.go +++ b/models/list_components_price_points_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ListComponentsPricePointsResponse represents a ListComponentsPricePointsResponse struct. type ListComponentsPricePointsResponse struct { - PricePoints []ComponentPricePoint `json:"price_points"` + PricePoints []ComponentPricePoint `json:"price_points"` } -// MarshalJSON implements the json.Marshaler interface for ListComponentsPricePointsResponse. +// MarshalJSON implements the json.Marshaler interface for ListComponentsPricePointsResponse. // It customizes the JSON marshaling process for ListComponentsPricePointsResponse objects. func (l *ListComponentsPricePointsResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListComponentsPricePointsResponse object to a map representation for JSON marshaling. func (l *ListComponentsPricePointsResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["price_points"] = l.PricePoints - return structMap + structMap := make(map[string]any) + structMap["price_points"] = l.PricePoints + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListComponentsPricePointsResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListComponentsPricePointsResponse. // It customizes the JSON unmarshaling process for ListComponentsPricePointsResponse objects. func (l *ListComponentsPricePointsResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoints []ComponentPricePoint `json:"price_points"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.PricePoints = temp.PricePoints - return nil + var temp listComponentsPricePointsResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + l.PricePoints = *temp.PricePoints + return nil +} + +// TODO +type listComponentsPricePointsResponse struct { + PricePoints *[]ComponentPricePoint `json:"price_points"` +} + +func (l *listComponentsPricePointsResponse) validate() error { + var errs []string + if l.PricePoints == nil { + errs = append(errs, "required field `price_points` is missing for type `List Components Price Points Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/list_credit_notes_response.go b/models/list_credit_notes_response.go index 981a6f72..a34e2023 100644 --- a/models/list_credit_notes_response.go +++ b/models/list_credit_notes_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ListCreditNotesResponse represents a ListCreditNotesResponse struct. type ListCreditNotesResponse struct { - CreditNotes []CreditNote `json:"credit_notes"` + CreditNotes []CreditNote `json:"credit_notes"` } -// MarshalJSON implements the json.Marshaler interface for ListCreditNotesResponse. +// MarshalJSON implements the json.Marshaler interface for ListCreditNotesResponse. // It customizes the JSON marshaling process for ListCreditNotesResponse objects. func (l *ListCreditNotesResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListCreditNotesResponse object to a map representation for JSON marshaling. func (l *ListCreditNotesResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["credit_notes"] = l.CreditNotes - return structMap + structMap := make(map[string]any) + structMap["credit_notes"] = l.CreditNotes + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListCreditNotesResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListCreditNotesResponse. // It customizes the JSON unmarshaling process for ListCreditNotesResponse objects. func (l *ListCreditNotesResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - CreditNotes []CreditNote `json:"credit_notes"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.CreditNotes = temp.CreditNotes - return nil + var temp listCreditNotesResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + l.CreditNotes = *temp.CreditNotes + return nil +} + +// TODO +type listCreditNotesResponse struct { + CreditNotes *[]CreditNote `json:"credit_notes"` +} + +func (l *listCreditNotesResponse) validate() error { + var errs []string + if l.CreditNotes == nil { + errs = append(errs, "required field `credit_notes` is missing for type `List Credit Notes Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/list_invoice_events_response.go b/models/list_invoice_events_response.go index 7cdfe241..96203586 100644 --- a/models/list_invoice_events_response.go +++ b/models/list_invoice_events_response.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListInvoiceEventsResponse represents a ListInvoiceEventsResponse struct. type ListInvoiceEventsResponse struct { - Events []InvoiceEvent `json:"events,omitempty"` - Page *int `json:"page,omitempty"` - PerPage *int `json:"per_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` + Events []InvoiceEvent `json:"events,omitempty"` + Page *int `json:"page,omitempty"` + PerPage *int `json:"per_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListInvoiceEventsResponse. +// MarshalJSON implements the json.Marshaler interface for ListInvoiceEventsResponse. // It customizes the JSON marshaling process for ListInvoiceEventsResponse objects. func (l *ListInvoiceEventsResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListInvoiceEventsResponse object to a map representation for JSON marshaling. func (l *ListInvoiceEventsResponse) toMap() map[string]any { - structMap := make(map[string]any) - if l.Events != nil { - structMap["events"] = l.Events - } - if l.Page != nil { - structMap["page"] = l.Page - } - if l.PerPage != nil { - structMap["per_page"] = l.PerPage - } - if l.TotalPages != nil { - structMap["total_pages"] = l.TotalPages - } - return structMap + structMap := make(map[string]any) + if l.Events != nil { + structMap["events"] = l.Events + } + if l.Page != nil { + structMap["page"] = l.Page + } + if l.PerPage != nil { + structMap["per_page"] = l.PerPage + } + if l.TotalPages != nil { + structMap["total_pages"] = l.TotalPages + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListInvoiceEventsResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListInvoiceEventsResponse. // It customizes the JSON unmarshaling process for ListInvoiceEventsResponse objects. func (l *ListInvoiceEventsResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Events []InvoiceEvent `json:"events,omitempty"` - Page *int `json:"page,omitempty"` - PerPage *int `json:"per_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.Events = temp.Events - l.Page = temp.Page - l.PerPage = temp.PerPage - l.TotalPages = temp.TotalPages - return nil + var temp listInvoiceEventsResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.Events = temp.Events + l.Page = temp.Page + l.PerPage = temp.PerPage + l.TotalPages = temp.TotalPages + return nil +} + +// TODO +type listInvoiceEventsResponse struct { + Events []InvoiceEvent `json:"events,omitempty"` + Page *int `json:"page,omitempty"` + PerPage *int `json:"per_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` } diff --git a/models/list_invoices_response.go b/models/list_invoices_response.go index aa5a8012..b9d7f5df 100644 --- a/models/list_invoices_response.go +++ b/models/list_invoices_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ListInvoicesResponse represents a ListInvoicesResponse struct. type ListInvoicesResponse struct { - Invoices []Invoice `json:"invoices"` + Invoices []Invoice `json:"invoices"` } -// MarshalJSON implements the json.Marshaler interface for ListInvoicesResponse. +// MarshalJSON implements the json.Marshaler interface for ListInvoicesResponse. // It customizes the JSON marshaling process for ListInvoicesResponse objects. func (l *ListInvoicesResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListInvoicesResponse object to a map representation for JSON marshaling. func (l *ListInvoicesResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["invoices"] = l.Invoices - return structMap + structMap := make(map[string]any) + structMap["invoices"] = l.Invoices + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListInvoicesResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListInvoicesResponse. // It customizes the JSON unmarshaling process for ListInvoicesResponse objects. func (l *ListInvoicesResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Invoices []Invoice `json:"invoices"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.Invoices = temp.Invoices - return nil + var temp listInvoicesResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + l.Invoices = *temp.Invoices + return nil +} + +// TODO +type listInvoicesResponse struct { + Invoices *[]Invoice `json:"invoices"` +} + +func (l *listInvoicesResponse) validate() error { + var errs []string + if l.Invoices == nil { + errs = append(errs, "required field `invoices` is missing for type `List Invoices Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/list_metafields_response.go b/models/list_metafields_response.go index e915834f..201c37ac 100644 --- a/models/list_metafields_response.go +++ b/models/list_metafields_response.go @@ -1,66 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListMetafieldsResponse represents a ListMetafieldsResponse struct. type ListMetafieldsResponse struct { - TotalCount *int `json:"total_count,omitempty"` - CurrentPage *int `json:"current_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` - PerPage *int `json:"per_page,omitempty"` - Metafields []Metafield `json:"metafields,omitempty"` + TotalCount *int `json:"total_count,omitempty"` + CurrentPage *int `json:"current_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` + PerPage *int `json:"per_page,omitempty"` + Metafields []Metafield `json:"metafields,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListMetafieldsResponse. +// MarshalJSON implements the json.Marshaler interface for ListMetafieldsResponse. // It customizes the JSON marshaling process for ListMetafieldsResponse objects. func (l *ListMetafieldsResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListMetafieldsResponse object to a map representation for JSON marshaling. func (l *ListMetafieldsResponse) toMap() map[string]any { - structMap := make(map[string]any) - if l.TotalCount != nil { - structMap["total_count"] = l.TotalCount - } - if l.CurrentPage != nil { - structMap["current_page"] = l.CurrentPage - } - if l.TotalPages != nil { - structMap["total_pages"] = l.TotalPages - } - if l.PerPage != nil { - structMap["per_page"] = l.PerPage - } - if l.Metafields != nil { - structMap["metafields"] = l.Metafields - } - return structMap + structMap := make(map[string]any) + if l.TotalCount != nil { + structMap["total_count"] = l.TotalCount + } + if l.CurrentPage != nil { + structMap["current_page"] = l.CurrentPage + } + if l.TotalPages != nil { + structMap["total_pages"] = l.TotalPages + } + if l.PerPage != nil { + structMap["per_page"] = l.PerPage + } + if l.Metafields != nil { + structMap["metafields"] = l.Metafields + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListMetafieldsResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListMetafieldsResponse. // It customizes the JSON unmarshaling process for ListMetafieldsResponse objects. func (l *ListMetafieldsResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - TotalCount *int `json:"total_count,omitempty"` - CurrentPage *int `json:"current_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` - PerPage *int `json:"per_page,omitempty"` - Metafields []Metafield `json:"metafields,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.TotalCount = temp.TotalCount - l.CurrentPage = temp.CurrentPage - l.TotalPages = temp.TotalPages - l.PerPage = temp.PerPage - l.Metafields = temp.Metafields - return nil + var temp listMetafieldsResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.TotalCount = temp.TotalCount + l.CurrentPage = temp.CurrentPage + l.TotalPages = temp.TotalPages + l.PerPage = temp.PerPage + l.Metafields = temp.Metafields + return nil +} + +// TODO +type listMetafieldsResponse struct { + TotalCount *int `json:"total_count,omitempty"` + CurrentPage *int `json:"current_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` + PerPage *int `json:"per_page,omitempty"` + Metafields []Metafield `json:"metafields,omitempty"` } diff --git a/models/list_mrr_response.go b/models/list_mrr_response.go index 2e61cebf..aea659bb 100644 --- a/models/list_mrr_response.go +++ b/models/list_mrr_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ListMRRResponse represents a ListMRRResponse struct. type ListMRRResponse struct { - Mrr ListMRRResponseResult `json:"mrr"` + Mrr ListMRRResponseResult `json:"mrr"` } -// MarshalJSON implements the json.Marshaler interface for ListMRRResponse. +// MarshalJSON implements the json.Marshaler interface for ListMRRResponse. // It customizes the JSON marshaling process for ListMRRResponse objects. func (l *ListMRRResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListMRRResponse object to a map representation for JSON marshaling. func (l *ListMRRResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["mrr"] = l.Mrr.toMap() - return structMap + structMap := make(map[string]any) + structMap["mrr"] = l.Mrr.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListMRRResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListMRRResponse. // It customizes the JSON unmarshaling process for ListMRRResponse objects. func (l *ListMRRResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Mrr ListMRRResponseResult `json:"mrr"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.Mrr = temp.Mrr - return nil + var temp listMRRResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + l.Mrr = *temp.Mrr + return nil +} + +// TODO +type listMRRResponse struct { + Mrr *ListMRRResponseResult `json:"mrr"` +} + +func (l *listMRRResponse) validate() error { + var errs []string + if l.Mrr == nil { + errs = append(errs, "required field `mrr` is missing for type `List MRR Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/list_mrr_response_result.go b/models/list_mrr_response_result.go index 96324824..7c12b06a 100644 --- a/models/list_mrr_response_result.go +++ b/models/list_mrr_response_result.go @@ -1,78 +1,80 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListMRRResponseResult represents a ListMRRResponseResult struct. type ListMRRResponseResult struct { - Page *int `json:"page,omitempty"` - PerPage *int `json:"per_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` - TotalEntries *int `json:"total_entries,omitempty"` - Currency *string `json:"currency,omitempty"` - CurrencySymbol *string `json:"currency_symbol,omitempty"` - Movements []Movement `json:"movements,omitempty"` + Page *int `json:"page,omitempty"` + PerPage *int `json:"per_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` + TotalEntries *int `json:"total_entries,omitempty"` + Currency *string `json:"currency,omitempty"` + CurrencySymbol *string `json:"currency_symbol,omitempty"` + Movements []Movement `json:"movements,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListMRRResponseResult. +// MarshalJSON implements the json.Marshaler interface for ListMRRResponseResult. // It customizes the JSON marshaling process for ListMRRResponseResult objects. func (l *ListMRRResponseResult) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListMRRResponseResult object to a map representation for JSON marshaling. func (l *ListMRRResponseResult) toMap() map[string]any { - structMap := make(map[string]any) - if l.Page != nil { - structMap["page"] = l.Page - } - if l.PerPage != nil { - structMap["per_page"] = l.PerPage - } - if l.TotalPages != nil { - structMap["total_pages"] = l.TotalPages - } - if l.TotalEntries != nil { - structMap["total_entries"] = l.TotalEntries - } - if l.Currency != nil { - structMap["currency"] = l.Currency - } - if l.CurrencySymbol != nil { - structMap["currency_symbol"] = l.CurrencySymbol - } - if l.Movements != nil { - structMap["movements"] = l.Movements - } - return structMap + structMap := make(map[string]any) + if l.Page != nil { + structMap["page"] = l.Page + } + if l.PerPage != nil { + structMap["per_page"] = l.PerPage + } + if l.TotalPages != nil { + structMap["total_pages"] = l.TotalPages + } + if l.TotalEntries != nil { + structMap["total_entries"] = l.TotalEntries + } + if l.Currency != nil { + structMap["currency"] = l.Currency + } + if l.CurrencySymbol != nil { + structMap["currency_symbol"] = l.CurrencySymbol + } + if l.Movements != nil { + structMap["movements"] = l.Movements + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListMRRResponseResult. +// UnmarshalJSON implements the json.Unmarshaler interface for ListMRRResponseResult. // It customizes the JSON unmarshaling process for ListMRRResponseResult objects. func (l *ListMRRResponseResult) UnmarshalJSON(input []byte) error { - temp := &struct { - Page *int `json:"page,omitempty"` - PerPage *int `json:"per_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` - TotalEntries *int `json:"total_entries,omitempty"` - Currency *string `json:"currency,omitempty"` - CurrencySymbol *string `json:"currency_symbol,omitempty"` - Movements []Movement `json:"movements,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.Page = temp.Page - l.PerPage = temp.PerPage - l.TotalPages = temp.TotalPages - l.TotalEntries = temp.TotalEntries - l.Currency = temp.Currency - l.CurrencySymbol = temp.CurrencySymbol - l.Movements = temp.Movements - return nil + var temp listMRRResponseResult + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.Page = temp.Page + l.PerPage = temp.PerPage + l.TotalPages = temp.TotalPages + l.TotalEntries = temp.TotalEntries + l.Currency = temp.Currency + l.CurrencySymbol = temp.CurrencySymbol + l.Movements = temp.Movements + return nil +} + +// TODO +type listMRRResponseResult struct { + Page *int `json:"page,omitempty"` + PerPage *int `json:"per_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` + TotalEntries *int `json:"total_entries,omitempty"` + Currency *string `json:"currency,omitempty"` + CurrencySymbol *string `json:"currency_symbol,omitempty"` + Movements []Movement `json:"movements,omitempty"` } diff --git a/models/list_offers_response.go b/models/list_offers_response.go index b0aec3cc..77c227cd 100644 --- a/models/list_offers_response.go +++ b/models/list_offers_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListOffersResponse represents a ListOffersResponse struct. type ListOffersResponse struct { - Offers []Offer `json:"offers,omitempty"` + Offers []Offer `json:"offers,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListOffersResponse. +// MarshalJSON implements the json.Marshaler interface for ListOffersResponse. // It customizes the JSON marshaling process for ListOffersResponse objects. func (l *ListOffersResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListOffersResponse object to a map representation for JSON marshaling. func (l *ListOffersResponse) toMap() map[string]any { - structMap := make(map[string]any) - if l.Offers != nil { - structMap["offers"] = l.Offers - } - return structMap + structMap := make(map[string]any) + if l.Offers != nil { + structMap["offers"] = l.Offers + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListOffersResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListOffersResponse. // It customizes the JSON unmarshaling process for ListOffersResponse objects. func (l *ListOffersResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Offers []Offer `json:"offers,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.Offers = temp.Offers - return nil + var temp listOffersResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.Offers = temp.Offers + return nil +} + +// TODO +type listOffersResponse struct { + Offers []Offer `json:"offers,omitempty"` } diff --git a/models/list_product_price_points_input_product_id.go b/models/list_product_price_points_input_product_id.go new file mode 100644 index 00000000..4fb6bc03 --- /dev/null +++ b/models/list_product_price_points_input_product_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ListProductPricePointsInputProductId represents a ListProductPricePointsInputProductId struct. +// This is a container for one-of cases. +type ListProductPricePointsInputProductId struct { + value any + isNumber bool + isString bool +} + +// String converts the ListProductPricePointsInputProductId object to a string representation. +func (l ListProductPricePointsInputProductId) String() string { + if bytes, err := json.Marshal(l.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ListProductPricePointsInputProductId. +// It customizes the JSON marshaling process for ListProductPricePointsInputProductId objects. +func (l *ListProductPricePointsInputProductId) MarshalJSON() ( + []byte, + error) { + if l.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ListProductPricePointsInputProductIdContainer.From*` functions to initialize the ListProductPricePointsInputProductId object.") + } + return json.Marshal(l.toMap()) +} + +// toMap converts the ListProductPricePointsInputProductId object to a map representation for JSON marshaling. +func (l *ListProductPricePointsInputProductId) toMap() any { + switch obj := l.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ListProductPricePointsInputProductId. +// It customizes the JSON unmarshaling process for ListProductPricePointsInputProductId objects. +func (l *ListProductPricePointsInputProductId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &l.isNumber), + NewTypeHolder(new(string), false, &l.isString), + ) + + l.value = result + return err +} + +func (l *ListProductPricePointsInputProductId) AsNumber() ( + *int, + bool) { + if !l.isNumber { + return nil, false + } + return l.value.(*int), true +} + +func (l *ListProductPricePointsInputProductId) AsString() ( + *string, + bool) { + if !l.isString { + return nil, false + } + return l.value.(*string), true +} + +// internalListProductPricePointsInputProductId represents a listProductPricePointsInputProductId struct. +// This is a container for one-of cases. +type internalListProductPricePointsInputProductId struct{} + +var ListProductPricePointsInputProductIdContainer internalListProductPricePointsInputProductId + +func (l *internalListProductPricePointsInputProductId) FromNumber(val int) ListProductPricePointsInputProductId { + return ListProductPricePointsInputProductId{value: &val} +} + +func (l *internalListProductPricePointsInputProductId) FromString(val string) ListProductPricePointsInputProductId { + return ListProductPricePointsInputProductId{value: &val} +} diff --git a/models/list_product_price_points_response.go b/models/list_product_price_points_response.go index fb149bb3..00bfb1ef 100644 --- a/models/list_product_price_points_response.go +++ b/models/list_product_price_points_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ListProductPricePointsResponse represents a ListProductPricePointsResponse struct. type ListProductPricePointsResponse struct { - PricePoints []ProductPricePoint `json:"price_points"` + PricePoints []ProductPricePoint `json:"price_points"` } -// MarshalJSON implements the json.Marshaler interface for ListProductPricePointsResponse. +// MarshalJSON implements the json.Marshaler interface for ListProductPricePointsResponse. // It customizes the JSON marshaling process for ListProductPricePointsResponse objects. func (l *ListProductPricePointsResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListProductPricePointsResponse object to a map representation for JSON marshaling. func (l *ListProductPricePointsResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["price_points"] = l.PricePoints - return structMap + structMap := make(map[string]any) + structMap["price_points"] = l.PricePoints + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListProductPricePointsResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListProductPricePointsResponse. // It customizes the JSON unmarshaling process for ListProductPricePointsResponse objects. func (l *ListProductPricePointsResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoints []ProductPricePoint `json:"price_points"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.PricePoints = temp.PricePoints - return nil + var temp listProductPricePointsResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + l.PricePoints = *temp.PricePoints + return nil +} + +// TODO +type listProductPricePointsResponse struct { + PricePoints *[]ProductPricePoint `json:"price_points"` +} + +func (l *listProductPricePointsResponse) validate() error { + var errs []string + if l.PricePoints == nil { + errs = append(errs, "required field `price_points` is missing for type `List Product Price Points Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/list_proforma_invoices_meta.go b/models/list_proforma_invoices_meta.go index c3f4a821..0dc070c0 100644 --- a/models/list_proforma_invoices_meta.go +++ b/models/list_proforma_invoices_meta.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListProformaInvoicesMeta represents a ListProformaInvoicesMeta struct. type ListProformaInvoicesMeta struct { - TotalCount *int `json:"total_count,omitempty"` - CurrentPage *int `json:"current_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` - StatusCode *int `json:"status_code,omitempty"` + TotalCount *int `json:"total_count,omitempty"` + CurrentPage *int `json:"current_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` + StatusCode *int `json:"status_code,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListProformaInvoicesMeta. +// MarshalJSON implements the json.Marshaler interface for ListProformaInvoicesMeta. // It customizes the JSON marshaling process for ListProformaInvoicesMeta objects. func (l *ListProformaInvoicesMeta) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListProformaInvoicesMeta object to a map representation for JSON marshaling. func (l *ListProformaInvoicesMeta) toMap() map[string]any { - structMap := make(map[string]any) - if l.TotalCount != nil { - structMap["total_count"] = l.TotalCount - } - if l.CurrentPage != nil { - structMap["current_page"] = l.CurrentPage - } - if l.TotalPages != nil { - structMap["total_pages"] = l.TotalPages - } - if l.StatusCode != nil { - structMap["status_code"] = l.StatusCode - } - return structMap + structMap := make(map[string]any) + if l.TotalCount != nil { + structMap["total_count"] = l.TotalCount + } + if l.CurrentPage != nil { + structMap["current_page"] = l.CurrentPage + } + if l.TotalPages != nil { + structMap["total_pages"] = l.TotalPages + } + if l.StatusCode != nil { + structMap["status_code"] = l.StatusCode + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListProformaInvoicesMeta. +// UnmarshalJSON implements the json.Unmarshaler interface for ListProformaInvoicesMeta. // It customizes the JSON unmarshaling process for ListProformaInvoicesMeta objects. func (l *ListProformaInvoicesMeta) UnmarshalJSON(input []byte) error { - temp := &struct { - TotalCount *int `json:"total_count,omitempty"` - CurrentPage *int `json:"current_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` - StatusCode *int `json:"status_code,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.TotalCount = temp.TotalCount - l.CurrentPage = temp.CurrentPage - l.TotalPages = temp.TotalPages - l.StatusCode = temp.StatusCode - return nil + var temp listProformaInvoicesMeta + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.TotalCount = temp.TotalCount + l.CurrentPage = temp.CurrentPage + l.TotalPages = temp.TotalPages + l.StatusCode = temp.StatusCode + return nil +} + +// TODO +type listProformaInvoicesMeta struct { + TotalCount *int `json:"total_count,omitempty"` + CurrentPage *int `json:"current_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` + StatusCode *int `json:"status_code,omitempty"` } diff --git a/models/list_proforma_invoices_response.go b/models/list_proforma_invoices_response.go index 1ee38e61..0987dec3 100644 --- a/models/list_proforma_invoices_response.go +++ b/models/list_proforma_invoices_response.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListProformaInvoicesResponse represents a ListProformaInvoicesResponse struct. type ListProformaInvoicesResponse struct { - ProformaInvoices []ProformaInvoice `json:"proforma_invoices,omitempty"` - Meta *ListProformaInvoicesMeta `json:"meta,omitempty"` + ProformaInvoices []ProformaInvoice `json:"proforma_invoices,omitempty"` + Meta *ListProformaInvoicesMeta `json:"meta,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListProformaInvoicesResponse. +// MarshalJSON implements the json.Marshaler interface for ListProformaInvoicesResponse. // It customizes the JSON marshaling process for ListProformaInvoicesResponse objects. func (l *ListProformaInvoicesResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListProformaInvoicesResponse object to a map representation for JSON marshaling. func (l *ListProformaInvoicesResponse) toMap() map[string]any { - structMap := make(map[string]any) - if l.ProformaInvoices != nil { - structMap["proforma_invoices"] = l.ProformaInvoices - } - if l.Meta != nil { - structMap["meta"] = l.Meta.toMap() - } - return structMap + structMap := make(map[string]any) + if l.ProformaInvoices != nil { + structMap["proforma_invoices"] = l.ProformaInvoices + } + if l.Meta != nil { + structMap["meta"] = l.Meta.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListProformaInvoicesResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListProformaInvoicesResponse. // It customizes the JSON unmarshaling process for ListProformaInvoicesResponse objects. func (l *ListProformaInvoicesResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - ProformaInvoices []ProformaInvoice `json:"proforma_invoices,omitempty"` - Meta *ListProformaInvoicesMeta `json:"meta,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.ProformaInvoices = temp.ProformaInvoices - l.Meta = temp.Meta - return nil + var temp listProformaInvoicesResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.ProformaInvoices = temp.ProformaInvoices + l.Meta = temp.Meta + return nil +} + +// TODO +type listProformaInvoicesResponse struct { + ProformaInvoices []ProformaInvoice `json:"proforma_invoices,omitempty"` + Meta *ListProformaInvoicesMeta `json:"meta,omitempty"` } diff --git a/models/list_public_keys_meta.go b/models/list_public_keys_meta.go index 3ea75a32..2dab974a 100644 --- a/models/list_public_keys_meta.go +++ b/models/list_public_keys_meta.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListPublicKeysMeta represents a ListPublicKeysMeta struct. type ListPublicKeysMeta struct { - TotalCount *int `json:"total_count,omitempty"` - CurrentPage *int `json:"current_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` - PerPage *int `json:"per_page,omitempty"` + TotalCount *int `json:"total_count,omitempty"` + CurrentPage *int `json:"current_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` + PerPage *int `json:"per_page,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListPublicKeysMeta. +// MarshalJSON implements the json.Marshaler interface for ListPublicKeysMeta. // It customizes the JSON marshaling process for ListPublicKeysMeta objects. func (l *ListPublicKeysMeta) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListPublicKeysMeta object to a map representation for JSON marshaling. func (l *ListPublicKeysMeta) toMap() map[string]any { - structMap := make(map[string]any) - if l.TotalCount != nil { - structMap["total_count"] = l.TotalCount - } - if l.CurrentPage != nil { - structMap["current_page"] = l.CurrentPage - } - if l.TotalPages != nil { - structMap["total_pages"] = l.TotalPages - } - if l.PerPage != nil { - structMap["per_page"] = l.PerPage - } - return structMap + structMap := make(map[string]any) + if l.TotalCount != nil { + structMap["total_count"] = l.TotalCount + } + if l.CurrentPage != nil { + structMap["current_page"] = l.CurrentPage + } + if l.TotalPages != nil { + structMap["total_pages"] = l.TotalPages + } + if l.PerPage != nil { + structMap["per_page"] = l.PerPage + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListPublicKeysMeta. +// UnmarshalJSON implements the json.Unmarshaler interface for ListPublicKeysMeta. // It customizes the JSON unmarshaling process for ListPublicKeysMeta objects. func (l *ListPublicKeysMeta) UnmarshalJSON(input []byte) error { - temp := &struct { - TotalCount *int `json:"total_count,omitempty"` - CurrentPage *int `json:"current_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` - PerPage *int `json:"per_page,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.TotalCount = temp.TotalCount - l.CurrentPage = temp.CurrentPage - l.TotalPages = temp.TotalPages - l.PerPage = temp.PerPage - return nil + var temp listPublicKeysMeta + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.TotalCount = temp.TotalCount + l.CurrentPage = temp.CurrentPage + l.TotalPages = temp.TotalPages + l.PerPage = temp.PerPage + return nil +} + +// TODO +type listPublicKeysMeta struct { + TotalCount *int `json:"total_count,omitempty"` + CurrentPage *int `json:"current_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` + PerPage *int `json:"per_page,omitempty"` } diff --git a/models/list_public_keys_response.go b/models/list_public_keys_response.go index 33b7ee9a..e298ed17 100644 --- a/models/list_public_keys_response.go +++ b/models/list_public_keys_response.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListPublicKeysResponse represents a ListPublicKeysResponse struct. type ListPublicKeysResponse struct { - ChargifyJsKeys []PublicKey `json:"chargify_js_keys,omitempty"` - Meta *ListPublicKeysMeta `json:"meta,omitempty"` + ChargifyJsKeys []PublicKey `json:"chargify_js_keys,omitempty"` + Meta *ListPublicKeysMeta `json:"meta,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListPublicKeysResponse. +// MarshalJSON implements the json.Marshaler interface for ListPublicKeysResponse. // It customizes the JSON marshaling process for ListPublicKeysResponse objects. func (l *ListPublicKeysResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListPublicKeysResponse object to a map representation for JSON marshaling. func (l *ListPublicKeysResponse) toMap() map[string]any { - structMap := make(map[string]any) - if l.ChargifyJsKeys != nil { - structMap["chargify_js_keys"] = l.ChargifyJsKeys - } - if l.Meta != nil { - structMap["meta"] = l.Meta.toMap() - } - return structMap + structMap := make(map[string]any) + if l.ChargifyJsKeys != nil { + structMap["chargify_js_keys"] = l.ChargifyJsKeys + } + if l.Meta != nil { + structMap["meta"] = l.Meta.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListPublicKeysResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListPublicKeysResponse. // It customizes the JSON unmarshaling process for ListPublicKeysResponse objects. func (l *ListPublicKeysResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - ChargifyJsKeys []PublicKey `json:"chargify_js_keys,omitempty"` - Meta *ListPublicKeysMeta `json:"meta,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.ChargifyJsKeys = temp.ChargifyJsKeys - l.Meta = temp.Meta - return nil + var temp listPublicKeysResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.ChargifyJsKeys = temp.ChargifyJsKeys + l.Meta = temp.Meta + return nil +} + +// TODO +type listPublicKeysResponse struct { + ChargifyJsKeys []PublicKey `json:"chargify_js_keys,omitempty"` + Meta *ListPublicKeysMeta `json:"meta,omitempty"` } diff --git a/models/list_sale_rep_item.go b/models/list_sale_rep_item.go index a1fd69c9..c5cb1b23 100644 --- a/models/list_sale_rep_item.go +++ b/models/list_sale_rep_item.go @@ -1,66 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListSaleRepItem represents a ListSaleRepItem struct. type ListSaleRepItem struct { - Id *int `json:"id,omitempty"` - FullName *string `json:"full_name,omitempty"` - SubscriptionsCount *int `json:"subscriptions_count,omitempty"` - MrrData map[string]SaleRepItemMrr `json:"mrr_data,omitempty"` - TestMode *bool `json:"test_mode,omitempty"` + Id *int `json:"id,omitempty"` + FullName *string `json:"full_name,omitempty"` + SubscriptionsCount *int `json:"subscriptions_count,omitempty"` + MrrData map[string]SaleRepItemMrr `json:"mrr_data,omitempty"` + TestMode *bool `json:"test_mode,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListSaleRepItem. +// MarshalJSON implements the json.Marshaler interface for ListSaleRepItem. // It customizes the JSON marshaling process for ListSaleRepItem objects. func (l *ListSaleRepItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListSaleRepItem object to a map representation for JSON marshaling. func (l *ListSaleRepItem) toMap() map[string]any { - structMap := make(map[string]any) - if l.Id != nil { - structMap["id"] = l.Id - } - if l.FullName != nil { - structMap["full_name"] = l.FullName - } - if l.SubscriptionsCount != nil { - structMap["subscriptions_count"] = l.SubscriptionsCount - } - if l.MrrData != nil { - structMap["mrr_data"] = l.MrrData - } - if l.TestMode != nil { - structMap["test_mode"] = l.TestMode - } - return structMap + structMap := make(map[string]any) + if l.Id != nil { + structMap["id"] = l.Id + } + if l.FullName != nil { + structMap["full_name"] = l.FullName + } + if l.SubscriptionsCount != nil { + structMap["subscriptions_count"] = l.SubscriptionsCount + } + if l.MrrData != nil { + structMap["mrr_data"] = l.MrrData + } + if l.TestMode != nil { + structMap["test_mode"] = l.TestMode + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListSaleRepItem. +// UnmarshalJSON implements the json.Unmarshaler interface for ListSaleRepItem. // It customizes the JSON unmarshaling process for ListSaleRepItem objects. func (l *ListSaleRepItem) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - FullName *string `json:"full_name,omitempty"` - SubscriptionsCount *int `json:"subscriptions_count,omitempty"` - MrrData map[string]SaleRepItemMrr `json:"mrr_data,omitempty"` - TestMode *bool `json:"test_mode,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.Id = temp.Id - l.FullName = temp.FullName - l.SubscriptionsCount = temp.SubscriptionsCount - l.MrrData = temp.MrrData - l.TestMode = temp.TestMode - return nil + var temp listSaleRepItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.Id = temp.Id + l.FullName = temp.FullName + l.SubscriptionsCount = temp.SubscriptionsCount + l.MrrData = temp.MrrData + l.TestMode = temp.TestMode + return nil +} + +// TODO +type listSaleRepItem struct { + Id *int `json:"id,omitempty"` + FullName *string `json:"full_name,omitempty"` + SubscriptionsCount *int `json:"subscriptions_count,omitempty"` + MrrData map[string]SaleRepItemMrr `json:"mrr_data,omitempty"` + TestMode *bool `json:"test_mode,omitempty"` } diff --git a/models/list_segments_response.go b/models/list_segments_response.go index 5bc7cbb3..56bf2090 100644 --- a/models/list_segments_response.go +++ b/models/list_segments_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListSegmentsResponse represents a ListSegmentsResponse struct. type ListSegmentsResponse struct { - Segments []Segment `json:"segments,omitempty"` + Segments []Segment `json:"segments,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListSegmentsResponse. +// MarshalJSON implements the json.Marshaler interface for ListSegmentsResponse. // It customizes the JSON marshaling process for ListSegmentsResponse objects. func (l *ListSegmentsResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListSegmentsResponse object to a map representation for JSON marshaling. func (l *ListSegmentsResponse) toMap() map[string]any { - structMap := make(map[string]any) - if l.Segments != nil { - structMap["segments"] = l.Segments - } - return structMap + structMap := make(map[string]any) + if l.Segments != nil { + structMap["segments"] = l.Segments + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListSegmentsResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListSegmentsResponse. // It customizes the JSON unmarshaling process for ListSegmentsResponse objects. func (l *ListSegmentsResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Segments []Segment `json:"segments,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.Segments = temp.Segments - return nil + var temp listSegmentsResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.Segments = temp.Segments + return nil +} + +// TODO +type listSegmentsResponse struct { + Segments []Segment `json:"segments,omitempty"` } diff --git a/models/list_subcription_group_prepayment_item.go b/models/list_subcription_group_prepayment_item.go index cbff3f8c..c071efee 100644 --- a/models/list_subcription_group_prepayment_item.go +++ b/models/list_subcription_group_prepayment_item.go @@ -1,98 +1,100 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // ListSubcriptionGroupPrepaymentItem represents a ListSubcriptionGroupPrepaymentItem struct. type ListSubcriptionGroupPrepaymentItem struct { - Id *int `json:"id,omitempty"` - SubscriptionGroupUid *string `json:"subscription_group_uid,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - RemainingAmountInCents *int64 `json:"remaining_amount_in_cents,omitempty"` - Details *string `json:"details,omitempty"` - External *bool `json:"external,omitempty"` - Memo *string `json:"memo,omitempty"` - PaymentType *PrepaymentMethod `json:"payment_type,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` + Id *int `json:"id,omitempty"` + SubscriptionGroupUid *string `json:"subscription_group_uid,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + RemainingAmountInCents *int64 `json:"remaining_amount_in_cents,omitempty"` + Details *string `json:"details,omitempty"` + External *bool `json:"external,omitempty"` + Memo *string `json:"memo,omitempty"` + PaymentType *PrepaymentMethod `json:"payment_type,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListSubcriptionGroupPrepaymentItem. +// MarshalJSON implements the json.Marshaler interface for ListSubcriptionGroupPrepaymentItem. // It customizes the JSON marshaling process for ListSubcriptionGroupPrepaymentItem objects. func (l *ListSubcriptionGroupPrepaymentItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListSubcriptionGroupPrepaymentItem object to a map representation for JSON marshaling. func (l *ListSubcriptionGroupPrepaymentItem) toMap() map[string]any { - structMap := make(map[string]any) - if l.Id != nil { - structMap["id"] = l.Id - } - if l.SubscriptionGroupUid != nil { - structMap["subscription_group_uid"] = l.SubscriptionGroupUid - } - if l.AmountInCents != nil { - structMap["amount_in_cents"] = l.AmountInCents - } - if l.RemainingAmountInCents != nil { - structMap["remaining_amount_in_cents"] = l.RemainingAmountInCents - } - if l.Details != nil { - structMap["details"] = l.Details - } - if l.External != nil { - structMap["external"] = l.External - } - if l.Memo != nil { - structMap["memo"] = l.Memo - } - if l.PaymentType != nil { - structMap["payment_type"] = l.PaymentType - } - if l.CreatedAt != nil { - structMap["created_at"] = l.CreatedAt.Format(time.RFC3339) - } - return structMap + structMap := make(map[string]any) + if l.Id != nil { + structMap["id"] = l.Id + } + if l.SubscriptionGroupUid != nil { + structMap["subscription_group_uid"] = l.SubscriptionGroupUid + } + if l.AmountInCents != nil { + structMap["amount_in_cents"] = l.AmountInCents + } + if l.RemainingAmountInCents != nil { + structMap["remaining_amount_in_cents"] = l.RemainingAmountInCents + } + if l.Details != nil { + structMap["details"] = l.Details + } + if l.External != nil { + structMap["external"] = l.External + } + if l.Memo != nil { + structMap["memo"] = l.Memo + } + if l.PaymentType != nil { + structMap["payment_type"] = l.PaymentType + } + if l.CreatedAt != nil { + structMap["created_at"] = l.CreatedAt.Format(time.RFC3339) + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListSubcriptionGroupPrepaymentItem. +// UnmarshalJSON implements the json.Unmarshaler interface for ListSubcriptionGroupPrepaymentItem. // It customizes the JSON unmarshaling process for ListSubcriptionGroupPrepaymentItem objects. func (l *ListSubcriptionGroupPrepaymentItem) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - SubscriptionGroupUid *string `json:"subscription_group_uid,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - RemainingAmountInCents *int64 `json:"remaining_amount_in_cents,omitempty"` - Details *string `json:"details,omitempty"` - External *bool `json:"external,omitempty"` - Memo *string `json:"memo,omitempty"` - PaymentType *PrepaymentMethod `json:"payment_type,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.Id = temp.Id - l.SubscriptionGroupUid = temp.SubscriptionGroupUid - l.AmountInCents = temp.AmountInCents - l.RemainingAmountInCents = temp.RemainingAmountInCents - l.Details = temp.Details - l.External = temp.External - l.Memo = temp.Memo - l.PaymentType = temp.PaymentType - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - l.CreatedAt = &CreatedAtVal - } - return nil + var temp listSubcriptionGroupPrepaymentItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.Id = temp.Id + l.SubscriptionGroupUid = temp.SubscriptionGroupUid + l.AmountInCents = temp.AmountInCents + l.RemainingAmountInCents = temp.RemainingAmountInCents + l.Details = temp.Details + l.External = temp.External + l.Memo = temp.Memo + l.PaymentType = temp.PaymentType + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + l.CreatedAt = &CreatedAtVal + } + return nil +} + +// TODO +type listSubcriptionGroupPrepaymentItem struct { + Id *int `json:"id,omitempty"` + SubscriptionGroupUid *string `json:"subscription_group_uid,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + RemainingAmountInCents *int64 `json:"remaining_amount_in_cents,omitempty"` + Details *string `json:"details,omitempty"` + External *bool `json:"external,omitempty"` + Memo *string `json:"memo,omitempty"` + PaymentType *PrepaymentMethod `json:"payment_type,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` } diff --git a/models/list_subscription_components_response.go b/models/list_subscription_components_response.go index b5bf066a..84e2681f 100644 --- a/models/list_subscription_components_response.go +++ b/models/list_subscription_components_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ListSubscriptionComponentsResponse represents a ListSubscriptionComponentsResponse struct. type ListSubscriptionComponentsResponse struct { - SubscriptionsComponents []SubscriptionComponent `json:"subscriptions_components"` + SubscriptionsComponents []SubscriptionComponent `json:"subscriptions_components"` } -// MarshalJSON implements the json.Marshaler interface for ListSubscriptionComponentsResponse. +// MarshalJSON implements the json.Marshaler interface for ListSubscriptionComponentsResponse. // It customizes the JSON marshaling process for ListSubscriptionComponentsResponse objects. func (l *ListSubscriptionComponentsResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListSubscriptionComponentsResponse object to a map representation for JSON marshaling. func (l *ListSubscriptionComponentsResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscriptions_components"] = l.SubscriptionsComponents - return structMap + structMap := make(map[string]any) + structMap["subscriptions_components"] = l.SubscriptionsComponents + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionComponentsResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionComponentsResponse. // It customizes the JSON unmarshaling process for ListSubscriptionComponentsResponse objects. func (l *ListSubscriptionComponentsResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - SubscriptionsComponents []SubscriptionComponent `json:"subscriptions_components"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.SubscriptionsComponents = temp.SubscriptionsComponents - return nil + var temp listSubscriptionComponentsResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + l.SubscriptionsComponents = *temp.SubscriptionsComponents + return nil +} + +// TODO +type listSubscriptionComponentsResponse struct { + SubscriptionsComponents *[]SubscriptionComponent `json:"subscriptions_components"` +} + +func (l *listSubscriptionComponentsResponse) validate() error { + var errs []string + if l.SubscriptionsComponents == nil { + errs = append(errs, "required field `subscriptions_components` is missing for type `List Subscription Components Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/list_subscription_group_prepayment.go b/models/list_subscription_group_prepayment.go index 6aafc41c..2a35097d 100644 --- a/models/list_subscription_group_prepayment.go +++ b/models/list_subscription_group_prepayment.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ListSubscriptionGroupPrepayment represents a ListSubscriptionGroupPrepayment struct. type ListSubscriptionGroupPrepayment struct { - Prepayment ListSubcriptionGroupPrepaymentItem `json:"prepayment"` + Prepayment ListSubcriptionGroupPrepaymentItem `json:"prepayment"` } -// MarshalJSON implements the json.Marshaler interface for ListSubscriptionGroupPrepayment. +// MarshalJSON implements the json.Marshaler interface for ListSubscriptionGroupPrepayment. // It customizes the JSON marshaling process for ListSubscriptionGroupPrepayment objects. func (l *ListSubscriptionGroupPrepayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListSubscriptionGroupPrepayment object to a map representation for JSON marshaling. func (l *ListSubscriptionGroupPrepayment) toMap() map[string]any { - structMap := make(map[string]any) - structMap["prepayment"] = l.Prepayment.toMap() - return structMap + structMap := make(map[string]any) + structMap["prepayment"] = l.Prepayment.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionGroupPrepayment. +// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionGroupPrepayment. // It customizes the JSON unmarshaling process for ListSubscriptionGroupPrepayment objects. func (l *ListSubscriptionGroupPrepayment) UnmarshalJSON(input []byte) error { - temp := &struct { - Prepayment ListSubcriptionGroupPrepaymentItem `json:"prepayment"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.Prepayment = temp.Prepayment - return nil + var temp listSubscriptionGroupPrepayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + l.Prepayment = *temp.Prepayment + return nil +} + +// TODO +type listSubscriptionGroupPrepayment struct { + Prepayment *ListSubcriptionGroupPrepaymentItem `json:"prepayment"` +} + +func (l *listSubscriptionGroupPrepayment) validate() error { + var errs []string + if l.Prepayment == nil { + errs = append(errs, "required field `prepayment` is missing for type `List Subscription Group Prepayment`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/list_subscription_group_prepayment_response.go b/models/list_subscription_group_prepayment_response.go index 296a17a7..ca52b57a 100644 --- a/models/list_subscription_group_prepayment_response.go +++ b/models/list_subscription_group_prepayment_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ListSubscriptionGroupPrepaymentResponse represents a ListSubscriptionGroupPrepaymentResponse struct. type ListSubscriptionGroupPrepaymentResponse struct { - Prepayments []ListSubscriptionGroupPrepayment `json:"prepayments"` + Prepayments []ListSubscriptionGroupPrepayment `json:"prepayments"` } -// MarshalJSON implements the json.Marshaler interface for ListSubscriptionGroupPrepaymentResponse. +// MarshalJSON implements the json.Marshaler interface for ListSubscriptionGroupPrepaymentResponse. // It customizes the JSON marshaling process for ListSubscriptionGroupPrepaymentResponse objects. func (l *ListSubscriptionGroupPrepaymentResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListSubscriptionGroupPrepaymentResponse object to a map representation for JSON marshaling. func (l *ListSubscriptionGroupPrepaymentResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["prepayments"] = l.Prepayments - return structMap + structMap := make(map[string]any) + structMap["prepayments"] = l.Prepayments + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionGroupPrepaymentResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionGroupPrepaymentResponse. // It customizes the JSON unmarshaling process for ListSubscriptionGroupPrepaymentResponse objects. func (l *ListSubscriptionGroupPrepaymentResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Prepayments []ListSubscriptionGroupPrepayment `json:"prepayments"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.Prepayments = temp.Prepayments - return nil + var temp listSubscriptionGroupPrepaymentResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + l.Prepayments = *temp.Prepayments + return nil +} + +// TODO +type listSubscriptionGroupPrepaymentResponse struct { + Prepayments *[]ListSubscriptionGroupPrepayment `json:"prepayments"` +} + +func (l *listSubscriptionGroupPrepaymentResponse) validate() error { + var errs []string + if l.Prepayments == nil { + errs = append(errs, "required field `prepayments` is missing for type `List Subscription Group Prepayment Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/list_subscription_groups_item.go b/models/list_subscription_groups_item.go index 930ea659..39e68ca6 100644 --- a/models/list_subscription_groups_item.go +++ b/models/list_subscription_groups_item.go @@ -1,104 +1,112 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // ListSubscriptionGroupsItem represents a ListSubscriptionGroupsItem struct. type ListSubscriptionGroupsItem struct { - Uid *string `json:"uid,omitempty"` - Scheme *int `json:"scheme,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - SubscriptionIds []int `json:"subscription_ids,omitempty"` - PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` - NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` - State *string `json:"state,omitempty"` - CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` - AccountBalances *SubscriptionGroupBalances `json:"account_balances,omitempty"` + Uid *string `json:"uid,omitempty"` + Scheme *int `json:"scheme,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + SubscriptionIds []int `json:"subscription_ids,omitempty"` + PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` + NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` + State *string `json:"state,omitempty"` + CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` + AccountBalances *SubscriptionGroupBalances `json:"account_balances,omitempty"` + GroupType *GroupType `json:"group_type,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListSubscriptionGroupsItem. +// MarshalJSON implements the json.Marshaler interface for ListSubscriptionGroupsItem. // It customizes the JSON marshaling process for ListSubscriptionGroupsItem objects. func (l *ListSubscriptionGroupsItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListSubscriptionGroupsItem object to a map representation for JSON marshaling. func (l *ListSubscriptionGroupsItem) toMap() map[string]any { - structMap := make(map[string]any) - if l.Uid != nil { - structMap["uid"] = l.Uid - } - if l.Scheme != nil { - structMap["scheme"] = l.Scheme - } - if l.CustomerId != nil { - structMap["customer_id"] = l.CustomerId - } - if l.PaymentProfileId != nil { - structMap["payment_profile_id"] = l.PaymentProfileId - } - if l.SubscriptionIds != nil { - structMap["subscription_ids"] = l.SubscriptionIds - } - if l.PrimarySubscriptionId != nil { - structMap["primary_subscription_id"] = l.PrimarySubscriptionId - } - if l.NextAssessmentAt != nil { - structMap["next_assessment_at"] = l.NextAssessmentAt.Format(time.RFC3339) - } - if l.State != nil { - structMap["state"] = l.State - } - if l.CancelAtEndOfPeriod != nil { - structMap["cancel_at_end_of_period"] = l.CancelAtEndOfPeriod - } - if l.AccountBalances != nil { - structMap["account_balances"] = l.AccountBalances.toMap() - } - return structMap + structMap := make(map[string]any) + if l.Uid != nil { + structMap["uid"] = l.Uid + } + if l.Scheme != nil { + structMap["scheme"] = l.Scheme + } + if l.CustomerId != nil { + structMap["customer_id"] = l.CustomerId + } + if l.PaymentProfileId != nil { + structMap["payment_profile_id"] = l.PaymentProfileId + } + if l.SubscriptionIds != nil { + structMap["subscription_ids"] = l.SubscriptionIds + } + if l.PrimarySubscriptionId != nil { + structMap["primary_subscription_id"] = l.PrimarySubscriptionId + } + if l.NextAssessmentAt != nil { + structMap["next_assessment_at"] = l.NextAssessmentAt.Format(time.RFC3339) + } + if l.State != nil { + structMap["state"] = l.State + } + if l.CancelAtEndOfPeriod != nil { + structMap["cancel_at_end_of_period"] = l.CancelAtEndOfPeriod + } + if l.AccountBalances != nil { + structMap["account_balances"] = l.AccountBalances.toMap() + } + if l.GroupType != nil { + structMap["group_type"] = l.GroupType + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionGroupsItem. +// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionGroupsItem. // It customizes the JSON unmarshaling process for ListSubscriptionGroupsItem objects. func (l *ListSubscriptionGroupsItem) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Scheme *int `json:"scheme,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - SubscriptionIds []int `json:"subscription_ids,omitempty"` - PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` - NextAssessmentAt *string `json:"next_assessment_at,omitempty"` - State *string `json:"state,omitempty"` - CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` - AccountBalances *SubscriptionGroupBalances `json:"account_balances,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.Uid = temp.Uid - l.Scheme = temp.Scheme - l.CustomerId = temp.CustomerId - l.PaymentProfileId = temp.PaymentProfileId - l.SubscriptionIds = temp.SubscriptionIds - l.PrimarySubscriptionId = temp.PrimarySubscriptionId - if temp.NextAssessmentAt != nil { - NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) - if err != nil { - log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) - } - l.NextAssessmentAt = &NextAssessmentAtVal - } - l.State = temp.State - l.CancelAtEndOfPeriod = temp.CancelAtEndOfPeriod - l.AccountBalances = temp.AccountBalances - return nil + var temp listSubscriptionGroupsItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.Uid = temp.Uid + l.Scheme = temp.Scheme + l.CustomerId = temp.CustomerId + l.PaymentProfileId = temp.PaymentProfileId + l.SubscriptionIds = temp.SubscriptionIds + l.PrimarySubscriptionId = temp.PrimarySubscriptionId + if temp.NextAssessmentAt != nil { + NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) + if err != nil { + log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) + } + l.NextAssessmentAt = &NextAssessmentAtVal + } + l.State = temp.State + l.CancelAtEndOfPeriod = temp.CancelAtEndOfPeriod + l.AccountBalances = temp.AccountBalances + l.GroupType = temp.GroupType + return nil +} + +// TODO +type listSubscriptionGroupsItem struct { + Uid *string `json:"uid,omitempty"` + Scheme *int `json:"scheme,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + SubscriptionIds []int `json:"subscription_ids,omitempty"` + PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` + NextAssessmentAt *string `json:"next_assessment_at,omitempty"` + State *string `json:"state,omitempty"` + CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` + AccountBalances *SubscriptionGroupBalances `json:"account_balances,omitempty"` + GroupType *GroupType `json:"group_type,omitempty"` } diff --git a/models/list_subscription_groups_meta.go b/models/list_subscription_groups_meta.go index fe349327..8b4e7689 100644 --- a/models/list_subscription_groups_meta.go +++ b/models/list_subscription_groups_meta.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListSubscriptionGroupsMeta represents a ListSubscriptionGroupsMeta struct. type ListSubscriptionGroupsMeta struct { - CurrentPage *int `json:"current_page,omitempty"` - TotalCount *int `json:"total_count,omitempty"` + CurrentPage *int `json:"current_page,omitempty"` + TotalCount *int `json:"total_count,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListSubscriptionGroupsMeta. +// MarshalJSON implements the json.Marshaler interface for ListSubscriptionGroupsMeta. // It customizes the JSON marshaling process for ListSubscriptionGroupsMeta objects. func (l *ListSubscriptionGroupsMeta) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListSubscriptionGroupsMeta object to a map representation for JSON marshaling. func (l *ListSubscriptionGroupsMeta) toMap() map[string]any { - structMap := make(map[string]any) - if l.CurrentPage != nil { - structMap["current_page"] = l.CurrentPage - } - if l.TotalCount != nil { - structMap["total_count"] = l.TotalCount - } - return structMap + structMap := make(map[string]any) + if l.CurrentPage != nil { + structMap["current_page"] = l.CurrentPage + } + if l.TotalCount != nil { + structMap["total_count"] = l.TotalCount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionGroupsMeta. +// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionGroupsMeta. // It customizes the JSON unmarshaling process for ListSubscriptionGroupsMeta objects. func (l *ListSubscriptionGroupsMeta) UnmarshalJSON(input []byte) error { - temp := &struct { - CurrentPage *int `json:"current_page,omitempty"` - TotalCount *int `json:"total_count,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.CurrentPage = temp.CurrentPage - l.TotalCount = temp.TotalCount - return nil + var temp listSubscriptionGroupsMeta + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.CurrentPage = temp.CurrentPage + l.TotalCount = temp.TotalCount + return nil +} + +// TODO +type listSubscriptionGroupsMeta struct { + CurrentPage *int `json:"current_page,omitempty"` + TotalCount *int `json:"total_count,omitempty"` } diff --git a/models/list_subscription_groups_response.go b/models/list_subscription_groups_response.go index 78b00fbd..ea2c05cd 100644 --- a/models/list_subscription_groups_response.go +++ b/models/list_subscription_groups_response.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // ListSubscriptionGroupsResponse represents a ListSubscriptionGroupsResponse struct. type ListSubscriptionGroupsResponse struct { - SubscriptionGroups []ListSubscriptionGroupsItem `json:"subscription_groups,omitempty"` - Meta *ListSubscriptionGroupsMeta `json:"meta,omitempty"` + SubscriptionGroups []ListSubscriptionGroupsItem `json:"subscription_groups,omitempty"` + Meta *ListSubscriptionGroupsMeta `json:"meta,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ListSubscriptionGroupsResponse. +// MarshalJSON implements the json.Marshaler interface for ListSubscriptionGroupsResponse. // It customizes the JSON marshaling process for ListSubscriptionGroupsResponse objects. func (l *ListSubscriptionGroupsResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(l.toMap()) + []byte, + error) { + return json.Marshal(l.toMap()) } // toMap converts the ListSubscriptionGroupsResponse object to a map representation for JSON marshaling. func (l *ListSubscriptionGroupsResponse) toMap() map[string]any { - structMap := make(map[string]any) - if l.SubscriptionGroups != nil { - structMap["subscription_groups"] = l.SubscriptionGroups - } - if l.Meta != nil { - structMap["meta"] = l.Meta.toMap() - } - return structMap + structMap := make(map[string]any) + if l.SubscriptionGroups != nil { + structMap["subscription_groups"] = l.SubscriptionGroups + } + if l.Meta != nil { + structMap["meta"] = l.Meta.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionGroupsResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ListSubscriptionGroupsResponse. // It customizes the JSON unmarshaling process for ListSubscriptionGroupsResponse objects. func (l *ListSubscriptionGroupsResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - SubscriptionGroups []ListSubscriptionGroupsItem `json:"subscription_groups,omitempty"` - Meta *ListSubscriptionGroupsMeta `json:"meta,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - l.SubscriptionGroups = temp.SubscriptionGroups - l.Meta = temp.Meta - return nil + var temp listSubscriptionGroupsResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + l.SubscriptionGroups = temp.SubscriptionGroups + l.Meta = temp.Meta + return nil +} + +// TODO +type listSubscriptionGroupsResponse struct { + SubscriptionGroups []ListSubscriptionGroupsItem `json:"subscription_groups,omitempty"` + Meta *ListSubscriptionGroupsMeta `json:"meta,omitempty"` } diff --git a/models/list_usages_input_component_id.go b/models/list_usages_input_component_id.go new file mode 100644 index 00000000..314ec788 --- /dev/null +++ b/models/list_usages_input_component_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ListUsagesInputComponentId represents a ListUsagesInputComponentId struct. +// This is a container for one-of cases. +type ListUsagesInputComponentId struct { + value any + isNumber bool + isString bool +} + +// String converts the ListUsagesInputComponentId object to a string representation. +func (l ListUsagesInputComponentId) String() string { + if bytes, err := json.Marshal(l.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ListUsagesInputComponentId. +// It customizes the JSON marshaling process for ListUsagesInputComponentId objects. +func (l *ListUsagesInputComponentId) MarshalJSON() ( + []byte, + error) { + if l.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ListUsagesInputComponentIdContainer.From*` functions to initialize the ListUsagesInputComponentId object.") + } + return json.Marshal(l.toMap()) +} + +// toMap converts the ListUsagesInputComponentId object to a map representation for JSON marshaling. +func (l *ListUsagesInputComponentId) toMap() any { + switch obj := l.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ListUsagesInputComponentId. +// It customizes the JSON unmarshaling process for ListUsagesInputComponentId objects. +func (l *ListUsagesInputComponentId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &l.isNumber), + NewTypeHolder(new(string), false, &l.isString), + ) + + l.value = result + return err +} + +func (l *ListUsagesInputComponentId) AsNumber() ( + *int, + bool) { + if !l.isNumber { + return nil, false + } + return l.value.(*int), true +} + +func (l *ListUsagesInputComponentId) AsString() ( + *string, + bool) { + if !l.isString { + return nil, false + } + return l.value.(*string), true +} + +// internalListUsagesInputComponentId represents a listUsagesInputComponentId struct. +// This is a container for one-of cases. +type internalListUsagesInputComponentId struct{} + +var ListUsagesInputComponentIdContainer internalListUsagesInputComponentId + +func (l *internalListUsagesInputComponentId) FromNumber(val int) ListUsagesInputComponentId { + return ListUsagesInputComponentId{value: &val} +} + +func (l *internalListUsagesInputComponentId) FromString(val string) ListUsagesInputComponentId { + return ListUsagesInputComponentId{value: &val} +} diff --git a/models/m_errors.go b/models/m_errors.go index 87197826..2f63a9f7 100644 --- a/models/m_errors.go +++ b/models/m_errors.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // Errors represents a Errors struct. type Errors struct { - PerPage []string `json:"per_page,omitempty"` - PricePoint []string `json:"price_point,omitempty"` + PerPage []string `json:"per_page,omitempty"` + PricePoint []string `json:"price_point,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Errors. +// MarshalJSON implements the json.Marshaler interface for Errors. // It customizes the JSON marshaling process for Errors objects. func (e *Errors) MarshalJSON() ( - []byte, - error) { - return json.Marshal(e.toMap()) + []byte, + error) { + return json.Marshal(e.toMap()) } // toMap converts the Errors object to a map representation for JSON marshaling. func (e *Errors) toMap() map[string]any { - structMap := make(map[string]any) - if e.PerPage != nil { - structMap["per_page"] = e.PerPage - } - if e.PricePoint != nil { - structMap["price_point"] = e.PricePoint - } - return structMap + structMap := make(map[string]any) + if e.PerPage != nil { + structMap["per_page"] = e.PerPage + } + if e.PricePoint != nil { + structMap["price_point"] = e.PricePoint + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Errors. +// UnmarshalJSON implements the json.Unmarshaler interface for Errors. // It customizes the JSON unmarshaling process for Errors objects. func (e *Errors) UnmarshalJSON(input []byte) error { - temp := &struct { - PerPage []string `json:"per_page,omitempty"` - PricePoint []string `json:"price_point,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - e.PerPage = temp.PerPage - e.PricePoint = temp.PricePoint - return nil + var temp mErrors + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + e.PerPage = temp.PerPage + e.PricePoint = temp.PricePoint + return nil +} + +// TODO +type mErrors struct { + PerPage []string `json:"per_page,omitempty"` + PricePoint []string `json:"price_point,omitempty"` } diff --git a/models/metadata.go b/models/metadata.go index 599b879e..96b8c212 100644 --- a/models/metadata.go +++ b/models/metadata.go @@ -1,86 +1,108 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Metadata represents a Metadata struct. type Metadata struct { - Id Optional[int] `json:"id"` - Value Optional[string] `json:"value"` - ResourceId Optional[int] `json:"resource_id"` - Name *string `json:"name,omitempty"` - DeletedAt Optional[time.Time] `json:"deleted_at"` - MetafieldId Optional[int] `json:"metafield_id"` + Id Optional[int] `json:"id"` + Value Optional[string] `json:"value"` + ResourceId Optional[int] `json:"resource_id"` + Name *string `json:"name,omitempty"` + DeletedAt Optional[time.Time] `json:"deleted_at"` + MetafieldId Optional[int] `json:"metafield_id"` } -// MarshalJSON implements the json.Marshaler interface for Metadata. +// MarshalJSON implements the json.Marshaler interface for Metadata. // It customizes the JSON marshaling process for Metadata objects. func (m *Metadata) MarshalJSON() ( - []byte, - error) { - return json.Marshal(m.toMap()) + []byte, + error) { + return json.Marshal(m.toMap()) } // toMap converts the Metadata object to a map representation for JSON marshaling. func (m *Metadata) toMap() map[string]any { - structMap := make(map[string]any) - if m.Id.IsValueSet() { - structMap["id"] = m.Id.Value() - } - if m.Value.IsValueSet() { - structMap["value"] = m.Value.Value() - } - if m.ResourceId.IsValueSet() { - structMap["resource_id"] = m.ResourceId.Value() - } - if m.Name != nil { - structMap["name"] = m.Name - } - if m.DeletedAt.IsValueSet() { - var DeletedAtVal *string = nil - if m.DeletedAt.Value() != nil { - val := m.DeletedAt.Value().Format(time.RFC3339) - DeletedAtVal = &val - } - structMap["deleted_at"] = DeletedAtVal - } - if m.MetafieldId.IsValueSet() { - structMap["metafield_id"] = m.MetafieldId.Value() - } - return structMap + structMap := make(map[string]any) + if m.Id.IsValueSet() { + if m.Id.Value() != nil { + structMap["id"] = m.Id.Value() + } else { + structMap["id"] = nil + } + } + if m.Value.IsValueSet() { + if m.Value.Value() != nil { + structMap["value"] = m.Value.Value() + } else { + structMap["value"] = nil + } + } + if m.ResourceId.IsValueSet() { + if m.ResourceId.Value() != nil { + structMap["resource_id"] = m.ResourceId.Value() + } else { + structMap["resource_id"] = nil + } + } + if m.Name != nil { + structMap["name"] = m.Name + } + if m.DeletedAt.IsValueSet() { + var DeletedAtVal *string = nil + if m.DeletedAt.Value() != nil { + val := m.DeletedAt.Value().Format(time.RFC3339) + DeletedAtVal = &val + } + if m.DeletedAt.Value() != nil { + structMap["deleted_at"] = DeletedAtVal + } else { + structMap["deleted_at"] = nil + } + } + if m.MetafieldId.IsValueSet() { + if m.MetafieldId.Value() != nil { + structMap["metafield_id"] = m.MetafieldId.Value() + } else { + structMap["metafield_id"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Metadata. +// UnmarshalJSON implements the json.Unmarshaler interface for Metadata. // It customizes the JSON unmarshaling process for Metadata objects. func (m *Metadata) UnmarshalJSON(input []byte) error { - temp := &struct { - Id Optional[int] `json:"id"` - Value Optional[string] `json:"value"` - ResourceId Optional[int] `json:"resource_id"` - Name *string `json:"name,omitempty"` - DeletedAt Optional[string] `json:"deleted_at"` - MetafieldId Optional[int] `json:"metafield_id"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - m.Id = temp.Id - m.Value = temp.Value - m.ResourceId = temp.ResourceId - m.Name = temp.Name - m.DeletedAt.ShouldSetValue(temp.DeletedAt.IsValueSet()) - if temp.DeletedAt.Value() != nil { - DeletedAtVal, err := time.Parse(time.RFC3339, (*temp.DeletedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse deleted_at as % s format.", time.RFC3339) - } - m.DeletedAt.SetValue(&DeletedAtVal) - } - m.MetafieldId = temp.MetafieldId - return nil + var temp metadata + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + m.Id = temp.Id + m.Value = temp.Value + m.ResourceId = temp.ResourceId + m.Name = temp.Name + m.DeletedAt.ShouldSetValue(temp.DeletedAt.IsValueSet()) + if temp.DeletedAt.Value() != nil { + DeletedAtVal, err := time.Parse(time.RFC3339, (*temp.DeletedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse deleted_at as % s format.", time.RFC3339) + } + m.DeletedAt.SetValue(&DeletedAtVal) + } + m.MetafieldId = temp.MetafieldId + return nil +} + +// TODO +type metadata struct { + Id Optional[int] `json:"id"` + Value Optional[string] `json:"value"` + ResourceId Optional[int] `json:"resource_id"` + Name *string `json:"name,omitempty"` + DeletedAt Optional[string] `json:"deleted_at"` + MetafieldId Optional[int] `json:"metafield_id"` } diff --git a/models/metafield.go b/models/metafield.go index c729a388..1cacb32e 100644 --- a/models/metafield.go +++ b/models/metafield.go @@ -1,75 +1,81 @@ package models import ( - "encoding/json" + "encoding/json" ) // Metafield represents a Metafield struct. type Metafield struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - // Warning: When updating a metafield's scope attribute, all scope attributes must be passed. Partially complete scope attributes will override the existing settings. - Scope *MetafieldScope `json:"scope,omitempty"` - // the amount of subscriptions this metafield has been applied to in Chargify - DataCount *int `json:"data_count,omitempty"` - // Indicates how data should be added to the metafield. For example, a text type is just a string, so a given metafield of this type can have any value attached. On the other hand, dropdown and radio have a set of allowed values that can be input, and appear differently on a Public Signup Page. Defaults to 'text' - InputType *MetafieldInput `json:"input_type,omitempty"` - Enum Optional[interface{}] `json:"enum"` + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + // Warning: When updating a metafield's scope attribute, all scope attributes must be passed. Partially complete scope attributes will override the existing settings. + Scope *MetafieldScope `json:"scope,omitempty"` + // the amount of subscriptions this metafield has been applied to in Chargify + DataCount *int `json:"data_count,omitempty"` + // Indicates how data should be added to the metafield. For example, a text type is just a string, so a given metafield of this type can have any value attached. On the other hand, dropdown and radio have a set of allowed values that can be input, and appear differently on a Public Signup Page. Defaults to 'text' + InputType *MetafieldInput `json:"input_type,omitempty"` + Enum Optional[MetafieldEnum] `json:"enum"` } -// MarshalJSON implements the json.Marshaler interface for Metafield. +// MarshalJSON implements the json.Marshaler interface for Metafield. // It customizes the JSON marshaling process for Metafield objects. func (m *Metafield) MarshalJSON() ( - []byte, - error) { - return json.Marshal(m.toMap()) + []byte, + error) { + return json.Marshal(m.toMap()) } // toMap converts the Metafield object to a map representation for JSON marshaling. func (m *Metafield) toMap() map[string]any { - structMap := make(map[string]any) - if m.Id != nil { - structMap["id"] = m.Id - } - if m.Name != nil { - structMap["name"] = m.Name - } - if m.Scope != nil { - structMap["scope"] = m.Scope.toMap() - } - if m.DataCount != nil { - structMap["data_count"] = m.DataCount - } - if m.InputType != nil { - structMap["input_type"] = m.InputType - } - if m.Enum.IsValueSet() { - structMap["enum"] = m.Enum.Value() - } - return structMap + structMap := make(map[string]any) + if m.Id != nil { + structMap["id"] = m.Id + } + if m.Name != nil { + structMap["name"] = m.Name + } + if m.Scope != nil { + structMap["scope"] = m.Scope.toMap() + } + if m.DataCount != nil { + structMap["data_count"] = m.DataCount + } + if m.InputType != nil { + structMap["input_type"] = m.InputType + } + if m.Enum.IsValueSet() { + if m.Enum.Value() != nil { + structMap["enum"] = m.Enum.Value().toMap() + } else { + structMap["enum"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Metafield. +// UnmarshalJSON implements the json.Unmarshaler interface for Metafield. // It customizes the JSON unmarshaling process for Metafield objects. func (m *Metafield) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Scope *MetafieldScope `json:"scope,omitempty"` - DataCount *int `json:"data_count,omitempty"` - InputType *MetafieldInput `json:"input_type,omitempty"` - Enum Optional[interface{}] `json:"enum"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - m.Id = temp.Id - m.Name = temp.Name - m.Scope = temp.Scope - m.DataCount = temp.DataCount - m.InputType = temp.InputType - m.Enum = temp.Enum - return nil + var temp metafield + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + m.Id = temp.Id + m.Name = temp.Name + m.Scope = temp.Scope + m.DataCount = temp.DataCount + m.InputType = temp.InputType + m.Enum = temp.Enum + return nil +} + +// TODO +type metafield struct { + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Scope *MetafieldScope `json:"scope,omitempty"` + DataCount *int `json:"data_count,omitempty"` + InputType *MetafieldInput `json:"input_type,omitempty"` + Enum Optional[MetafieldEnum] `json:"enum"` } diff --git a/models/metafield_enum.go b/models/metafield_enum.go new file mode 100644 index 00000000..78bd96fd --- /dev/null +++ b/models/metafield_enum.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// MetafieldEnum represents a MetafieldEnum struct. +// This is a container for one-of cases. +type MetafieldEnum struct { + value any + isString bool + isArrayOfString bool +} + +// String converts the MetafieldEnum object to a string representation. +func (m MetafieldEnum) String() string { + if bytes, err := json.Marshal(m.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for MetafieldEnum. +// It customizes the JSON marshaling process for MetafieldEnum objects. +func (m *MetafieldEnum) MarshalJSON() ( + []byte, + error) { + if m.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.MetafieldEnumContainer.From*` functions to initialize the MetafieldEnum object.") + } + return json.Marshal(m.toMap()) +} + +// toMap converts the MetafieldEnum object to a map representation for JSON marshaling. +func (m *MetafieldEnum) toMap() any { + switch obj := m.value.(type) { + case *string: + return *obj + case *[]string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for MetafieldEnum. +// It customizes the JSON unmarshaling process for MetafieldEnum objects. +func (m *MetafieldEnum) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &m.isString), + NewTypeHolder(new([]string), false, &m.isArrayOfString), + ) + + m.value = result + return err +} + +func (m *MetafieldEnum) AsString() ( + *string, + bool) { + if !m.isString { + return nil, false + } + return m.value.(*string), true +} + +func (m *MetafieldEnum) AsArrayOfString() ( + *[]string, + bool) { + if !m.isArrayOfString { + return nil, false + } + return m.value.(*[]string), true +} + +// internalMetafieldEnum represents a metafieldEnum struct. +// This is a container for one-of cases. +type internalMetafieldEnum struct{} + +var MetafieldEnumContainer internalMetafieldEnum + +func (m *internalMetafieldEnum) FromString(val string) MetafieldEnum { + return MetafieldEnum{value: &val} +} + +func (m *internalMetafieldEnum) FromArrayOfString(val []string) MetafieldEnum { + return MetafieldEnum{value: &val} +} diff --git a/models/metafield_scope.go b/models/metafield_scope.go index 1fc20ff1..4eb55f0a 100644 --- a/models/metafield_scope.go +++ b/models/metafield_scope.go @@ -1,85 +1,87 @@ package models import ( - "encoding/json" + "encoding/json" ) -// MetafieldScope represents a MetafieldScope struct. +// MetafieldScope represents a MetafieldScope struct. // Warning: When updating a metafield's scope attribute, all scope attributes must be passed. Partially complete scope attributes will override the existing settings. type MetafieldScope struct { - // Include (1) or exclude (0) metafields from the csv export. - Csv *IncludeOption `json:"csv,omitempty"` - // Include (1) or exclude (0) metafields from invoices. - Invoices *IncludeOption `json:"invoices,omitempty"` - // Include (1) or exclude (0) metafields from statements. - Statements *IncludeOption `json:"statements,omitempty"` - // Include (1) or exclude (0) metafields from the portal. - Portal *IncludeOption `json:"portal,omitempty"` - // Include (1) or exclude (0) metafields from being viewable by your ecosystem. - PublicShow *IncludeOption `json:"public_show,omitempty"` - // Include (1) or exclude (0) metafields from being edited by your ecosystem. - PublicEdit *IncludeOption `json:"public_edit,omitempty"` - Hosted []string `json:"hosted,omitempty"` + // Include (1) or exclude (0) metafields from the csv export. + Csv *IncludeOption `json:"csv,omitempty"` + // Include (1) or exclude (0) metafields from invoices. + Invoices *IncludeOption `json:"invoices,omitempty"` + // Include (1) or exclude (0) metafields from statements. + Statements *IncludeOption `json:"statements,omitempty"` + // Include (1) or exclude (0) metafields from the portal. + Portal *IncludeOption `json:"portal,omitempty"` + // Include (1) or exclude (0) metafields from being viewable by your ecosystem. + PublicShow *IncludeOption `json:"public_show,omitempty"` + // Include (1) or exclude (0) metafields from being edited by your ecosystem. + PublicEdit *IncludeOption `json:"public_edit,omitempty"` + Hosted []string `json:"hosted,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for MetafieldScope. +// MarshalJSON implements the json.Marshaler interface for MetafieldScope. // It customizes the JSON marshaling process for MetafieldScope objects. func (m *MetafieldScope) MarshalJSON() ( - []byte, - error) { - return json.Marshal(m.toMap()) + []byte, + error) { + return json.Marshal(m.toMap()) } // toMap converts the MetafieldScope object to a map representation for JSON marshaling. func (m *MetafieldScope) toMap() map[string]any { - structMap := make(map[string]any) - if m.Csv != nil { - structMap["csv"] = m.Csv - } - if m.Invoices != nil { - structMap["invoices"] = m.Invoices - } - if m.Statements != nil { - structMap["statements"] = m.Statements - } - if m.Portal != nil { - structMap["portal"] = m.Portal - } - if m.PublicShow != nil { - structMap["public_show"] = m.PublicShow - } - if m.PublicEdit != nil { - structMap["public_edit"] = m.PublicEdit - } - if m.Hosted != nil { - structMap["hosted"] = m.Hosted - } - return structMap + structMap := make(map[string]any) + if m.Csv != nil { + structMap["csv"] = m.Csv + } + if m.Invoices != nil { + structMap["invoices"] = m.Invoices + } + if m.Statements != nil { + structMap["statements"] = m.Statements + } + if m.Portal != nil { + structMap["portal"] = m.Portal + } + if m.PublicShow != nil { + structMap["public_show"] = m.PublicShow + } + if m.PublicEdit != nil { + structMap["public_edit"] = m.PublicEdit + } + if m.Hosted != nil { + structMap["hosted"] = m.Hosted + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for MetafieldScope. +// UnmarshalJSON implements the json.Unmarshaler interface for MetafieldScope. // It customizes the JSON unmarshaling process for MetafieldScope objects. func (m *MetafieldScope) UnmarshalJSON(input []byte) error { - temp := &struct { - Csv *IncludeOption `json:"csv,omitempty"` - Invoices *IncludeOption `json:"invoices,omitempty"` - Statements *IncludeOption `json:"statements,omitempty"` - Portal *IncludeOption `json:"portal,omitempty"` - PublicShow *IncludeOption `json:"public_show,omitempty"` - PublicEdit *IncludeOption `json:"public_edit,omitempty"` - Hosted []string `json:"hosted,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - m.Csv = temp.Csv - m.Invoices = temp.Invoices - m.Statements = temp.Statements - m.Portal = temp.Portal - m.PublicShow = temp.PublicShow - m.PublicEdit = temp.PublicEdit - m.Hosted = temp.Hosted - return nil + var temp metafieldScope + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + m.Csv = temp.Csv + m.Invoices = temp.Invoices + m.Statements = temp.Statements + m.Portal = temp.Portal + m.PublicShow = temp.PublicShow + m.PublicEdit = temp.PublicEdit + m.Hosted = temp.Hosted + return nil +} + +// TODO +type metafieldScope struct { + Csv *IncludeOption `json:"csv,omitempty"` + Invoices *IncludeOption `json:"invoices,omitempty"` + Statements *IncludeOption `json:"statements,omitempty"` + Portal *IncludeOption `json:"portal,omitempty"` + PublicShow *IncludeOption `json:"public_show,omitempty"` + PublicEdit *IncludeOption `json:"public_edit,omitempty"` + Hosted []string `json:"hosted,omitempty"` } diff --git a/models/metered_component.go b/models/metered_component.go index 074ced69..805a4099 100644 --- a/models/metered_component.go +++ b/models/metered_component.go @@ -1,161 +1,195 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // MeteredComponent represents a MeteredComponent struct. type MeteredComponent struct { - // A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". - Name string `json:"name"` - // The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item - UnitName string `json:"unit_name"` - // A description for the component that will be displayed to the user on the hosted signup page. - Description *string `json:"description,omitempty"` - // A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'. - Handle *string `json:"handle,omitempty"` - // Boolean flag describing whether a component is taxable or not. - Taxable *bool `json:"taxable,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme PricingScheme `json:"pricing_scheme"` - // (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. - Prices []Price `json:"prices,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` - // The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 - UnitPrice *interface{} `json:"unit_price,omitempty"` - // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. - TaxCode *string `json:"tax_code,omitempty"` - // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - // deprecated May 2011 - use unit_price instead - PriceInCents *string `json:"price_in_cents,omitempty"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + // A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". + Name string `json:"name"` + // The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item + UnitName string `json:"unit_name"` + // A description for the component that will be displayed to the user on the hosted signup page. + Description *string `json:"description,omitempty"` + // A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'. + Handle *string `json:"handle,omitempty"` + // Boolean flag describing whether a component is taxable or not. + Taxable *bool `json:"taxable,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme PricingScheme `json:"pricing_scheme"` + // (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. + Prices []Price `json:"prices,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` + // The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 + UnitPrice *MeteredComponentUnitPrice `json:"unit_price,omitempty"` + // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. + TaxCode *string `json:"tax_code,omitempty"` + // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + // deprecated May 2011 - use unit_price instead + PriceInCents *string `json:"price_in_cents,omitempty"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for MeteredComponent. +// MarshalJSON implements the json.Marshaler interface for MeteredComponent. // It customizes the JSON marshaling process for MeteredComponent objects. func (m *MeteredComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(m.toMap()) + []byte, + error) { + return json.Marshal(m.toMap()) } // toMap converts the MeteredComponent object to a map representation for JSON marshaling. func (m *MeteredComponent) toMap() map[string]any { - structMap := make(map[string]any) - structMap["name"] = m.Name - structMap["unit_name"] = m.UnitName - if m.Description != nil { - structMap["description"] = m.Description - } - if m.Handle != nil { - structMap["handle"] = m.Handle - } - if m.Taxable != nil { - structMap["taxable"] = m.Taxable - } - structMap["pricing_scheme"] = m.PricingScheme - if m.Prices != nil { - structMap["prices"] = m.Prices - } - if m.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = m.UpgradeCharge.Value() - } - if m.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = m.DowngradeCredit.Value() - } - if m.PricePoints != nil { - structMap["price_points"] = m.PricePoints - } - if m.UnitPrice != nil { - structMap["unit_price"] = m.UnitPrice - } - if m.TaxCode != nil { - structMap["tax_code"] = m.TaxCode - } - if m.HideDateRangeOnInvoice != nil { - structMap["hide_date_range_on_invoice"] = m.HideDateRangeOnInvoice - } - if m.PriceInCents != nil { - structMap["price_in_cents"] = m.PriceInCents - } - if m.DisplayOnHostedPage != nil { - structMap["display_on_hosted_page"] = m.DisplayOnHostedPage - } - if m.AllowFractionalQuantities != nil { - structMap["allow_fractional_quantities"] = m.AllowFractionalQuantities - } - if m.PublicSignupPageIds != nil { - structMap["public_signup_page_ids"] = m.PublicSignupPageIds - } - if m.Interval != nil { - structMap["interval"] = m.Interval - } - if m.IntervalUnit != nil { - structMap["interval_unit"] = m.IntervalUnit - } - return structMap + structMap := make(map[string]any) + structMap["name"] = m.Name + structMap["unit_name"] = m.UnitName + if m.Description != nil { + structMap["description"] = m.Description + } + if m.Handle != nil { + structMap["handle"] = m.Handle + } + if m.Taxable != nil { + structMap["taxable"] = m.Taxable + } + structMap["pricing_scheme"] = m.PricingScheme + if m.Prices != nil { + structMap["prices"] = m.Prices + } + if m.UpgradeCharge.IsValueSet() { + if m.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = m.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if m.DowngradeCredit.IsValueSet() { + if m.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = m.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if m.PricePoints != nil { + structMap["price_points"] = m.PricePoints + } + if m.UnitPrice != nil { + structMap["unit_price"] = m.UnitPrice.toMap() + } + if m.TaxCode != nil { + structMap["tax_code"] = m.TaxCode + } + if m.HideDateRangeOnInvoice != nil { + structMap["hide_date_range_on_invoice"] = m.HideDateRangeOnInvoice + } + if m.PriceInCents != nil { + structMap["price_in_cents"] = m.PriceInCents + } + if m.DisplayOnHostedPage != nil { + structMap["display_on_hosted_page"] = m.DisplayOnHostedPage + } + if m.AllowFractionalQuantities != nil { + structMap["allow_fractional_quantities"] = m.AllowFractionalQuantities + } + if m.PublicSignupPageIds != nil { + structMap["public_signup_page_ids"] = m.PublicSignupPageIds + } + if m.Interval != nil { + structMap["interval"] = m.Interval + } + if m.IntervalUnit != nil { + structMap["interval_unit"] = m.IntervalUnit + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for MeteredComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for MeteredComponent. // It customizes the JSON unmarshaling process for MeteredComponent objects. func (m *MeteredComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - Name string `json:"name"` - UnitName string `json:"unit_name"` - Description *string `json:"description,omitempty"` - Handle *string `json:"handle,omitempty"` - Taxable *bool `json:"taxable,omitempty"` - PricingScheme PricingScheme `json:"pricing_scheme"` - Prices []Price `json:"prices,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` - UnitPrice *interface{} `json:"unit_price,omitempty"` - TaxCode *string `json:"tax_code,omitempty"` - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - PriceInCents *string `json:"price_in_cents,omitempty"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - m.Name = temp.Name - m.UnitName = temp.UnitName - m.Description = temp.Description - m.Handle = temp.Handle - m.Taxable = temp.Taxable - m.PricingScheme = temp.PricingScheme - m.Prices = temp.Prices - m.UpgradeCharge = temp.UpgradeCharge - m.DowngradeCredit = temp.DowngradeCredit - m.PricePoints = temp.PricePoints - m.UnitPrice = temp.UnitPrice - m.TaxCode = temp.TaxCode - m.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice - m.PriceInCents = temp.PriceInCents - m.DisplayOnHostedPage = temp.DisplayOnHostedPage - m.AllowFractionalQuantities = temp.AllowFractionalQuantities - m.PublicSignupPageIds = temp.PublicSignupPageIds - m.Interval = temp.Interval - m.IntervalUnit = temp.IntervalUnit - return nil + var temp meteredComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + m.Name = *temp.Name + m.UnitName = *temp.UnitName + m.Description = temp.Description + m.Handle = temp.Handle + m.Taxable = temp.Taxable + m.PricingScheme = *temp.PricingScheme + m.Prices = temp.Prices + m.UpgradeCharge = temp.UpgradeCharge + m.DowngradeCredit = temp.DowngradeCredit + m.PricePoints = temp.PricePoints + m.UnitPrice = temp.UnitPrice + m.TaxCode = temp.TaxCode + m.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice + m.PriceInCents = temp.PriceInCents + m.DisplayOnHostedPage = temp.DisplayOnHostedPage + m.AllowFractionalQuantities = temp.AllowFractionalQuantities + m.PublicSignupPageIds = temp.PublicSignupPageIds + m.Interval = temp.Interval + m.IntervalUnit = temp.IntervalUnit + return nil +} + +// TODO +type meteredComponent struct { + Name *string `json:"name"` + UnitName *string `json:"unit_name"` + Description *string `json:"description,omitempty"` + Handle *string `json:"handle,omitempty"` + Taxable *bool `json:"taxable,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme"` + Prices []Price `json:"prices,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` + UnitPrice *MeteredComponentUnitPrice `json:"unit_price,omitempty"` + TaxCode *string `json:"tax_code,omitempty"` + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + PriceInCents *string `json:"price_in_cents,omitempty"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` +} + +func (m *meteredComponent) validate() error { + var errs []string + if m.Name == nil { + errs = append(errs, "required field `name` is missing for type `Metered Component`") + } + if m.UnitName == nil { + errs = append(errs, "required field `unit_name` is missing for type `Metered Component`") + } + if m.PricingScheme == nil { + errs = append(errs, "required field `pricing_scheme` is missing for type `Metered Component`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/metered_component_unit_price.go b/models/metered_component_unit_price.go new file mode 100644 index 00000000..c83d133f --- /dev/null +++ b/models/metered_component_unit_price.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// MeteredComponentUnitPrice represents a MeteredComponentUnitPrice struct. +// This is a container for one-of cases. +type MeteredComponentUnitPrice struct { + value any + isString bool + isPrecision bool +} + +// String converts the MeteredComponentUnitPrice object to a string representation. +func (m MeteredComponentUnitPrice) String() string { + if bytes, err := json.Marshal(m.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for MeteredComponentUnitPrice. +// It customizes the JSON marshaling process for MeteredComponentUnitPrice objects. +func (m *MeteredComponentUnitPrice) MarshalJSON() ( + []byte, + error) { + if m.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.MeteredComponentUnitPriceContainer.From*` functions to initialize the MeteredComponentUnitPrice object.") + } + return json.Marshal(m.toMap()) +} + +// toMap converts the MeteredComponentUnitPrice object to a map representation for JSON marshaling. +func (m *MeteredComponentUnitPrice) toMap() any { + switch obj := m.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for MeteredComponentUnitPrice. +// It customizes the JSON unmarshaling process for MeteredComponentUnitPrice objects. +func (m *MeteredComponentUnitPrice) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &m.isString), + NewTypeHolder(new(float64), false, &m.isPrecision), + ) + + m.value = result + return err +} + +func (m *MeteredComponentUnitPrice) AsString() ( + *string, + bool) { + if !m.isString { + return nil, false + } + return m.value.(*string), true +} + +func (m *MeteredComponentUnitPrice) AsPrecision() ( + *float64, + bool) { + if !m.isPrecision { + return nil, false + } + return m.value.(*float64), true +} + +// internalMeteredComponentUnitPrice represents a meteredComponentUnitPrice struct. +// This is a container for one-of cases. +type internalMeteredComponentUnitPrice struct{} + +var MeteredComponentUnitPriceContainer internalMeteredComponentUnitPrice + +func (m *internalMeteredComponentUnitPrice) FromString(val string) MeteredComponentUnitPrice { + return MeteredComponentUnitPrice{value: &val} +} + +func (m *internalMeteredComponentUnitPrice) FromPrecision(val float64) MeteredComponentUnitPrice { + return MeteredComponentUnitPrice{value: &val} +} diff --git a/models/metered_usage.go b/models/metered_usage.go new file mode 100644 index 00000000..97bf0d51 --- /dev/null +++ b/models/metered_usage.go @@ -0,0 +1,95 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// MeteredUsage represents a MeteredUsage struct. +type MeteredUsage struct { + PreviousUnitBalance string `json:"previous_unit_balance"` + NewUnitBalance int `json:"new_unit_balance"` + UsageQuantity int `json:"usage_quantity"` + ComponentId int `json:"component_id"` + ComponentHandle string `json:"component_handle"` + Memo string `json:"memo"` +} + +// MarshalJSON implements the json.Marshaler interface for MeteredUsage. +// It customizes the JSON marshaling process for MeteredUsage objects. +func (m *MeteredUsage) MarshalJSON() ( + []byte, + error) { + return json.Marshal(m.toMap()) +} + +// toMap converts the MeteredUsage object to a map representation for JSON marshaling. +func (m *MeteredUsage) toMap() map[string]any { + structMap := make(map[string]any) + structMap["previous_unit_balance"] = m.PreviousUnitBalance + structMap["new_unit_balance"] = m.NewUnitBalance + structMap["usage_quantity"] = m.UsageQuantity + structMap["component_id"] = m.ComponentId + structMap["component_handle"] = m.ComponentHandle + structMap["memo"] = m.Memo + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for MeteredUsage. +// It customizes the JSON unmarshaling process for MeteredUsage objects. +func (m *MeteredUsage) UnmarshalJSON(input []byte) error { + var temp meteredUsage + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + m.PreviousUnitBalance = *temp.PreviousUnitBalance + m.NewUnitBalance = *temp.NewUnitBalance + m.UsageQuantity = *temp.UsageQuantity + m.ComponentId = *temp.ComponentId + m.ComponentHandle = *temp.ComponentHandle + m.Memo = *temp.Memo + return nil +} + +// TODO +type meteredUsage struct { + PreviousUnitBalance *string `json:"previous_unit_balance"` + NewUnitBalance *int `json:"new_unit_balance"` + UsageQuantity *int `json:"usage_quantity"` + ComponentId *int `json:"component_id"` + ComponentHandle *string `json:"component_handle"` + Memo *string `json:"memo"` +} + +func (m *meteredUsage) validate() error { + var errs []string + if m.PreviousUnitBalance == nil { + errs = append(errs, "required field `previous_unit_balance` is missing for type `Metered Usage`") + } + if m.NewUnitBalance == nil { + errs = append(errs, "required field `new_unit_balance` is missing for type `Metered Usage`") + } + if m.UsageQuantity == nil { + errs = append(errs, "required field `usage_quantity` is missing for type `Metered Usage`") + } + if m.ComponentId == nil { + errs = append(errs, "required field `component_id` is missing for type `Metered Usage`") + } + if m.ComponentHandle == nil { + errs = append(errs, "required field `component_handle` is missing for type `Metered Usage`") + } + if m.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Metered Usage`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/movement.go b/models/movement.go index ac243784..5be564c7 100644 --- a/models/movement.go +++ b/models/movement.go @@ -1,98 +1,100 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Movement represents a Movement struct. type Movement struct { - Timestamp *time.Time `json:"timestamp,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - AmountFormatted *string `json:"amount_formatted,omitempty"` - Description *string `json:"description,omitempty"` - Category *string `json:"category,omitempty"` - Breakouts *Breakouts `json:"breakouts,omitempty"` - LineItems []MovementLineItem `json:"line_items,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - SubscriberName *string `json:"subscriber_name,omitempty"` + Timestamp *time.Time `json:"timestamp,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + AmountFormatted *string `json:"amount_formatted,omitempty"` + Description *string `json:"description,omitempty"` + Category *string `json:"category,omitempty"` + Breakouts *Breakouts `json:"breakouts,omitempty"` + LineItems []MovementLineItem `json:"line_items,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + SubscriberName *string `json:"subscriber_name,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Movement. +// MarshalJSON implements the json.Marshaler interface for Movement. // It customizes the JSON marshaling process for Movement objects. func (m *Movement) MarshalJSON() ( - []byte, - error) { - return json.Marshal(m.toMap()) + []byte, + error) { + return json.Marshal(m.toMap()) } // toMap converts the Movement object to a map representation for JSON marshaling. func (m *Movement) toMap() map[string]any { - structMap := make(map[string]any) - if m.Timestamp != nil { - structMap["timestamp"] = m.Timestamp.Format(time.RFC3339) - } - if m.AmountInCents != nil { - structMap["amount_in_cents"] = m.AmountInCents - } - if m.AmountFormatted != nil { - structMap["amount_formatted"] = m.AmountFormatted - } - if m.Description != nil { - structMap["description"] = m.Description - } - if m.Category != nil { - structMap["category"] = m.Category - } - if m.Breakouts != nil { - structMap["breakouts"] = m.Breakouts.toMap() - } - if m.LineItems != nil { - structMap["line_items"] = m.LineItems - } - if m.SubscriptionId != nil { - structMap["subscription_id"] = m.SubscriptionId - } - if m.SubscriberName != nil { - structMap["subscriber_name"] = m.SubscriberName - } - return structMap + structMap := make(map[string]any) + if m.Timestamp != nil { + structMap["timestamp"] = m.Timestamp.Format(time.RFC3339) + } + if m.AmountInCents != nil { + structMap["amount_in_cents"] = m.AmountInCents + } + if m.AmountFormatted != nil { + structMap["amount_formatted"] = m.AmountFormatted + } + if m.Description != nil { + structMap["description"] = m.Description + } + if m.Category != nil { + structMap["category"] = m.Category + } + if m.Breakouts != nil { + structMap["breakouts"] = m.Breakouts.toMap() + } + if m.LineItems != nil { + structMap["line_items"] = m.LineItems + } + if m.SubscriptionId != nil { + structMap["subscription_id"] = m.SubscriptionId + } + if m.SubscriberName != nil { + structMap["subscriber_name"] = m.SubscriberName + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Movement. +// UnmarshalJSON implements the json.Unmarshaler interface for Movement. // It customizes the JSON unmarshaling process for Movement objects. func (m *Movement) UnmarshalJSON(input []byte) error { - temp := &struct { - Timestamp *string `json:"timestamp,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - AmountFormatted *string `json:"amount_formatted,omitempty"` - Description *string `json:"description,omitempty"` - Category *string `json:"category,omitempty"` - Breakouts *Breakouts `json:"breakouts,omitempty"` - LineItems []MovementLineItem `json:"line_items,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - SubscriberName *string `json:"subscriber_name,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - if temp.Timestamp != nil { - TimestampVal, err := time.Parse(time.RFC3339, *temp.Timestamp) - if err != nil { - log.Fatalf("Cannot Parse timestamp as % s format.", time.RFC3339) - } - m.Timestamp = &TimestampVal - } - m.AmountInCents = temp.AmountInCents - m.AmountFormatted = temp.AmountFormatted - m.Description = temp.Description - m.Category = temp.Category - m.Breakouts = temp.Breakouts - m.LineItems = temp.LineItems - m.SubscriptionId = temp.SubscriptionId - m.SubscriberName = temp.SubscriberName - return nil + var temp movement + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + if temp.Timestamp != nil { + TimestampVal, err := time.Parse(time.RFC3339, *temp.Timestamp) + if err != nil { + log.Fatalf("Cannot Parse timestamp as % s format.", time.RFC3339) + } + m.Timestamp = &TimestampVal + } + m.AmountInCents = temp.AmountInCents + m.AmountFormatted = temp.AmountFormatted + m.Description = temp.Description + m.Category = temp.Category + m.Breakouts = temp.Breakouts + m.LineItems = temp.LineItems + m.SubscriptionId = temp.SubscriptionId + m.SubscriberName = temp.SubscriberName + return nil +} + +// TODO +type movement struct { + Timestamp *string `json:"timestamp,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + AmountFormatted *string `json:"amount_formatted,omitempty"` + Description *string `json:"description,omitempty"` + Category *string `json:"category,omitempty"` + Breakouts *Breakouts `json:"breakouts,omitempty"` + LineItems []MovementLineItem `json:"line_items,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + SubscriberName *string `json:"subscriber_name,omitempty"` } diff --git a/models/movement_line_item.go b/models/movement_line_item.go index dfd92f7e..789ebc64 100644 --- a/models/movement_line_item.go +++ b/models/movement_line_item.go @@ -1,92 +1,94 @@ package models import ( - "encoding/json" + "encoding/json" ) // MovementLineItem represents a MovementLineItem struct. type MovementLineItem struct { - ProductId *int `json:"product_id,omitempty"` - // For Product (or "baseline") line items, this field will have a value of `0`. - ComponentId *int `json:"component_id,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - Name *string `json:"name,omitempty"` - Mrr *int `json:"mrr,omitempty"` - MrrMovements []MRRMovement `json:"mrr_movements,omitempty"` - Quantity *int `json:"quantity,omitempty"` - PrevQuantity *int `json:"prev_quantity,omitempty"` - // When `true`, the line item's MRR value will contribute to the `plan` breakout. When `false`, the line item contributes to the `usage` breakout. - Recurring *bool `json:"recurring,omitempty"` + ProductId *int `json:"product_id,omitempty"` + // For Product (or "baseline") line items, this field will have a value of `0`. + ComponentId *int `json:"component_id,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + Name *string `json:"name,omitempty"` + Mrr *int `json:"mrr,omitempty"` + MrrMovements []MRRMovement `json:"mrr_movements,omitempty"` + Quantity *int `json:"quantity,omitempty"` + PrevQuantity *int `json:"prev_quantity,omitempty"` + // When `true`, the line item's MRR value will contribute to the `plan` breakout. When `false`, the line item contributes to the `usage` breakout. + Recurring *bool `json:"recurring,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for MovementLineItem. +// MarshalJSON implements the json.Marshaler interface for MovementLineItem. // It customizes the JSON marshaling process for MovementLineItem objects. func (m *MovementLineItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(m.toMap()) + []byte, + error) { + return json.Marshal(m.toMap()) } // toMap converts the MovementLineItem object to a map representation for JSON marshaling. func (m *MovementLineItem) toMap() map[string]any { - structMap := make(map[string]any) - if m.ProductId != nil { - structMap["product_id"] = m.ProductId - } - if m.ComponentId != nil { - structMap["component_id"] = m.ComponentId - } - if m.PricePointId != nil { - structMap["price_point_id"] = m.PricePointId - } - if m.Name != nil { - structMap["name"] = m.Name - } - if m.Mrr != nil { - structMap["mrr"] = m.Mrr - } - if m.MrrMovements != nil { - structMap["mrr_movements"] = m.MrrMovements - } - if m.Quantity != nil { - structMap["quantity"] = m.Quantity - } - if m.PrevQuantity != nil { - structMap["prev_quantity"] = m.PrevQuantity - } - if m.Recurring != nil { - structMap["recurring"] = m.Recurring - } - return structMap + structMap := make(map[string]any) + if m.ProductId != nil { + structMap["product_id"] = m.ProductId + } + if m.ComponentId != nil { + structMap["component_id"] = m.ComponentId + } + if m.PricePointId != nil { + structMap["price_point_id"] = m.PricePointId + } + if m.Name != nil { + structMap["name"] = m.Name + } + if m.Mrr != nil { + structMap["mrr"] = m.Mrr + } + if m.MrrMovements != nil { + structMap["mrr_movements"] = m.MrrMovements + } + if m.Quantity != nil { + structMap["quantity"] = m.Quantity + } + if m.PrevQuantity != nil { + structMap["prev_quantity"] = m.PrevQuantity + } + if m.Recurring != nil { + structMap["recurring"] = m.Recurring + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for MovementLineItem. +// UnmarshalJSON implements the json.Unmarshaler interface for MovementLineItem. // It customizes the JSON unmarshaling process for MovementLineItem objects. func (m *MovementLineItem) UnmarshalJSON(input []byte) error { - temp := &struct { - ProductId *int `json:"product_id,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - Name *string `json:"name,omitempty"` - Mrr *int `json:"mrr,omitempty"` - MrrMovements []MRRMovement `json:"mrr_movements,omitempty"` - Quantity *int `json:"quantity,omitempty"` - PrevQuantity *int `json:"prev_quantity,omitempty"` - Recurring *bool `json:"recurring,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - m.ProductId = temp.ProductId - m.ComponentId = temp.ComponentId - m.PricePointId = temp.PricePointId - m.Name = temp.Name - m.Mrr = temp.Mrr - m.MrrMovements = temp.MrrMovements - m.Quantity = temp.Quantity - m.PrevQuantity = temp.PrevQuantity - m.Recurring = temp.Recurring - return nil + var temp movementLineItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + m.ProductId = temp.ProductId + m.ComponentId = temp.ComponentId + m.PricePointId = temp.PricePointId + m.Name = temp.Name + m.Mrr = temp.Mrr + m.MrrMovements = temp.MrrMovements + m.Quantity = temp.Quantity + m.PrevQuantity = temp.PrevQuantity + m.Recurring = temp.Recurring + return nil +} + +// TODO +type movementLineItem struct { + ProductId *int `json:"product_id,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + Name *string `json:"name,omitempty"` + Mrr *int `json:"mrr,omitempty"` + MrrMovements []MRRMovement `json:"mrr_movements,omitempty"` + Quantity *int `json:"quantity,omitempty"` + PrevQuantity *int `json:"prev_quantity,omitempty"` + Recurring *bool `json:"recurring,omitempty"` } diff --git a/models/mrr.go b/models/mrr.go index ad83f2b6..2b8942a2 100644 --- a/models/mrr.go +++ b/models/mrr.go @@ -1,81 +1,83 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // MRR represents a MRR struct. type MRR struct { - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - AmountFormatted *string `json:"amount_formatted,omitempty"` - Currency *string `json:"currency,omitempty"` - CurrencySymbol *string `json:"currency_symbol,omitempty"` - Breakouts *Breakouts `json:"breakouts,omitempty"` - // ISO8601 timestamp - AtTime *time.Time `json:"at_time,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + AmountFormatted *string `json:"amount_formatted,omitempty"` + Currency *string `json:"currency,omitempty"` + CurrencySymbol *string `json:"currency_symbol,omitempty"` + Breakouts *Breakouts `json:"breakouts,omitempty"` + // ISO8601 timestamp + AtTime *time.Time `json:"at_time,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for MRR. +// MarshalJSON implements the json.Marshaler interface for MRR. // It customizes the JSON marshaling process for MRR objects. func (m *MRR) MarshalJSON() ( - []byte, - error) { - return json.Marshal(m.toMap()) + []byte, + error) { + return json.Marshal(m.toMap()) } // toMap converts the MRR object to a map representation for JSON marshaling. func (m *MRR) toMap() map[string]any { - structMap := make(map[string]any) - if m.AmountInCents != nil { - structMap["amount_in_cents"] = m.AmountInCents - } - if m.AmountFormatted != nil { - structMap["amount_formatted"] = m.AmountFormatted - } - if m.Currency != nil { - structMap["currency"] = m.Currency - } - if m.CurrencySymbol != nil { - structMap["currency_symbol"] = m.CurrencySymbol - } - if m.Breakouts != nil { - structMap["breakouts"] = m.Breakouts.toMap() - } - if m.AtTime != nil { - structMap["at_time"] = m.AtTime.Format(time.RFC3339) - } - return structMap + structMap := make(map[string]any) + if m.AmountInCents != nil { + structMap["amount_in_cents"] = m.AmountInCents + } + if m.AmountFormatted != nil { + structMap["amount_formatted"] = m.AmountFormatted + } + if m.Currency != nil { + structMap["currency"] = m.Currency + } + if m.CurrencySymbol != nil { + structMap["currency_symbol"] = m.CurrencySymbol + } + if m.Breakouts != nil { + structMap["breakouts"] = m.Breakouts.toMap() + } + if m.AtTime != nil { + structMap["at_time"] = m.AtTime.Format(time.RFC3339) + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for MRR. +// UnmarshalJSON implements the json.Unmarshaler interface for MRR. // It customizes the JSON unmarshaling process for MRR objects. func (m *MRR) UnmarshalJSON(input []byte) error { - temp := &struct { - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - AmountFormatted *string `json:"amount_formatted,omitempty"` - Currency *string `json:"currency,omitempty"` - CurrencySymbol *string `json:"currency_symbol,omitempty"` - Breakouts *Breakouts `json:"breakouts,omitempty"` - AtTime *string `json:"at_time,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - m.AmountInCents = temp.AmountInCents - m.AmountFormatted = temp.AmountFormatted - m.Currency = temp.Currency - m.CurrencySymbol = temp.CurrencySymbol - m.Breakouts = temp.Breakouts - if temp.AtTime != nil { - AtTimeVal, err := time.Parse(time.RFC3339, *temp.AtTime) - if err != nil { - log.Fatalf("Cannot Parse at_time as % s format.", time.RFC3339) - } - m.AtTime = &AtTimeVal - } - return nil + var temp mrr + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + m.AmountInCents = temp.AmountInCents + m.AmountFormatted = temp.AmountFormatted + m.Currency = temp.Currency + m.CurrencySymbol = temp.CurrencySymbol + m.Breakouts = temp.Breakouts + if temp.AtTime != nil { + AtTimeVal, err := time.Parse(time.RFC3339, *temp.AtTime) + if err != nil { + log.Fatalf("Cannot Parse at_time as % s format.", time.RFC3339) + } + m.AtTime = &AtTimeVal + } + return nil +} + +// TODO +type mrr struct { + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + AmountFormatted *string `json:"amount_formatted,omitempty"` + Currency *string `json:"currency,omitempty"` + CurrencySymbol *string `json:"currency_symbol,omitempty"` + Breakouts *Breakouts `json:"breakouts,omitempty"` + AtTime *string `json:"at_time,omitempty"` } diff --git a/models/mrr_movement.go b/models/mrr_movement.go index 76538e16..223c4471 100644 --- a/models/mrr_movement.go +++ b/models/mrr_movement.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // MRRMovement represents a MRRMovement struct. type MRRMovement struct { - Amount *int `json:"amount,omitempty"` - Category *string `json:"category,omitempty"` - SubscriberDelta *int `json:"subscriber_delta,omitempty"` - LeadDelta *int `json:"lead_delta,omitempty"` + Amount *int `json:"amount,omitempty"` + Category *string `json:"category,omitempty"` + SubscriberDelta *int `json:"subscriber_delta,omitempty"` + LeadDelta *int `json:"lead_delta,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for MRRMovement. +// MarshalJSON implements the json.Marshaler interface for MRRMovement. // It customizes the JSON marshaling process for MRRMovement objects. func (m *MRRMovement) MarshalJSON() ( - []byte, - error) { - return json.Marshal(m.toMap()) + []byte, + error) { + return json.Marshal(m.toMap()) } // toMap converts the MRRMovement object to a map representation for JSON marshaling. func (m *MRRMovement) toMap() map[string]any { - structMap := make(map[string]any) - if m.Amount != nil { - structMap["amount"] = m.Amount - } - if m.Category != nil { - structMap["category"] = m.Category - } - if m.SubscriberDelta != nil { - structMap["subscriber_delta"] = m.SubscriberDelta - } - if m.LeadDelta != nil { - structMap["lead_delta"] = m.LeadDelta - } - return structMap + structMap := make(map[string]any) + if m.Amount != nil { + structMap["amount"] = m.Amount + } + if m.Category != nil { + structMap["category"] = m.Category + } + if m.SubscriberDelta != nil { + structMap["subscriber_delta"] = m.SubscriberDelta + } + if m.LeadDelta != nil { + structMap["lead_delta"] = m.LeadDelta + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for MRRMovement. +// UnmarshalJSON implements the json.Unmarshaler interface for MRRMovement. // It customizes the JSON unmarshaling process for MRRMovement objects. func (m *MRRMovement) UnmarshalJSON(input []byte) error { - temp := &struct { - Amount *int `json:"amount,omitempty"` - Category *string `json:"category,omitempty"` - SubscriberDelta *int `json:"subscriber_delta,omitempty"` - LeadDelta *int `json:"lead_delta,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - m.Amount = temp.Amount - m.Category = temp.Category - m.SubscriberDelta = temp.SubscriberDelta - m.LeadDelta = temp.LeadDelta - return nil + var temp mrrMovement + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + m.Amount = temp.Amount + m.Category = temp.Category + m.SubscriberDelta = temp.SubscriberDelta + m.LeadDelta = temp.LeadDelta + return nil +} + +// TODO +type mrrMovement struct { + Amount *int `json:"amount,omitempty"` + Category *string `json:"category,omitempty"` + SubscriberDelta *int `json:"subscriber_delta,omitempty"` + LeadDelta *int `json:"lead_delta,omitempty"` } diff --git a/models/mrr_response.go b/models/mrr_response.go index 378dfdee..287a8f05 100644 --- a/models/mrr_response.go +++ b/models/mrr_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // MRRResponse represents a MRRResponse struct. type MRRResponse struct { - Mrr MRR `json:"mrr"` + Mrr MRR `json:"mrr"` } -// MarshalJSON implements the json.Marshaler interface for MRRResponse. +// MarshalJSON implements the json.Marshaler interface for MRRResponse. // It customizes the JSON marshaling process for MRRResponse objects. func (m *MRRResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(m.toMap()) + []byte, + error) { + return json.Marshal(m.toMap()) } // toMap converts the MRRResponse object to a map representation for JSON marshaling. func (m *MRRResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["mrr"] = m.Mrr.toMap() - return structMap + structMap := make(map[string]any) + structMap["mrr"] = m.Mrr.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for MRRResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for MRRResponse. // It customizes the JSON unmarshaling process for MRRResponse objects. func (m *MRRResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Mrr MRR `json:"mrr"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - m.Mrr = temp.Mrr - return nil + var temp mrrResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + m.Mrr = *temp.Mrr + return nil +} + +// TODO +type mrrResponse struct { + Mrr *MRR `json:"mrr"` +} + +func (m *mrrResponse) validate() error { + var errs []string + if m.Mrr == nil { + errs = append(errs, "required field `mrr` is missing for type `MRR response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/multi_invoice_payment.go b/models/multi_invoice_payment.go index 66fc2d80..860717f7 100644 --- a/models/multi_invoice_payment.go +++ b/models/multi_invoice_payment.go @@ -1,63 +1,65 @@ package models import ( - "encoding/json" + "encoding/json" ) // MultiInvoicePayment represents a MultiInvoicePayment struct. type MultiInvoicePayment struct { - // The numeric ID of the transaction. - TransactionId *int `json:"transaction_id,omitempty"` - // Dollar amount of the sum of the paid invoices. - TotalAmount *string `json:"total_amount,omitempty"` - // The ISO 4217 currency code (3 character string) representing the currency of invoice transaction. - CurrencyCode *string `json:"currency_code,omitempty"` - Applications []InvoicePaymentApplication `json:"applications,omitempty"` + // The numeric ID of the transaction. + TransactionId *int `json:"transaction_id,omitempty"` + // Dollar amount of the sum of the paid invoices. + TotalAmount *string `json:"total_amount,omitempty"` + // The ISO 4217 currency code (3 character string) representing the currency of invoice transaction. + CurrencyCode *string `json:"currency_code,omitempty"` + Applications []InvoicePaymentApplication `json:"applications,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for MultiInvoicePayment. +// MarshalJSON implements the json.Marshaler interface for MultiInvoicePayment. // It customizes the JSON marshaling process for MultiInvoicePayment objects. func (m *MultiInvoicePayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(m.toMap()) + []byte, + error) { + return json.Marshal(m.toMap()) } // toMap converts the MultiInvoicePayment object to a map representation for JSON marshaling. func (m *MultiInvoicePayment) toMap() map[string]any { - structMap := make(map[string]any) - if m.TransactionId != nil { - structMap["transaction_id"] = m.TransactionId - } - if m.TotalAmount != nil { - structMap["total_amount"] = m.TotalAmount - } - if m.CurrencyCode != nil { - structMap["currency_code"] = m.CurrencyCode - } - if m.Applications != nil { - structMap["applications"] = m.Applications - } - return structMap + structMap := make(map[string]any) + if m.TransactionId != nil { + structMap["transaction_id"] = m.TransactionId + } + if m.TotalAmount != nil { + structMap["total_amount"] = m.TotalAmount + } + if m.CurrencyCode != nil { + structMap["currency_code"] = m.CurrencyCode + } + if m.Applications != nil { + structMap["applications"] = m.Applications + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for MultiInvoicePayment. +// UnmarshalJSON implements the json.Unmarshaler interface for MultiInvoicePayment. // It customizes the JSON unmarshaling process for MultiInvoicePayment objects. func (m *MultiInvoicePayment) UnmarshalJSON(input []byte) error { - temp := &struct { - TransactionId *int `json:"transaction_id,omitempty"` - TotalAmount *string `json:"total_amount,omitempty"` - CurrencyCode *string `json:"currency_code,omitempty"` - Applications []InvoicePaymentApplication `json:"applications,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - m.TransactionId = temp.TransactionId - m.TotalAmount = temp.TotalAmount - m.CurrencyCode = temp.CurrencyCode - m.Applications = temp.Applications - return nil + var temp multiInvoicePayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + m.TransactionId = temp.TransactionId + m.TotalAmount = temp.TotalAmount + m.CurrencyCode = temp.CurrencyCode + m.Applications = temp.Applications + return nil +} + +// TODO +type multiInvoicePayment struct { + TransactionId *int `json:"transaction_id,omitempty"` + TotalAmount *string `json:"total_amount,omitempty"` + CurrencyCode *string `json:"currency_code,omitempty"` + Applications []InvoicePaymentApplication `json:"applications,omitempty"` } diff --git a/models/multi_invoice_payment_response.go b/models/multi_invoice_payment_response.go index 430edd56..a23f5d83 100644 --- a/models/multi_invoice_payment_response.go +++ b/models/multi_invoice_payment_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // MultiInvoicePaymentResponse represents a MultiInvoicePaymentResponse struct. type MultiInvoicePaymentResponse struct { - Payment MultiInvoicePayment `json:"payment"` + Payment MultiInvoicePayment `json:"payment"` } -// MarshalJSON implements the json.Marshaler interface for MultiInvoicePaymentResponse. +// MarshalJSON implements the json.Marshaler interface for MultiInvoicePaymentResponse. // It customizes the JSON marshaling process for MultiInvoicePaymentResponse objects. func (m *MultiInvoicePaymentResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(m.toMap()) + []byte, + error) { + return json.Marshal(m.toMap()) } // toMap converts the MultiInvoicePaymentResponse object to a map representation for JSON marshaling. func (m *MultiInvoicePaymentResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["payment"] = m.Payment.toMap() - return structMap + structMap := make(map[string]any) + structMap["payment"] = m.Payment.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for MultiInvoicePaymentResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for MultiInvoicePaymentResponse. // It customizes the JSON unmarshaling process for MultiInvoicePaymentResponse objects. func (m *MultiInvoicePaymentResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Payment MultiInvoicePayment `json:"payment"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - m.Payment = temp.Payment - return nil + var temp multiInvoicePaymentResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + m.Payment = *temp.Payment + return nil +} + +// TODO +type multiInvoicePaymentResponse struct { + Payment *MultiInvoicePayment `json:"payment"` +} + +func (m *multiInvoicePaymentResponse) validate() error { + var errs []string + if m.Payment == nil { + errs = append(errs, "required field `payment` is missing for type `Multi Invoice Payment Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/nested_subscription_group.go b/models/nested_subscription_group.go index 3475fbea..f7d903ee 100644 --- a/models/nested_subscription_group.go +++ b/models/nested_subscription_group.go @@ -1,64 +1,66 @@ package models import ( - "encoding/json" + "encoding/json" ) // NestedSubscriptionGroup represents a NestedSubscriptionGroup struct. type NestedSubscriptionGroup struct { - // The UID for the group - Uid *string `json:"uid,omitempty"` - // Whether the group is configured to rely on a primary subscription for billing. At this time, it will always be 1. - Scheme *int `json:"scheme,omitempty"` - // The subscription ID of the primary within the group. Applicable to scheme 1. - PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` - // A boolean indicating whether the subscription is the primary in the group. Applicable to scheme 1. - Primary *bool `json:"primary,omitempty"` + // The UID for the group + Uid *string `json:"uid,omitempty"` + // Whether the group is configured to rely on a primary subscription for billing. At this time, it will always be 1. + Scheme *int `json:"scheme,omitempty"` + // The subscription ID of the primary within the group. Applicable to scheme 1. + PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` + // A boolean indicating whether the subscription is the primary in the group. Applicable to scheme 1. + Primary *bool `json:"primary,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for NestedSubscriptionGroup. +// MarshalJSON implements the json.Marshaler interface for NestedSubscriptionGroup. // It customizes the JSON marshaling process for NestedSubscriptionGroup objects. func (n *NestedSubscriptionGroup) MarshalJSON() ( - []byte, - error) { - return json.Marshal(n.toMap()) + []byte, + error) { + return json.Marshal(n.toMap()) } // toMap converts the NestedSubscriptionGroup object to a map representation for JSON marshaling. func (n *NestedSubscriptionGroup) toMap() map[string]any { - structMap := make(map[string]any) - if n.Uid != nil { - structMap["uid"] = n.Uid - } - if n.Scheme != nil { - structMap["scheme"] = n.Scheme - } - if n.PrimarySubscriptionId != nil { - structMap["primary_subscription_id"] = n.PrimarySubscriptionId - } - if n.Primary != nil { - structMap["primary"] = n.Primary - } - return structMap + structMap := make(map[string]any) + if n.Uid != nil { + structMap["uid"] = n.Uid + } + if n.Scheme != nil { + structMap["scheme"] = n.Scheme + } + if n.PrimarySubscriptionId != nil { + structMap["primary_subscription_id"] = n.PrimarySubscriptionId + } + if n.Primary != nil { + structMap["primary"] = n.Primary + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for NestedSubscriptionGroup. +// UnmarshalJSON implements the json.Unmarshaler interface for NestedSubscriptionGroup. // It customizes the JSON unmarshaling process for NestedSubscriptionGroup objects. func (n *NestedSubscriptionGroup) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Scheme *int `json:"scheme,omitempty"` - PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` - Primary *bool `json:"primary,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - n.Uid = temp.Uid - n.Scheme = temp.Scheme - n.PrimarySubscriptionId = temp.PrimarySubscriptionId - n.Primary = temp.Primary - return nil + var temp nestedSubscriptionGroup + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + n.Uid = temp.Uid + n.Scheme = temp.Scheme + n.PrimarySubscriptionId = temp.PrimarySubscriptionId + n.Primary = temp.Primary + return nil +} + +// TODO +type nestedSubscriptionGroup struct { + Uid *string `json:"uid,omitempty"` + Scheme *int `json:"scheme,omitempty"` + PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` + Primary *bool `json:"primary,omitempty"` } diff --git a/models/net_terms.go b/models/net_terms.go index c92373c3..8135e9bf 100644 --- a/models/net_terms.go +++ b/models/net_terms.go @@ -1,66 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" ) // NetTerms represents a NetTerms struct. type NetTerms struct { - DefaultNetTerms *int `json:"default_net_terms,omitempty"` - AutomaticNetTerms *int `json:"automatic_net_terms,omitempty"` - RemittanceNetTerms *int `json:"remittance_net_terms,omitempty"` - NetTermsOnRemittanceSignupsEnabled *bool `json:"net_terms_on_remittance_signups_enabled,omitempty"` - CustomNetTermsEnabled *bool `json:"custom_net_terms_enabled,omitempty"` + DefaultNetTerms *int `json:"default_net_terms,omitempty"` + AutomaticNetTerms *int `json:"automatic_net_terms,omitempty"` + RemittanceNetTerms *int `json:"remittance_net_terms,omitempty"` + NetTermsOnRemittanceSignupsEnabled *bool `json:"net_terms_on_remittance_signups_enabled,omitempty"` + CustomNetTermsEnabled *bool `json:"custom_net_terms_enabled,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for NetTerms. +// MarshalJSON implements the json.Marshaler interface for NetTerms. // It customizes the JSON marshaling process for NetTerms objects. func (n *NetTerms) MarshalJSON() ( - []byte, - error) { - return json.Marshal(n.toMap()) + []byte, + error) { + return json.Marshal(n.toMap()) } // toMap converts the NetTerms object to a map representation for JSON marshaling. func (n *NetTerms) toMap() map[string]any { - structMap := make(map[string]any) - if n.DefaultNetTerms != nil { - structMap["default_net_terms"] = n.DefaultNetTerms - } - if n.AutomaticNetTerms != nil { - structMap["automatic_net_terms"] = n.AutomaticNetTerms - } - if n.RemittanceNetTerms != nil { - structMap["remittance_net_terms"] = n.RemittanceNetTerms - } - if n.NetTermsOnRemittanceSignupsEnabled != nil { - structMap["net_terms_on_remittance_signups_enabled"] = n.NetTermsOnRemittanceSignupsEnabled - } - if n.CustomNetTermsEnabled != nil { - structMap["custom_net_terms_enabled"] = n.CustomNetTermsEnabled - } - return structMap + structMap := make(map[string]any) + if n.DefaultNetTerms != nil { + structMap["default_net_terms"] = n.DefaultNetTerms + } + if n.AutomaticNetTerms != nil { + structMap["automatic_net_terms"] = n.AutomaticNetTerms + } + if n.RemittanceNetTerms != nil { + structMap["remittance_net_terms"] = n.RemittanceNetTerms + } + if n.NetTermsOnRemittanceSignupsEnabled != nil { + structMap["net_terms_on_remittance_signups_enabled"] = n.NetTermsOnRemittanceSignupsEnabled + } + if n.CustomNetTermsEnabled != nil { + structMap["custom_net_terms_enabled"] = n.CustomNetTermsEnabled + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for NetTerms. +// UnmarshalJSON implements the json.Unmarshaler interface for NetTerms. // It customizes the JSON unmarshaling process for NetTerms objects. func (n *NetTerms) UnmarshalJSON(input []byte) error { - temp := &struct { - DefaultNetTerms *int `json:"default_net_terms,omitempty"` - AutomaticNetTerms *int `json:"automatic_net_terms,omitempty"` - RemittanceNetTerms *int `json:"remittance_net_terms,omitempty"` - NetTermsOnRemittanceSignupsEnabled *bool `json:"net_terms_on_remittance_signups_enabled,omitempty"` - CustomNetTermsEnabled *bool `json:"custom_net_terms_enabled,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - n.DefaultNetTerms = temp.DefaultNetTerms - n.AutomaticNetTerms = temp.AutomaticNetTerms - n.RemittanceNetTerms = temp.RemittanceNetTerms - n.NetTermsOnRemittanceSignupsEnabled = temp.NetTermsOnRemittanceSignupsEnabled - n.CustomNetTermsEnabled = temp.CustomNetTermsEnabled - return nil + var temp netTerms + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + n.DefaultNetTerms = temp.DefaultNetTerms + n.AutomaticNetTerms = temp.AutomaticNetTerms + n.RemittanceNetTerms = temp.RemittanceNetTerms + n.NetTermsOnRemittanceSignupsEnabled = temp.NetTermsOnRemittanceSignupsEnabled + n.CustomNetTermsEnabled = temp.CustomNetTermsEnabled + return nil +} + +// TODO +type netTerms struct { + DefaultNetTerms *int `json:"default_net_terms,omitempty"` + AutomaticNetTerms *int `json:"automatic_net_terms,omitempty"` + RemittanceNetTerms *int `json:"remittance_net_terms,omitempty"` + NetTermsOnRemittanceSignupsEnabled *bool `json:"net_terms_on_remittance_signups_enabled,omitempty"` + CustomNetTermsEnabled *bool `json:"custom_net_terms_enabled,omitempty"` } diff --git a/models/offer.go b/models/offer.go index 8ca130a1..4fd2581e 100644 --- a/models/offer.go +++ b/models/offer.go @@ -1,176 +1,186 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Offer represents a Offer struct. type Offer struct { - Id *int `json:"id,omitempty"` - SiteId *int `json:"site_id,omitempty"` - ProductFamilyId *int `json:"product_family_id,omitempty"` - ProductId *int `json:"product_id,omitempty"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - ProductRevisableNumber *int `json:"product_revisable_number,omitempty"` - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - Description Optional[string] `json:"description"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - ArchivedAt Optional[time.Time] `json:"archived_at"` - OfferItems []OfferItem `json:"offer_items,omitempty"` - OfferDiscounts []OfferDiscount `json:"offer_discounts,omitempty"` - ProductFamilyName *string `json:"product_family_name,omitempty"` - ProductName *string `json:"product_name,omitempty"` - ProductPricePointName *string `json:"product_price_point_name,omitempty"` - ProductPriceInCents *int64 `json:"product_price_in_cents,omitempty"` - OfferSignupPages []OfferSignupPage `json:"offer_signup_pages,omitempty"` + Id *int `json:"id,omitempty"` + SiteId *int `json:"site_id,omitempty"` + ProductFamilyId *int `json:"product_family_id,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + ProductRevisableNumber *int `json:"product_revisable_number,omitempty"` + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + Description Optional[string] `json:"description"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + ArchivedAt Optional[time.Time] `json:"archived_at"` + OfferItems []OfferItem `json:"offer_items,omitempty"` + OfferDiscounts []OfferDiscount `json:"offer_discounts,omitempty"` + ProductFamilyName *string `json:"product_family_name,omitempty"` + ProductName *string `json:"product_name,omitempty"` + ProductPricePointName *string `json:"product_price_point_name,omitempty"` + ProductPriceInCents *int64 `json:"product_price_in_cents,omitempty"` + OfferSignupPages []OfferSignupPage `json:"offer_signup_pages,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Offer. +// MarshalJSON implements the json.Marshaler interface for Offer. // It customizes the JSON marshaling process for Offer objects. func (o *Offer) MarshalJSON() ( - []byte, - error) { - return json.Marshal(o.toMap()) + []byte, + error) { + return json.Marshal(o.toMap()) } // toMap converts the Offer object to a map representation for JSON marshaling. func (o *Offer) toMap() map[string]any { - structMap := make(map[string]any) - if o.Id != nil { - structMap["id"] = o.Id - } - if o.SiteId != nil { - structMap["site_id"] = o.SiteId - } - if o.ProductFamilyId != nil { - structMap["product_family_id"] = o.ProductFamilyId - } - if o.ProductId != nil { - structMap["product_id"] = o.ProductId - } - if o.ProductPricePointId != nil { - structMap["product_price_point_id"] = o.ProductPricePointId - } - if o.ProductRevisableNumber != nil { - structMap["product_revisable_number"] = o.ProductRevisableNumber - } - if o.Name != nil { - structMap["name"] = o.Name - } - if o.Handle != nil { - structMap["handle"] = o.Handle - } - if o.Description.IsValueSet() { - structMap["description"] = o.Description.Value() - } - if o.CreatedAt != nil { - structMap["created_at"] = o.CreatedAt.Format(time.RFC3339) - } - if o.UpdatedAt != nil { - structMap["updated_at"] = o.UpdatedAt.Format(time.RFC3339) - } - if o.ArchivedAt.IsValueSet() { - var ArchivedAtVal *string = nil - if o.ArchivedAt.Value() != nil { - val := o.ArchivedAt.Value().Format(time.RFC3339) - ArchivedAtVal = &val - } - structMap["archived_at"] = ArchivedAtVal - } - if o.OfferItems != nil { - structMap["offer_items"] = o.OfferItems - } - if o.OfferDiscounts != nil { - structMap["offer_discounts"] = o.OfferDiscounts - } - if o.ProductFamilyName != nil { - structMap["product_family_name"] = o.ProductFamilyName - } - if o.ProductName != nil { - structMap["product_name"] = o.ProductName - } - if o.ProductPricePointName != nil { - structMap["product_price_point_name"] = o.ProductPricePointName - } - if o.ProductPriceInCents != nil { - structMap["product_price_in_cents"] = o.ProductPriceInCents - } - if o.OfferSignupPages != nil { - structMap["offer_signup_pages"] = o.OfferSignupPages - } - return structMap + structMap := make(map[string]any) + if o.Id != nil { + structMap["id"] = o.Id + } + if o.SiteId != nil { + structMap["site_id"] = o.SiteId + } + if o.ProductFamilyId != nil { + structMap["product_family_id"] = o.ProductFamilyId + } + if o.ProductId != nil { + structMap["product_id"] = o.ProductId + } + if o.ProductPricePointId != nil { + structMap["product_price_point_id"] = o.ProductPricePointId + } + if o.ProductRevisableNumber != nil { + structMap["product_revisable_number"] = o.ProductRevisableNumber + } + if o.Name != nil { + structMap["name"] = o.Name + } + if o.Handle != nil { + structMap["handle"] = o.Handle + } + if o.Description.IsValueSet() { + if o.Description.Value() != nil { + structMap["description"] = o.Description.Value() + } else { + structMap["description"] = nil + } + } + if o.CreatedAt != nil { + structMap["created_at"] = o.CreatedAt.Format(time.RFC3339) + } + if o.UpdatedAt != nil { + structMap["updated_at"] = o.UpdatedAt.Format(time.RFC3339) + } + if o.ArchivedAt.IsValueSet() { + var ArchivedAtVal *string = nil + if o.ArchivedAt.Value() != nil { + val := o.ArchivedAt.Value().Format(time.RFC3339) + ArchivedAtVal = &val + } + if o.ArchivedAt.Value() != nil { + structMap["archived_at"] = ArchivedAtVal + } else { + structMap["archived_at"] = nil + } + } + if o.OfferItems != nil { + structMap["offer_items"] = o.OfferItems + } + if o.OfferDiscounts != nil { + structMap["offer_discounts"] = o.OfferDiscounts + } + if o.ProductFamilyName != nil { + structMap["product_family_name"] = o.ProductFamilyName + } + if o.ProductName != nil { + structMap["product_name"] = o.ProductName + } + if o.ProductPricePointName != nil { + structMap["product_price_point_name"] = o.ProductPricePointName + } + if o.ProductPriceInCents != nil { + structMap["product_price_in_cents"] = o.ProductPriceInCents + } + if o.OfferSignupPages != nil { + structMap["offer_signup_pages"] = o.OfferSignupPages + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Offer. +// UnmarshalJSON implements the json.Unmarshaler interface for Offer. // It customizes the JSON unmarshaling process for Offer objects. func (o *Offer) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - SiteId *int `json:"site_id,omitempty"` - ProductFamilyId *int `json:"product_family_id,omitempty"` - ProductId *int `json:"product_id,omitempty"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - ProductRevisableNumber *int `json:"product_revisable_number,omitempty"` - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - Description Optional[string] `json:"description"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - ArchivedAt Optional[string] `json:"archived_at"` - OfferItems []OfferItem `json:"offer_items,omitempty"` - OfferDiscounts []OfferDiscount `json:"offer_discounts,omitempty"` - ProductFamilyName *string `json:"product_family_name,omitempty"` - ProductName *string `json:"product_name,omitempty"` - ProductPricePointName *string `json:"product_price_point_name,omitempty"` - ProductPriceInCents *int64 `json:"product_price_in_cents,omitempty"` - OfferSignupPages []OfferSignupPage `json:"offer_signup_pages,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - o.Id = temp.Id - o.SiteId = temp.SiteId - o.ProductFamilyId = temp.ProductFamilyId - o.ProductId = temp.ProductId - o.ProductPricePointId = temp.ProductPricePointId - o.ProductRevisableNumber = temp.ProductRevisableNumber - o.Name = temp.Name - o.Handle = temp.Handle - o.Description = temp.Description - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - o.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - o.UpdatedAt = &UpdatedAtVal - } - o.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) - if temp.ArchivedAt.Value() != nil { - ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) - } - o.ArchivedAt.SetValue(&ArchivedAtVal) - } - o.OfferItems = temp.OfferItems - o.OfferDiscounts = temp.OfferDiscounts - o.ProductFamilyName = temp.ProductFamilyName - o.ProductName = temp.ProductName - o.ProductPricePointName = temp.ProductPricePointName - o.ProductPriceInCents = temp.ProductPriceInCents - o.OfferSignupPages = temp.OfferSignupPages - return nil + var temp offer + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + o.Id = temp.Id + o.SiteId = temp.SiteId + o.ProductFamilyId = temp.ProductFamilyId + o.ProductId = temp.ProductId + o.ProductPricePointId = temp.ProductPricePointId + o.ProductRevisableNumber = temp.ProductRevisableNumber + o.Name = temp.Name + o.Handle = temp.Handle + o.Description = temp.Description + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + o.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + o.UpdatedAt = &UpdatedAtVal + } + o.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) + if temp.ArchivedAt.Value() != nil { + ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) + } + o.ArchivedAt.SetValue(&ArchivedAtVal) + } + o.OfferItems = temp.OfferItems + o.OfferDiscounts = temp.OfferDiscounts + o.ProductFamilyName = temp.ProductFamilyName + o.ProductName = temp.ProductName + o.ProductPricePointName = temp.ProductPricePointName + o.ProductPriceInCents = temp.ProductPriceInCents + o.OfferSignupPages = temp.OfferSignupPages + return nil +} + +// TODO +type offer struct { + Id *int `json:"id,omitempty"` + SiteId *int `json:"site_id,omitempty"` + ProductFamilyId *int `json:"product_family_id,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + ProductRevisableNumber *int `json:"product_revisable_number,omitempty"` + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + Description Optional[string] `json:"description"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + ArchivedAt Optional[string] `json:"archived_at"` + OfferItems []OfferItem `json:"offer_items,omitempty"` + OfferDiscounts []OfferDiscount `json:"offer_discounts,omitempty"` + ProductFamilyName *string `json:"product_family_name,omitempty"` + ProductName *string `json:"product_name,omitempty"` + ProductPricePointName *string `json:"product_price_point_name,omitempty"` + ProductPriceInCents *int64 `json:"product_price_in_cents,omitempty"` + OfferSignupPages []OfferSignupPage `json:"offer_signup_pages,omitempty"` } diff --git a/models/offer_discount.go b/models/offer_discount.go index 58ae2035..8134545c 100644 --- a/models/offer_discount.go +++ b/models/offer_discount.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // OfferDiscount represents a OfferDiscount struct. type OfferDiscount struct { - CouponCode *string `json:"coupon_code,omitempty"` - CouponId *int `json:"coupon_id,omitempty"` - CouponName *string `json:"coupon_name,omitempty"` + CouponCode *string `json:"coupon_code,omitempty"` + CouponId *int `json:"coupon_id,omitempty"` + CouponName *string `json:"coupon_name,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for OfferDiscount. +// MarshalJSON implements the json.Marshaler interface for OfferDiscount. // It customizes the JSON marshaling process for OfferDiscount objects. func (o *OfferDiscount) MarshalJSON() ( - []byte, - error) { - return json.Marshal(o.toMap()) + []byte, + error) { + return json.Marshal(o.toMap()) } // toMap converts the OfferDiscount object to a map representation for JSON marshaling. func (o *OfferDiscount) toMap() map[string]any { - structMap := make(map[string]any) - if o.CouponCode != nil { - structMap["coupon_code"] = o.CouponCode - } - if o.CouponId != nil { - structMap["coupon_id"] = o.CouponId - } - if o.CouponName != nil { - structMap["coupon_name"] = o.CouponName - } - return structMap + structMap := make(map[string]any) + if o.CouponCode != nil { + structMap["coupon_code"] = o.CouponCode + } + if o.CouponId != nil { + structMap["coupon_id"] = o.CouponId + } + if o.CouponName != nil { + structMap["coupon_name"] = o.CouponName + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for OfferDiscount. +// UnmarshalJSON implements the json.Unmarshaler interface for OfferDiscount. // It customizes the JSON unmarshaling process for OfferDiscount objects. func (o *OfferDiscount) UnmarshalJSON(input []byte) error { - temp := &struct { - CouponCode *string `json:"coupon_code,omitempty"` - CouponId *int `json:"coupon_id,omitempty"` - CouponName *string `json:"coupon_name,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - o.CouponCode = temp.CouponCode - o.CouponId = temp.CouponId - o.CouponName = temp.CouponName - return nil + var temp offerDiscount + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + o.CouponCode = temp.CouponCode + o.CouponId = temp.CouponId + o.CouponName = temp.CouponName + return nil +} + +// TODO +type offerDiscount struct { + CouponCode *string `json:"coupon_code,omitempty"` + CouponId *int `json:"coupon_id,omitempty"` + CouponName *string `json:"coupon_name,omitempty"` } diff --git a/models/offer_item.go b/models/offer_item.go index e8b15399..18a34787 100644 --- a/models/offer_item.go +++ b/models/offer_item.go @@ -1,98 +1,100 @@ package models import ( - "encoding/json" + "encoding/json" ) // OfferItem represents a OfferItem struct. type OfferItem struct { - ComponentId *int `json:"component_id,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - StartingQuantity *string `json:"starting_quantity,omitempty"` - Editable *bool `json:"editable,omitempty"` - ComponentUnitPrice *string `json:"component_unit_price,omitempty"` - ComponentName *string `json:"component_name,omitempty"` - PricePointName *string `json:"price_point_name,omitempty"` - CurrencyPrices []CurrencyPrice `json:"currency_prices,omitempty"` - // The numerical interval. i.e. an interval of '30' coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + StartingQuantity *string `json:"starting_quantity,omitempty"` + Editable *bool `json:"editable,omitempty"` + ComponentUnitPrice *string `json:"component_unit_price,omitempty"` + ComponentName *string `json:"component_name,omitempty"` + PricePointName *string `json:"price_point_name,omitempty"` + CurrencyPrices []CurrencyPrice `json:"currency_prices,omitempty"` + // The numerical interval. i.e. an interval of '30' coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for OfferItem. +// MarshalJSON implements the json.Marshaler interface for OfferItem. // It customizes the JSON marshaling process for OfferItem objects. func (o *OfferItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(o.toMap()) + []byte, + error) { + return json.Marshal(o.toMap()) } // toMap converts the OfferItem object to a map representation for JSON marshaling. func (o *OfferItem) toMap() map[string]any { - structMap := make(map[string]any) - if o.ComponentId != nil { - structMap["component_id"] = o.ComponentId - } - if o.PricePointId != nil { - structMap["price_point_id"] = o.PricePointId - } - if o.StartingQuantity != nil { - structMap["starting_quantity"] = o.StartingQuantity - } - if o.Editable != nil { - structMap["editable"] = o.Editable - } - if o.ComponentUnitPrice != nil { - structMap["component_unit_price"] = o.ComponentUnitPrice - } - if o.ComponentName != nil { - structMap["component_name"] = o.ComponentName - } - if o.PricePointName != nil { - structMap["price_point_name"] = o.PricePointName - } - if o.CurrencyPrices != nil { - structMap["currency_prices"] = o.CurrencyPrices - } - if o.Interval != nil { - structMap["interval"] = o.Interval - } - if o.IntervalUnit != nil { - structMap["interval_unit"] = o.IntervalUnit - } - return structMap + structMap := make(map[string]any) + if o.ComponentId != nil { + structMap["component_id"] = o.ComponentId + } + if o.PricePointId != nil { + structMap["price_point_id"] = o.PricePointId + } + if o.StartingQuantity != nil { + structMap["starting_quantity"] = o.StartingQuantity + } + if o.Editable != nil { + structMap["editable"] = o.Editable + } + if o.ComponentUnitPrice != nil { + structMap["component_unit_price"] = o.ComponentUnitPrice + } + if o.ComponentName != nil { + structMap["component_name"] = o.ComponentName + } + if o.PricePointName != nil { + structMap["price_point_name"] = o.PricePointName + } + if o.CurrencyPrices != nil { + structMap["currency_prices"] = o.CurrencyPrices + } + if o.Interval != nil { + structMap["interval"] = o.Interval + } + if o.IntervalUnit != nil { + structMap["interval_unit"] = o.IntervalUnit + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for OfferItem. +// UnmarshalJSON implements the json.Unmarshaler interface for OfferItem. // It customizes the JSON unmarshaling process for OfferItem objects. func (o *OfferItem) UnmarshalJSON(input []byte) error { - temp := &struct { - ComponentId *int `json:"component_id,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - StartingQuantity *string `json:"starting_quantity,omitempty"` - Editable *bool `json:"editable,omitempty"` - ComponentUnitPrice *string `json:"component_unit_price,omitempty"` - ComponentName *string `json:"component_name,omitempty"` - PricePointName *string `json:"price_point_name,omitempty"` - CurrencyPrices []CurrencyPrice `json:"currency_prices,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - o.ComponentId = temp.ComponentId - o.PricePointId = temp.PricePointId - o.StartingQuantity = temp.StartingQuantity - o.Editable = temp.Editable - o.ComponentUnitPrice = temp.ComponentUnitPrice - o.ComponentName = temp.ComponentName - o.PricePointName = temp.PricePointName - o.CurrencyPrices = temp.CurrencyPrices - o.Interval = temp.Interval - o.IntervalUnit = temp.IntervalUnit - return nil + var temp offerItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + o.ComponentId = temp.ComponentId + o.PricePointId = temp.PricePointId + o.StartingQuantity = temp.StartingQuantity + o.Editable = temp.Editable + o.ComponentUnitPrice = temp.ComponentUnitPrice + o.ComponentName = temp.ComponentName + o.PricePointName = temp.PricePointName + o.CurrencyPrices = temp.CurrencyPrices + o.Interval = temp.Interval + o.IntervalUnit = temp.IntervalUnit + return nil +} + +// TODO +type offerItem struct { + ComponentId *int `json:"component_id,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + StartingQuantity *string `json:"starting_quantity,omitempty"` + Editable *bool `json:"editable,omitempty"` + ComponentUnitPrice *string `json:"component_unit_price,omitempty"` + ComponentName *string `json:"component_name,omitempty"` + PricePointName *string `json:"price_point_name,omitempty"` + CurrencyPrices []CurrencyPrice `json:"currency_prices,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` } diff --git a/models/offer_response.go b/models/offer_response.go index dc1949b3..46ffd1d1 100644 --- a/models/offer_response.go +++ b/models/offer_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // OfferResponse represents a OfferResponse struct. type OfferResponse struct { - Offer *Offer `json:"offer,omitempty"` + Offer *Offer `json:"offer,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for OfferResponse. +// MarshalJSON implements the json.Marshaler interface for OfferResponse. // It customizes the JSON marshaling process for OfferResponse objects. func (o *OfferResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(o.toMap()) + []byte, + error) { + return json.Marshal(o.toMap()) } // toMap converts the OfferResponse object to a map representation for JSON marshaling. func (o *OfferResponse) toMap() map[string]any { - structMap := make(map[string]any) - if o.Offer != nil { - structMap["offer"] = o.Offer.toMap() - } - return structMap + structMap := make(map[string]any) + if o.Offer != nil { + structMap["offer"] = o.Offer.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for OfferResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for OfferResponse. // It customizes the JSON unmarshaling process for OfferResponse objects. func (o *OfferResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Offer *Offer `json:"offer,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - o.Offer = temp.Offer - return nil + var temp offerResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + o.Offer = temp.Offer + return nil +} + +// TODO +type offerResponse struct { + Offer *Offer `json:"offer,omitempty"` } diff --git a/models/offer_signup_page.go b/models/offer_signup_page.go index 850ee541..d17b3072 100644 --- a/models/offer_signup_page.go +++ b/models/offer_signup_page.go @@ -1,72 +1,74 @@ package models import ( - "encoding/json" + "encoding/json" ) // OfferSignupPage represents a OfferSignupPage struct. type OfferSignupPage struct { - Id *int `json:"id,omitempty"` - Nickname *string `json:"nickname,omitempty"` - Enabled *bool `json:"enabled,omitempty"` - ReturnUrl *string `json:"return_url,omitempty"` - ReturnParams *string `json:"return_params,omitempty"` - Url *string `json:"url,omitempty"` + Id *int `json:"id,omitempty"` + Nickname *string `json:"nickname,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + ReturnUrl *string `json:"return_url,omitempty"` + ReturnParams *string `json:"return_params,omitempty"` + Url *string `json:"url,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for OfferSignupPage. +// MarshalJSON implements the json.Marshaler interface for OfferSignupPage. // It customizes the JSON marshaling process for OfferSignupPage objects. func (o *OfferSignupPage) MarshalJSON() ( - []byte, - error) { - return json.Marshal(o.toMap()) + []byte, + error) { + return json.Marshal(o.toMap()) } // toMap converts the OfferSignupPage object to a map representation for JSON marshaling. func (o *OfferSignupPage) toMap() map[string]any { - structMap := make(map[string]any) - if o.Id != nil { - structMap["id"] = o.Id - } - if o.Nickname != nil { - structMap["nickname"] = o.Nickname - } - if o.Enabled != nil { - structMap["enabled"] = o.Enabled - } - if o.ReturnUrl != nil { - structMap["return_url"] = o.ReturnUrl - } - if o.ReturnParams != nil { - structMap["return_params"] = o.ReturnParams - } - if o.Url != nil { - structMap["url"] = o.Url - } - return structMap + structMap := make(map[string]any) + if o.Id != nil { + structMap["id"] = o.Id + } + if o.Nickname != nil { + structMap["nickname"] = o.Nickname + } + if o.Enabled != nil { + structMap["enabled"] = o.Enabled + } + if o.ReturnUrl != nil { + structMap["return_url"] = o.ReturnUrl + } + if o.ReturnParams != nil { + structMap["return_params"] = o.ReturnParams + } + if o.Url != nil { + structMap["url"] = o.Url + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for OfferSignupPage. +// UnmarshalJSON implements the json.Unmarshaler interface for OfferSignupPage. // It customizes the JSON unmarshaling process for OfferSignupPage objects. func (o *OfferSignupPage) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Nickname *string `json:"nickname,omitempty"` - Enabled *bool `json:"enabled,omitempty"` - ReturnUrl *string `json:"return_url,omitempty"` - ReturnParams *string `json:"return_params,omitempty"` - Url *string `json:"url,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - o.Id = temp.Id - o.Nickname = temp.Nickname - o.Enabled = temp.Enabled - o.ReturnUrl = temp.ReturnUrl - o.ReturnParams = temp.ReturnParams - o.Url = temp.Url - return nil + var temp offerSignupPage + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + o.Id = temp.Id + o.Nickname = temp.Nickname + o.Enabled = temp.Enabled + o.ReturnUrl = temp.ReturnUrl + o.ReturnParams = temp.ReturnParams + o.Url = temp.Url + return nil +} + +// TODO +type offerSignupPage struct { + Id *int `json:"id,omitempty"` + Nickname *string `json:"nickname,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + ReturnUrl *string `json:"return_url,omitempty"` + ReturnParams *string `json:"return_params,omitempty"` + Url *string `json:"url,omitempty"` } diff --git a/models/on_off_component.go b/models/on_off_component.go index eef1977e..7c335fb6 100644 --- a/models/on_off_component.go +++ b/models/on_off_component.go @@ -1,151 +1,179 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // OnOffComponent represents a OnOffComponent struct. type OnOffComponent struct { - // A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". - Name string `json:"name"` - // A description for the component that will be displayed to the user on the hosted signup page. - Description *string `json:"description,omitempty"` - // A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'. - Handle *string `json:"handle,omitempty"` - // Boolean flag describing whether a component is taxable or not. - Taxable *bool `json:"taxable,omitempty"` - // (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. - Prices []Price `json:"prices,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` - // The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 - UnitPrice *interface{} `json:"unit_price,omitempty"` - // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. - TaxCode *string `json:"tax_code,omitempty"` - // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - // deprecated May 2011 - use unit_price instead - PriceInCents *string `json:"price_in_cents,omitempty"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + // A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". + Name string `json:"name"` + // A description for the component that will be displayed to the user on the hosted signup page. + Description *string `json:"description,omitempty"` + // A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'. + Handle *string `json:"handle,omitempty"` + // Boolean flag describing whether a component is taxable or not. + Taxable *bool `json:"taxable,omitempty"` + // (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. + Prices []Price `json:"prices,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` + // The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 + UnitPrice *OnOffComponentUnitPrice `json:"unit_price,omitempty"` + // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. + TaxCode *string `json:"tax_code,omitempty"` + // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + // deprecated May 2011 - use unit_price instead + PriceInCents *string `json:"price_in_cents,omitempty"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for OnOffComponent. +// MarshalJSON implements the json.Marshaler interface for OnOffComponent. // It customizes the JSON marshaling process for OnOffComponent objects. func (o *OnOffComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(o.toMap()) + []byte, + error) { + return json.Marshal(o.toMap()) } // toMap converts the OnOffComponent object to a map representation for JSON marshaling. func (o *OnOffComponent) toMap() map[string]any { - structMap := make(map[string]any) - structMap["name"] = o.Name - if o.Description != nil { - structMap["description"] = o.Description - } - if o.Handle != nil { - structMap["handle"] = o.Handle - } - if o.Taxable != nil { - structMap["taxable"] = o.Taxable - } - if o.Prices != nil { - structMap["prices"] = o.Prices - } - if o.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = o.UpgradeCharge.Value() - } - if o.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = o.DowngradeCredit.Value() - } - if o.PricePoints != nil { - structMap["price_points"] = o.PricePoints - } - if o.UnitPrice != nil { - structMap["unit_price"] = o.UnitPrice - } - if o.TaxCode != nil { - structMap["tax_code"] = o.TaxCode - } - if o.HideDateRangeOnInvoice != nil { - structMap["hide_date_range_on_invoice"] = o.HideDateRangeOnInvoice - } - if o.PriceInCents != nil { - structMap["price_in_cents"] = o.PriceInCents - } - if o.DisplayOnHostedPage != nil { - structMap["display_on_hosted_page"] = o.DisplayOnHostedPage - } - if o.AllowFractionalQuantities != nil { - structMap["allow_fractional_quantities"] = o.AllowFractionalQuantities - } - if o.PublicSignupPageIds != nil { - structMap["public_signup_page_ids"] = o.PublicSignupPageIds - } - if o.Interval != nil { - structMap["interval"] = o.Interval - } - if o.IntervalUnit != nil { - structMap["interval_unit"] = o.IntervalUnit - } - return structMap + structMap := make(map[string]any) + structMap["name"] = o.Name + if o.Description != nil { + structMap["description"] = o.Description + } + if o.Handle != nil { + structMap["handle"] = o.Handle + } + if o.Taxable != nil { + structMap["taxable"] = o.Taxable + } + if o.Prices != nil { + structMap["prices"] = o.Prices + } + if o.UpgradeCharge.IsValueSet() { + if o.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = o.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if o.DowngradeCredit.IsValueSet() { + if o.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = o.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if o.PricePoints != nil { + structMap["price_points"] = o.PricePoints + } + if o.UnitPrice != nil { + structMap["unit_price"] = o.UnitPrice.toMap() + } + if o.TaxCode != nil { + structMap["tax_code"] = o.TaxCode + } + if o.HideDateRangeOnInvoice != nil { + structMap["hide_date_range_on_invoice"] = o.HideDateRangeOnInvoice + } + if o.PriceInCents != nil { + structMap["price_in_cents"] = o.PriceInCents + } + if o.DisplayOnHostedPage != nil { + structMap["display_on_hosted_page"] = o.DisplayOnHostedPage + } + if o.AllowFractionalQuantities != nil { + structMap["allow_fractional_quantities"] = o.AllowFractionalQuantities + } + if o.PublicSignupPageIds != nil { + structMap["public_signup_page_ids"] = o.PublicSignupPageIds + } + if o.Interval != nil { + structMap["interval"] = o.Interval + } + if o.IntervalUnit != nil { + structMap["interval_unit"] = o.IntervalUnit + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for OnOffComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for OnOffComponent. // It customizes the JSON unmarshaling process for OnOffComponent objects. func (o *OnOffComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - Name string `json:"name"` - Description *string `json:"description,omitempty"` - Handle *string `json:"handle,omitempty"` - Taxable *bool `json:"taxable,omitempty"` - Prices []Price `json:"prices,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` - UnitPrice *interface{} `json:"unit_price,omitempty"` - TaxCode *string `json:"tax_code,omitempty"` - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - PriceInCents *string `json:"price_in_cents,omitempty"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - o.Name = temp.Name - o.Description = temp.Description - o.Handle = temp.Handle - o.Taxable = temp.Taxable - o.Prices = temp.Prices - o.UpgradeCharge = temp.UpgradeCharge - o.DowngradeCredit = temp.DowngradeCredit - o.PricePoints = temp.PricePoints - o.UnitPrice = temp.UnitPrice - o.TaxCode = temp.TaxCode - o.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice - o.PriceInCents = temp.PriceInCents - o.DisplayOnHostedPage = temp.DisplayOnHostedPage - o.AllowFractionalQuantities = temp.AllowFractionalQuantities - o.PublicSignupPageIds = temp.PublicSignupPageIds - o.Interval = temp.Interval - o.IntervalUnit = temp.IntervalUnit - return nil + var temp onOffComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + o.Name = *temp.Name + o.Description = temp.Description + o.Handle = temp.Handle + o.Taxable = temp.Taxable + o.Prices = temp.Prices + o.UpgradeCharge = temp.UpgradeCharge + o.DowngradeCredit = temp.DowngradeCredit + o.PricePoints = temp.PricePoints + o.UnitPrice = temp.UnitPrice + o.TaxCode = temp.TaxCode + o.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice + o.PriceInCents = temp.PriceInCents + o.DisplayOnHostedPage = temp.DisplayOnHostedPage + o.AllowFractionalQuantities = temp.AllowFractionalQuantities + o.PublicSignupPageIds = temp.PublicSignupPageIds + o.Interval = temp.Interval + o.IntervalUnit = temp.IntervalUnit + return nil +} + +// TODO +type onOffComponent struct { + Name *string `json:"name"` + Description *string `json:"description,omitempty"` + Handle *string `json:"handle,omitempty"` + Taxable *bool `json:"taxable,omitempty"` + Prices []Price `json:"prices,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` + UnitPrice *OnOffComponentUnitPrice `json:"unit_price,omitempty"` + TaxCode *string `json:"tax_code,omitempty"` + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + PriceInCents *string `json:"price_in_cents,omitempty"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` +} + +func (o *onOffComponent) validate() error { + var errs []string + if o.Name == nil { + errs = append(errs, "required field `name` is missing for type `On/Off Component`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/on_off_component_unit_price.go b/models/on_off_component_unit_price.go new file mode 100644 index 00000000..11d2698b --- /dev/null +++ b/models/on_off_component_unit_price.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// OnOffComponentUnitPrice represents a OnOffComponentUnitPrice struct. +// This is a container for one-of cases. +type OnOffComponentUnitPrice struct { + value any + isString bool + isPrecision bool +} + +// String converts the OnOffComponentUnitPrice object to a string representation. +func (o OnOffComponentUnitPrice) String() string { + if bytes, err := json.Marshal(o.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for OnOffComponentUnitPrice. +// It customizes the JSON marshaling process for OnOffComponentUnitPrice objects. +func (o *OnOffComponentUnitPrice) MarshalJSON() ( + []byte, + error) { + if o.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.OnOffComponentUnitPriceContainer.From*` functions to initialize the OnOffComponentUnitPrice object.") + } + return json.Marshal(o.toMap()) +} + +// toMap converts the OnOffComponentUnitPrice object to a map representation for JSON marshaling. +func (o *OnOffComponentUnitPrice) toMap() any { + switch obj := o.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for OnOffComponentUnitPrice. +// It customizes the JSON unmarshaling process for OnOffComponentUnitPrice objects. +func (o *OnOffComponentUnitPrice) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &o.isString), + NewTypeHolder(new(float64), false, &o.isPrecision), + ) + + o.value = result + return err +} + +func (o *OnOffComponentUnitPrice) AsString() ( + *string, + bool) { + if !o.isString { + return nil, false + } + return o.value.(*string), true +} + +func (o *OnOffComponentUnitPrice) AsPrecision() ( + *float64, + bool) { + if !o.isPrecision { + return nil, false + } + return o.value.(*float64), true +} + +// internalOnOffComponentUnitPrice represents a onOffComponentUnitPrice struct. +// This is a container for one-of cases. +type internalOnOffComponentUnitPrice struct{} + +var OnOffComponentUnitPriceContainer internalOnOffComponentUnitPrice + +func (o *internalOnOffComponentUnitPrice) FromString(val string) OnOffComponentUnitPrice { + return OnOffComponentUnitPrice{value: &val} +} + +func (o *internalOnOffComponentUnitPrice) FromPrecision(val float64) OnOffComponentUnitPrice { + return OnOffComponentUnitPrice{value: &val} +} diff --git a/models/organization_address.go b/models/organization_address.go index ecc68f66..701ef5d6 100644 --- a/models/organization_address.go +++ b/models/organization_address.go @@ -1,84 +1,118 @@ package models import ( - "encoding/json" + "encoding/json" ) // OrganizationAddress represents a OrganizationAddress struct. type OrganizationAddress struct { - Street Optional[string] `json:"street"` - Line2 Optional[string] `json:"line2"` - City Optional[string] `json:"city"` - State Optional[string] `json:"state"` - Zip Optional[string] `json:"zip"` - Country Optional[string] `json:"country"` - Name Optional[string] `json:"name"` - Phone Optional[string] `json:"phone"` + Street Optional[string] `json:"street"` + Line2 Optional[string] `json:"line2"` + City Optional[string] `json:"city"` + State Optional[string] `json:"state"` + Zip Optional[string] `json:"zip"` + Country Optional[string] `json:"country"` + Name Optional[string] `json:"name"` + Phone Optional[string] `json:"phone"` } -// MarshalJSON implements the json.Marshaler interface for OrganizationAddress. +// MarshalJSON implements the json.Marshaler interface for OrganizationAddress. // It customizes the JSON marshaling process for OrganizationAddress objects. func (o *OrganizationAddress) MarshalJSON() ( - []byte, - error) { - return json.Marshal(o.toMap()) + []byte, + error) { + return json.Marshal(o.toMap()) } // toMap converts the OrganizationAddress object to a map representation for JSON marshaling. func (o *OrganizationAddress) toMap() map[string]any { - structMap := make(map[string]any) - if o.Street.IsValueSet() { - structMap["street"] = o.Street.Value() - } - if o.Line2.IsValueSet() { - structMap["line2"] = o.Line2.Value() - } - if o.City.IsValueSet() { - structMap["city"] = o.City.Value() - } - if o.State.IsValueSet() { - structMap["state"] = o.State.Value() - } - if o.Zip.IsValueSet() { - structMap["zip"] = o.Zip.Value() - } - if o.Country.IsValueSet() { - structMap["country"] = o.Country.Value() - } - if o.Name.IsValueSet() { - structMap["name"] = o.Name.Value() - } - if o.Phone.IsValueSet() { - structMap["phone"] = o.Phone.Value() - } - return structMap + structMap := make(map[string]any) + if o.Street.IsValueSet() { + if o.Street.Value() != nil { + structMap["street"] = o.Street.Value() + } else { + structMap["street"] = nil + } + } + if o.Line2.IsValueSet() { + if o.Line2.Value() != nil { + structMap["line2"] = o.Line2.Value() + } else { + structMap["line2"] = nil + } + } + if o.City.IsValueSet() { + if o.City.Value() != nil { + structMap["city"] = o.City.Value() + } else { + structMap["city"] = nil + } + } + if o.State.IsValueSet() { + if o.State.Value() != nil { + structMap["state"] = o.State.Value() + } else { + structMap["state"] = nil + } + } + if o.Zip.IsValueSet() { + if o.Zip.Value() != nil { + structMap["zip"] = o.Zip.Value() + } else { + structMap["zip"] = nil + } + } + if o.Country.IsValueSet() { + if o.Country.Value() != nil { + structMap["country"] = o.Country.Value() + } else { + structMap["country"] = nil + } + } + if o.Name.IsValueSet() { + if o.Name.Value() != nil { + structMap["name"] = o.Name.Value() + } else { + structMap["name"] = nil + } + } + if o.Phone.IsValueSet() { + if o.Phone.Value() != nil { + structMap["phone"] = o.Phone.Value() + } else { + structMap["phone"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for OrganizationAddress. +// UnmarshalJSON implements the json.Unmarshaler interface for OrganizationAddress. // It customizes the JSON unmarshaling process for OrganizationAddress objects. func (o *OrganizationAddress) UnmarshalJSON(input []byte) error { - temp := &struct { - Street Optional[string] `json:"street"` - Line2 Optional[string] `json:"line2"` - City Optional[string] `json:"city"` - State Optional[string] `json:"state"` - Zip Optional[string] `json:"zip"` - Country Optional[string] `json:"country"` - Name Optional[string] `json:"name"` - Phone Optional[string] `json:"phone"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - o.Street = temp.Street - o.Line2 = temp.Line2 - o.City = temp.City - o.State = temp.State - o.Zip = temp.Zip - o.Country = temp.Country - o.Name = temp.Name - o.Phone = temp.Phone - return nil + var temp organizationAddress + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + o.Street = temp.Street + o.Line2 = temp.Line2 + o.City = temp.City + o.State = temp.State + o.Zip = temp.Zip + o.Country = temp.Country + o.Name = temp.Name + o.Phone = temp.Phone + return nil +} + +// TODO +type organizationAddress struct { + Street Optional[string] `json:"street"` + Line2 Optional[string] `json:"line2"` + City Optional[string] `json:"city"` + State Optional[string] `json:"state"` + Zip Optional[string] `json:"zip"` + Country Optional[string] `json:"country"` + Name Optional[string] `json:"name"` + Phone Optional[string] `json:"phone"` } diff --git a/models/origin_invoice.go b/models/origin_invoice.go index 6a3346e3..6be40497 100644 --- a/models/origin_invoice.go +++ b/models/origin_invoice.go @@ -1,50 +1,52 @@ package models import ( - "encoding/json" + "encoding/json" ) // OriginInvoice represents a OriginInvoice struct. type OriginInvoice struct { - // The UID of the invoice serving as an origin invoice. - Uid *string `json:"uid,omitempty"` - // The number of the invoice serving as an origin invoice. - Number *string `json:"number,omitempty"` + // The UID of the invoice serving as an origin invoice. + Uid *string `json:"uid,omitempty"` + // The number of the invoice serving as an origin invoice. + Number *string `json:"number,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for OriginInvoice. +// MarshalJSON implements the json.Marshaler interface for OriginInvoice. // It customizes the JSON marshaling process for OriginInvoice objects. func (o *OriginInvoice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(o.toMap()) + []byte, + error) { + return json.Marshal(o.toMap()) } // toMap converts the OriginInvoice object to a map representation for JSON marshaling. func (o *OriginInvoice) toMap() map[string]any { - structMap := make(map[string]any) - if o.Uid != nil { - structMap["uid"] = o.Uid - } - if o.Number != nil { - structMap["number"] = o.Number - } - return structMap + structMap := make(map[string]any) + if o.Uid != nil { + structMap["uid"] = o.Uid + } + if o.Number != nil { + structMap["number"] = o.Number + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for OriginInvoice. +// UnmarshalJSON implements the json.Unmarshaler interface for OriginInvoice. // It customizes the JSON unmarshaling process for OriginInvoice objects. func (o *OriginInvoice) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Number *string `json:"number,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - o.Uid = temp.Uid - o.Number = temp.Number - return nil + var temp originInvoice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + o.Uid = temp.Uid + o.Number = temp.Number + return nil +} + +// TODO +type originInvoice struct { + Uid *string `json:"uid,omitempty"` + Number *string `json:"number,omitempty"` } diff --git a/models/overage_pricing.go b/models/overage_pricing.go index 3b5c8032..7ec05575 100644 --- a/models/overage_pricing.go +++ b/models/overage_pricing.go @@ -1,47 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // OveragePricing represents a OveragePricing struct. type OveragePricing struct { - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme PricingScheme `json:"pricing_scheme"` - Prices []Price `json:"prices,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme PricingScheme `json:"pricing_scheme"` + Prices []Price `json:"prices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for OveragePricing. +// MarshalJSON implements the json.Marshaler interface for OveragePricing. // It customizes the JSON marshaling process for OveragePricing objects. func (o *OveragePricing) MarshalJSON() ( - []byte, - error) { - return json.Marshal(o.toMap()) + []byte, + error) { + return json.Marshal(o.toMap()) } // toMap converts the OveragePricing object to a map representation for JSON marshaling. func (o *OveragePricing) toMap() map[string]any { - structMap := make(map[string]any) - structMap["pricing_scheme"] = o.PricingScheme - if o.Prices != nil { - structMap["prices"] = o.Prices - } - return structMap + structMap := make(map[string]any) + structMap["pricing_scheme"] = o.PricingScheme + if o.Prices != nil { + structMap["prices"] = o.Prices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for OveragePricing. +// UnmarshalJSON implements the json.Unmarshaler interface for OveragePricing. // It customizes the JSON unmarshaling process for OveragePricing objects. func (o *OveragePricing) UnmarshalJSON(input []byte) error { - temp := &struct { - PricingScheme PricingScheme `json:"pricing_scheme"` - Prices []Price `json:"prices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - o.PricingScheme = temp.PricingScheme - o.Prices = temp.Prices - return nil + var temp overagePricing + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + o.PricingScheme = *temp.PricingScheme + o.Prices = temp.Prices + return nil +} + +// TODO +type overagePricing struct { + PricingScheme *PricingScheme `json:"pricing_scheme"` + Prices []Price `json:"prices,omitempty"` +} + +func (o *overagePricing) validate() error { + var errs []string + if o.PricingScheme == nil { + errs = append(errs, "required field `pricing_scheme` is missing for type `Overage Pricing`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/override_subscription.go b/models/override_subscription.go index 23861d0c..73e76b44 100644 --- a/models/override_subscription.go +++ b/models/override_subscription.go @@ -1,97 +1,99 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // OverrideSubscription represents a OverrideSubscription struct. type OverrideSubscription struct { - // Can be used to record an external signup date. Chargify uses this field to record when a subscription first goes active (either at signup or at trial end). Only ISO8601 format is supported. - ActivatedAt *time.Time `json:"activated_at,omitempty"` - // Can be used to record an external cancellation date. Chargify sets this field automatically when a subscription is canceled, whether by request or via dunning. Only ISO8601 format is supported. - CanceledAt *time.Time `json:"canceled_at,omitempty"` - // Can be used to record a reason for the original cancellation. - CancellationMessage *string `json:"cancellation_message,omitempty"` - // Can be used to record an external expiration date. Chargify sets this field automatically when a subscription expires (ceases billing) after a prescribed amount of time. Only ISO8601 format is supported. - ExpiresAt *time.Time `json:"expires_at,omitempty"` - // Can only be used when a subscription is unbilled, which happens when a future initial billing date is passed at subscription creation. The value passed must be before the current date and time. Allows you to set when the period started so mid period component allocations have the correct proration. Only ISO8601 format is supported. - CurrentPeriodStartsAt *time.Time `json:"current_period_starts_at,omitempty"` + // Can be used to record an external signup date. Chargify uses this field to record when a subscription first goes active (either at signup or at trial end). Only ISO8601 format is supported. + ActivatedAt *time.Time `json:"activated_at,omitempty"` + // Can be used to record an external cancellation date. Chargify sets this field automatically when a subscription is canceled, whether by request or via dunning. Only ISO8601 format is supported. + CanceledAt *time.Time `json:"canceled_at,omitempty"` + // Can be used to record a reason for the original cancellation. + CancellationMessage *string `json:"cancellation_message,omitempty"` + // Can be used to record an external expiration date. Chargify sets this field automatically when a subscription expires (ceases billing) after a prescribed amount of time. Only ISO8601 format is supported. + ExpiresAt *time.Time `json:"expires_at,omitempty"` + // Can only be used when a subscription is unbilled, which happens when a future initial billing date is passed at subscription creation. The value passed must be before the current date and time. Allows you to set when the period started so mid period component allocations have the correct proration. Only ISO8601 format is supported. + CurrentPeriodStartsAt *time.Time `json:"current_period_starts_at,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for OverrideSubscription. +// MarshalJSON implements the json.Marshaler interface for OverrideSubscription. // It customizes the JSON marshaling process for OverrideSubscription objects. func (o *OverrideSubscription) MarshalJSON() ( - []byte, - error) { - return json.Marshal(o.toMap()) + []byte, + error) { + return json.Marshal(o.toMap()) } // toMap converts the OverrideSubscription object to a map representation for JSON marshaling. func (o *OverrideSubscription) toMap() map[string]any { - structMap := make(map[string]any) - if o.ActivatedAt != nil { - structMap["activated_at"] = o.ActivatedAt.Format(time.RFC3339) - } - if o.CanceledAt != nil { - structMap["canceled_at"] = o.CanceledAt.Format(time.RFC3339) - } - if o.CancellationMessage != nil { - structMap["cancellation_message"] = o.CancellationMessage - } - if o.ExpiresAt != nil { - structMap["expires_at"] = o.ExpiresAt.Format(time.RFC3339) - } - if o.CurrentPeriodStartsAt != nil { - structMap["current_period_starts_at"] = o.CurrentPeriodStartsAt.Format(time.RFC3339) - } - return structMap + structMap := make(map[string]any) + if o.ActivatedAt != nil { + structMap["activated_at"] = o.ActivatedAt.Format(time.RFC3339) + } + if o.CanceledAt != nil { + structMap["canceled_at"] = o.CanceledAt.Format(time.RFC3339) + } + if o.CancellationMessage != nil { + structMap["cancellation_message"] = o.CancellationMessage + } + if o.ExpiresAt != nil { + structMap["expires_at"] = o.ExpiresAt.Format(time.RFC3339) + } + if o.CurrentPeriodStartsAt != nil { + structMap["current_period_starts_at"] = o.CurrentPeriodStartsAt.Format(time.RFC3339) + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for OverrideSubscription. +// UnmarshalJSON implements the json.Unmarshaler interface for OverrideSubscription. // It customizes the JSON unmarshaling process for OverrideSubscription objects. func (o *OverrideSubscription) UnmarshalJSON(input []byte) error { - temp := &struct { - ActivatedAt *string `json:"activated_at,omitempty"` - CanceledAt *string `json:"canceled_at,omitempty"` - CancellationMessage *string `json:"cancellation_message,omitempty"` - ExpiresAt *string `json:"expires_at,omitempty"` - CurrentPeriodStartsAt *string `json:"current_period_starts_at,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - if temp.ActivatedAt != nil { - ActivatedAtVal, err := time.Parse(time.RFC3339, *temp.ActivatedAt) - if err != nil { - log.Fatalf("Cannot Parse activated_at as % s format.", time.RFC3339) - } - o.ActivatedAt = &ActivatedAtVal - } - if temp.CanceledAt != nil { - CanceledAtVal, err := time.Parse(time.RFC3339, *temp.CanceledAt) - if err != nil { - log.Fatalf("Cannot Parse canceled_at as % s format.", time.RFC3339) - } - o.CanceledAt = &CanceledAtVal - } - o.CancellationMessage = temp.CancellationMessage - if temp.ExpiresAt != nil { - ExpiresAtVal, err := time.Parse(time.RFC3339, *temp.ExpiresAt) - if err != nil { - log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) - } - o.ExpiresAt = &ExpiresAtVal - } - if temp.CurrentPeriodStartsAt != nil { - CurrentPeriodStartsAtVal, err := time.Parse(time.RFC3339, *temp.CurrentPeriodStartsAt) - if err != nil { - log.Fatalf("Cannot Parse current_period_starts_at as % s format.", time.RFC3339) - } - o.CurrentPeriodStartsAt = &CurrentPeriodStartsAtVal - } - return nil + var temp overrideSubscription + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + if temp.ActivatedAt != nil { + ActivatedAtVal, err := time.Parse(time.RFC3339, *temp.ActivatedAt) + if err != nil { + log.Fatalf("Cannot Parse activated_at as % s format.", time.RFC3339) + } + o.ActivatedAt = &ActivatedAtVal + } + if temp.CanceledAt != nil { + CanceledAtVal, err := time.Parse(time.RFC3339, *temp.CanceledAt) + if err != nil { + log.Fatalf("Cannot Parse canceled_at as % s format.", time.RFC3339) + } + o.CanceledAt = &CanceledAtVal + } + o.CancellationMessage = temp.CancellationMessage + if temp.ExpiresAt != nil { + ExpiresAtVal, err := time.Parse(time.RFC3339, *temp.ExpiresAt) + if err != nil { + log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) + } + o.ExpiresAt = &ExpiresAtVal + } + if temp.CurrentPeriodStartsAt != nil { + CurrentPeriodStartsAtVal, err := time.Parse(time.RFC3339, *temp.CurrentPeriodStartsAt) + if err != nil { + log.Fatalf("Cannot Parse current_period_starts_at as % s format.", time.RFC3339) + } + o.CurrentPeriodStartsAt = &CurrentPeriodStartsAtVal + } + return nil +} + +// TODO +type overrideSubscription struct { + ActivatedAt *string `json:"activated_at,omitempty"` + CanceledAt *string `json:"canceled_at,omitempty"` + CancellationMessage *string `json:"cancellation_message,omitempty"` + ExpiresAt *string `json:"expires_at,omitempty"` + CurrentPeriodStartsAt *string `json:"current_period_starts_at,omitempty"` } diff --git a/models/override_subscription_request.go b/models/override_subscription_request.go index f38bf34b..79271cda 100644 --- a/models/override_subscription_request.go +++ b/models/override_subscription_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // OverrideSubscriptionRequest represents a OverrideSubscriptionRequest struct. type OverrideSubscriptionRequest struct { - Subscription OverrideSubscription `json:"subscription"` + Subscription OverrideSubscription `json:"subscription"` } -// MarshalJSON implements the json.Marshaler interface for OverrideSubscriptionRequest. +// MarshalJSON implements the json.Marshaler interface for OverrideSubscriptionRequest. // It customizes the JSON marshaling process for OverrideSubscriptionRequest objects. func (o *OverrideSubscriptionRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(o.toMap()) + []byte, + error) { + return json.Marshal(o.toMap()) } // toMap converts the OverrideSubscriptionRequest object to a map representation for JSON marshaling. func (o *OverrideSubscriptionRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscription"] = o.Subscription.toMap() - return structMap + structMap := make(map[string]any) + structMap["subscription"] = o.Subscription.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for OverrideSubscriptionRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for OverrideSubscriptionRequest. // It customizes the JSON unmarshaling process for OverrideSubscriptionRequest objects. func (o *OverrideSubscriptionRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Subscription OverrideSubscription `json:"subscription"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - o.Subscription = temp.Subscription - return nil + var temp overrideSubscriptionRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + o.Subscription = *temp.Subscription + return nil +} + +// TODO +type overrideSubscriptionRequest struct { + Subscription *OverrideSubscription `json:"subscription"` +} + +func (o *overrideSubscriptionRequest) validate() error { + var errs []string + if o.Subscription == nil { + errs = append(errs, "required field `subscription` is missing for type `Override Subscription Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/paginated_metadata.go b/models/paginated_metadata.go index c61969d3..5818854c 100644 --- a/models/paginated_metadata.go +++ b/models/paginated_metadata.go @@ -1,66 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" ) // PaginatedMetadata represents a PaginatedMetadata struct. type PaginatedMetadata struct { - TotalCount *int `json:"total_count,omitempty"` - CurrentPage *int `json:"current_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` - PerPage *int `json:"per_page,omitempty"` - Metadata []Metadata `json:"metadata,omitempty"` + TotalCount *int `json:"total_count,omitempty"` + CurrentPage *int `json:"current_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` + PerPage *int `json:"per_page,omitempty"` + Metadata []Metadata `json:"metadata,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PaginatedMetadata. +// MarshalJSON implements the json.Marshaler interface for PaginatedMetadata. // It customizes the JSON marshaling process for PaginatedMetadata objects. func (p *PaginatedMetadata) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PaginatedMetadata object to a map representation for JSON marshaling. func (p *PaginatedMetadata) toMap() map[string]any { - structMap := make(map[string]any) - if p.TotalCount != nil { - structMap["total_count"] = p.TotalCount - } - if p.CurrentPage != nil { - structMap["current_page"] = p.CurrentPage - } - if p.TotalPages != nil { - structMap["total_pages"] = p.TotalPages - } - if p.PerPage != nil { - structMap["per_page"] = p.PerPage - } - if p.Metadata != nil { - structMap["metadata"] = p.Metadata - } - return structMap + structMap := make(map[string]any) + if p.TotalCount != nil { + structMap["total_count"] = p.TotalCount + } + if p.CurrentPage != nil { + structMap["current_page"] = p.CurrentPage + } + if p.TotalPages != nil { + structMap["total_pages"] = p.TotalPages + } + if p.PerPage != nil { + structMap["per_page"] = p.PerPage + } + if p.Metadata != nil { + structMap["metadata"] = p.Metadata + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PaginatedMetadata. +// UnmarshalJSON implements the json.Unmarshaler interface for PaginatedMetadata. // It customizes the JSON unmarshaling process for PaginatedMetadata objects. func (p *PaginatedMetadata) UnmarshalJSON(input []byte) error { - temp := &struct { - TotalCount *int `json:"total_count,omitempty"` - CurrentPage *int `json:"current_page,omitempty"` - TotalPages *int `json:"total_pages,omitempty"` - PerPage *int `json:"per_page,omitempty"` - Metadata []Metadata `json:"metadata,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.TotalCount = temp.TotalCount - p.CurrentPage = temp.CurrentPage - p.TotalPages = temp.TotalPages - p.PerPage = temp.PerPage - p.Metadata = temp.Metadata - return nil + var temp paginatedMetadata + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.TotalCount = temp.TotalCount + p.CurrentPage = temp.CurrentPage + p.TotalPages = temp.TotalPages + p.PerPage = temp.PerPage + p.Metadata = temp.Metadata + return nil +} + +// TODO +type paginatedMetadata struct { + TotalCount *int `json:"total_count,omitempty"` + CurrentPage *int `json:"current_page,omitempty"` + TotalPages *int `json:"total_pages,omitempty"` + PerPage *int `json:"per_page,omitempty"` + Metadata []Metadata `json:"metadata,omitempty"` } diff --git a/models/paid_invoice.go b/models/paid_invoice.go index 0c92d3d3..d526ada3 100644 --- a/models/paid_invoice.go +++ b/models/paid_invoice.go @@ -1,64 +1,66 @@ package models import ( - "encoding/json" + "encoding/json" ) // PaidInvoice represents a PaidInvoice struct. type PaidInvoice struct { - // The uid of the paid invoice - InvoiceId *string `json:"invoice_id,omitempty"` - // The current status of the invoice. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. - Status *InvoiceStatus `json:"status,omitempty"` - // The remaining due amount on the invoice - DueAmount *string `json:"due_amount,omitempty"` - // The total amount paid on this invoice (including any prior payments) - PaidAmount *string `json:"paid_amount,omitempty"` + // The uid of the paid invoice + InvoiceId *string `json:"invoice_id,omitempty"` + // The current status of the invoice. See [Invoice Statuses](https://chargify.zendesk.com/hc/en-us/articles/4407737494171#line-item-breakdowns) for more. + Status *InvoiceStatus `json:"status,omitempty"` + // The remaining due amount on the invoice + DueAmount *string `json:"due_amount,omitempty"` + // The total amount paid on this invoice (including any prior payments) + PaidAmount *string `json:"paid_amount,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PaidInvoice. +// MarshalJSON implements the json.Marshaler interface for PaidInvoice. // It customizes the JSON marshaling process for PaidInvoice objects. func (p *PaidInvoice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PaidInvoice object to a map representation for JSON marshaling. func (p *PaidInvoice) toMap() map[string]any { - structMap := make(map[string]any) - if p.InvoiceId != nil { - structMap["invoice_id"] = p.InvoiceId - } - if p.Status != nil { - structMap["status"] = p.Status - } - if p.DueAmount != nil { - structMap["due_amount"] = p.DueAmount - } - if p.PaidAmount != nil { - structMap["paid_amount"] = p.PaidAmount - } - return structMap + structMap := make(map[string]any) + if p.InvoiceId != nil { + structMap["invoice_id"] = p.InvoiceId + } + if p.Status != nil { + structMap["status"] = p.Status + } + if p.DueAmount != nil { + structMap["due_amount"] = p.DueAmount + } + if p.PaidAmount != nil { + structMap["paid_amount"] = p.PaidAmount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PaidInvoice. +// UnmarshalJSON implements the json.Unmarshaler interface for PaidInvoice. // It customizes the JSON unmarshaling process for PaidInvoice objects. func (p *PaidInvoice) UnmarshalJSON(input []byte) error { - temp := &struct { - InvoiceId *string `json:"invoice_id,omitempty"` - Status *InvoiceStatus `json:"status,omitempty"` - DueAmount *string `json:"due_amount,omitempty"` - PaidAmount *string `json:"paid_amount,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.InvoiceId = temp.InvoiceId - p.Status = temp.Status - p.DueAmount = temp.DueAmount - p.PaidAmount = temp.PaidAmount - return nil + var temp paidInvoice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.InvoiceId = temp.InvoiceId + p.Status = temp.Status + p.DueAmount = temp.DueAmount + p.PaidAmount = temp.PaidAmount + return nil +} + +// TODO +type paidInvoice struct { + InvoiceId *string `json:"invoice_id,omitempty"` + Status *InvoiceStatus `json:"status,omitempty"` + DueAmount *string `json:"due_amount,omitempty"` + PaidAmount *string `json:"paid_amount,omitempty"` } diff --git a/models/pause_request.go b/models/pause_request.go index 883aa1e4..6fa21ea1 100644 --- a/models/pause_request.go +++ b/models/pause_request.go @@ -1,43 +1,45 @@ package models import ( - "encoding/json" + "encoding/json" ) -// PauseRequest represents a PauseRequest struct. +// PauseRequest represents a PauseRequest struct. // Allows to pause a Subscription type PauseRequest struct { - Hold *AutoResume `json:"hold,omitempty"` + Hold *AutoResume `json:"hold,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PauseRequest. +// MarshalJSON implements the json.Marshaler interface for PauseRequest. // It customizes the JSON marshaling process for PauseRequest objects. func (p *PauseRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PauseRequest object to a map representation for JSON marshaling. func (p *PauseRequest) toMap() map[string]any { - structMap := make(map[string]any) - if p.Hold != nil { - structMap["hold"] = p.Hold.toMap() - } - return structMap + structMap := make(map[string]any) + if p.Hold != nil { + structMap["hold"] = p.Hold.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PauseRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for PauseRequest. // It customizes the JSON unmarshaling process for PauseRequest objects. func (p *PauseRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Hold *AutoResume `json:"hold,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Hold = temp.Hold - return nil + var temp pauseRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Hold = temp.Hold + return nil +} + +// TODO +type pauseRequest struct { + Hold *AutoResume `json:"hold,omitempty"` } diff --git a/models/payer_attributes.go b/models/payer_attributes.go index 4a2830cb..0447544f 100644 --- a/models/payer_attributes.go +++ b/models/payer_attributes.go @@ -1,145 +1,147 @@ package models import ( - "encoding/json" + "encoding/json" ) // PayerAttributes represents a PayerAttributes struct. type PayerAttributes struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Email *string `json:"email,omitempty"` - CcEmails *string `json:"cc_emails,omitempty"` - Organization *string `json:"organization,omitempty"` - Reference *string `json:"reference,omitempty"` - Address *string `json:"address,omitempty"` - Address2 *string `json:"address_2,omitempty"` - City *string `json:"city,omitempty"` - State *string `json:"state,omitempty"` - Zip *string `json:"zip,omitempty"` - Country *string `json:"country,omitempty"` - Phone *string `json:"phone,omitempty"` - Locale *string `json:"locale,omitempty"` - VatNumber *string `json:"vat_number,omitempty"` - TaxExempt *string `json:"tax_exempt,omitempty"` - TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` - // (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. - Metafields map[string]string `json:"metafields,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Email *string `json:"email,omitempty"` + CcEmails *string `json:"cc_emails,omitempty"` + Organization *string `json:"organization,omitempty"` + Reference *string `json:"reference,omitempty"` + Address *string `json:"address,omitempty"` + Address2 *string `json:"address_2,omitempty"` + City *string `json:"city,omitempty"` + State *string `json:"state,omitempty"` + Zip *string `json:"zip,omitempty"` + Country *string `json:"country,omitempty"` + Phone *string `json:"phone,omitempty"` + Locale *string `json:"locale,omitempty"` + VatNumber *string `json:"vat_number,omitempty"` + TaxExempt *bool `json:"tax_exempt,omitempty"` + TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` + // (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. + Metafields map[string]string `json:"metafields,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PayerAttributes. +// MarshalJSON implements the json.Marshaler interface for PayerAttributes. // It customizes the JSON marshaling process for PayerAttributes objects. func (p *PayerAttributes) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PayerAttributes object to a map representation for JSON marshaling. func (p *PayerAttributes) toMap() map[string]any { - structMap := make(map[string]any) - if p.FirstName != nil { - structMap["first_name"] = p.FirstName - } - if p.LastName != nil { - structMap["last_name"] = p.LastName - } - if p.Email != nil { - structMap["email"] = p.Email - } - if p.CcEmails != nil { - structMap["cc_emails"] = p.CcEmails - } - if p.Organization != nil { - structMap["organization"] = p.Organization - } - if p.Reference != nil { - structMap["reference"] = p.Reference - } - if p.Address != nil { - structMap["address"] = p.Address - } - if p.Address2 != nil { - structMap["address_2"] = p.Address2 - } - if p.City != nil { - structMap["city"] = p.City - } - if p.State != nil { - structMap["state"] = p.State - } - if p.Zip != nil { - structMap["zip"] = p.Zip - } - if p.Country != nil { - structMap["country"] = p.Country - } - if p.Phone != nil { - structMap["phone"] = p.Phone - } - if p.Locale != nil { - structMap["locale"] = p.Locale - } - if p.VatNumber != nil { - structMap["vat_number"] = p.VatNumber - } - if p.TaxExempt != nil { - structMap["tax_exempt"] = p.TaxExempt - } - if p.TaxExemptReason != nil { - structMap["tax_exempt_reason"] = p.TaxExemptReason - } - if p.Metafields != nil { - structMap["metafields"] = p.Metafields - } - return structMap + structMap := make(map[string]any) + if p.FirstName != nil { + structMap["first_name"] = p.FirstName + } + if p.LastName != nil { + structMap["last_name"] = p.LastName + } + if p.Email != nil { + structMap["email"] = p.Email + } + if p.CcEmails != nil { + structMap["cc_emails"] = p.CcEmails + } + if p.Organization != nil { + structMap["organization"] = p.Organization + } + if p.Reference != nil { + structMap["reference"] = p.Reference + } + if p.Address != nil { + structMap["address"] = p.Address + } + if p.Address2 != nil { + structMap["address_2"] = p.Address2 + } + if p.City != nil { + structMap["city"] = p.City + } + if p.State != nil { + structMap["state"] = p.State + } + if p.Zip != nil { + structMap["zip"] = p.Zip + } + if p.Country != nil { + structMap["country"] = p.Country + } + if p.Phone != nil { + structMap["phone"] = p.Phone + } + if p.Locale != nil { + structMap["locale"] = p.Locale + } + if p.VatNumber != nil { + structMap["vat_number"] = p.VatNumber + } + if p.TaxExempt != nil { + structMap["tax_exempt"] = p.TaxExempt + } + if p.TaxExemptReason != nil { + structMap["tax_exempt_reason"] = p.TaxExemptReason + } + if p.Metafields != nil { + structMap["metafields"] = p.Metafields + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PayerAttributes. +// UnmarshalJSON implements the json.Unmarshaler interface for PayerAttributes. // It customizes the JSON unmarshaling process for PayerAttributes objects. func (p *PayerAttributes) UnmarshalJSON(input []byte) error { - temp := &struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Email *string `json:"email,omitempty"` - CcEmails *string `json:"cc_emails,omitempty"` - Organization *string `json:"organization,omitempty"` - Reference *string `json:"reference,omitempty"` - Address *string `json:"address,omitempty"` - Address2 *string `json:"address_2,omitempty"` - City *string `json:"city,omitempty"` - State *string `json:"state,omitempty"` - Zip *string `json:"zip,omitempty"` - Country *string `json:"country,omitempty"` - Phone *string `json:"phone,omitempty"` - Locale *string `json:"locale,omitempty"` - VatNumber *string `json:"vat_number,omitempty"` - TaxExempt *string `json:"tax_exempt,omitempty"` - TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` - Metafields map[string]string `json:"metafields,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.FirstName = temp.FirstName - p.LastName = temp.LastName - p.Email = temp.Email - p.CcEmails = temp.CcEmails - p.Organization = temp.Organization - p.Reference = temp.Reference - p.Address = temp.Address - p.Address2 = temp.Address2 - p.City = temp.City - p.State = temp.State - p.Zip = temp.Zip - p.Country = temp.Country - p.Phone = temp.Phone - p.Locale = temp.Locale - p.VatNumber = temp.VatNumber - p.TaxExempt = temp.TaxExempt - p.TaxExemptReason = temp.TaxExemptReason - p.Metafields = temp.Metafields - return nil + var temp payerAttributes + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.FirstName = temp.FirstName + p.LastName = temp.LastName + p.Email = temp.Email + p.CcEmails = temp.CcEmails + p.Organization = temp.Organization + p.Reference = temp.Reference + p.Address = temp.Address + p.Address2 = temp.Address2 + p.City = temp.City + p.State = temp.State + p.Zip = temp.Zip + p.Country = temp.Country + p.Phone = temp.Phone + p.Locale = temp.Locale + p.VatNumber = temp.VatNumber + p.TaxExempt = temp.TaxExempt + p.TaxExemptReason = temp.TaxExemptReason + p.Metafields = temp.Metafields + return nil +} + +// TODO +type payerAttributes struct { + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Email *string `json:"email,omitempty"` + CcEmails *string `json:"cc_emails,omitempty"` + Organization *string `json:"organization,omitempty"` + Reference *string `json:"reference,omitempty"` + Address *string `json:"address,omitempty"` + Address2 *string `json:"address_2,omitempty"` + City *string `json:"city,omitempty"` + State *string `json:"state,omitempty"` + Zip *string `json:"zip,omitempty"` + Country *string `json:"country,omitempty"` + Phone *string `json:"phone,omitempty"` + Locale *string `json:"locale,omitempty"` + VatNumber *string `json:"vat_number,omitempty"` + TaxExempt *bool `json:"tax_exempt,omitempty"` + TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` + Metafields map[string]string `json:"metafields,omitempty"` } diff --git a/models/payer_error.go b/models/payer_error.go index 8bf6455b..33719947 100644 --- a/models/payer_error.go +++ b/models/payer_error.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // PayerError represents a PayerError struct. type PayerError struct { - LastName []string `json:"last_name,omitempty"` - FirstName []string `json:"first_name,omitempty"` - Email []string `json:"email,omitempty"` + LastName []string `json:"last_name,omitempty"` + FirstName []string `json:"first_name,omitempty"` + Email []string `json:"email,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PayerError. +// MarshalJSON implements the json.Marshaler interface for PayerError. // It customizes the JSON marshaling process for PayerError objects. func (p *PayerError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PayerError object to a map representation for JSON marshaling. func (p *PayerError) toMap() map[string]any { - structMap := make(map[string]any) - if p.LastName != nil { - structMap["last_name"] = p.LastName - } - if p.FirstName != nil { - structMap["first_name"] = p.FirstName - } - if p.Email != nil { - structMap["email"] = p.Email - } - return structMap + structMap := make(map[string]any) + if p.LastName != nil { + structMap["last_name"] = p.LastName + } + if p.FirstName != nil { + structMap["first_name"] = p.FirstName + } + if p.Email != nil { + structMap["email"] = p.Email + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PayerError. +// UnmarshalJSON implements the json.Unmarshaler interface for PayerError. // It customizes the JSON unmarshaling process for PayerError objects. func (p *PayerError) UnmarshalJSON(input []byte) error { - temp := &struct { - LastName []string `json:"last_name,omitempty"` - FirstName []string `json:"first_name,omitempty"` - Email []string `json:"email,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.LastName = temp.LastName - p.FirstName = temp.FirstName - p.Email = temp.Email - return nil + var temp payerError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.LastName = temp.LastName + p.FirstName = temp.FirstName + p.Email = temp.Email + return nil +} + +// TODO +type payerError struct { + LastName []string `json:"last_name,omitempty"` + FirstName []string `json:"first_name,omitempty"` + Email []string `json:"email,omitempty"` } diff --git a/models/payment_collection_method_changed.go b/models/payment_collection_method_changed.go new file mode 100644 index 00000000..12886b3b --- /dev/null +++ b/models/payment_collection_method_changed.go @@ -0,0 +1,67 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PaymentCollectionMethodChanged represents a PaymentCollectionMethodChanged struct. +type PaymentCollectionMethodChanged struct { + PreviousValue string `json:"previous_value"` + CurrentValue string `json:"current_value"` +} + +// MarshalJSON implements the json.Marshaler interface for PaymentCollectionMethodChanged. +// It customizes the JSON marshaling process for PaymentCollectionMethodChanged objects. +func (p *PaymentCollectionMethodChanged) MarshalJSON() ( + []byte, + error) { + return json.Marshal(p.toMap()) +} + +// toMap converts the PaymentCollectionMethodChanged object to a map representation for JSON marshaling. +func (p *PaymentCollectionMethodChanged) toMap() map[string]any { + structMap := make(map[string]any) + structMap["previous_value"] = p.PreviousValue + structMap["current_value"] = p.CurrentValue + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentCollectionMethodChanged. +// It customizes the JSON unmarshaling process for PaymentCollectionMethodChanged objects. +func (p *PaymentCollectionMethodChanged) UnmarshalJSON(input []byte) error { + var temp paymentCollectionMethodChanged + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.PreviousValue = *temp.PreviousValue + p.CurrentValue = *temp.CurrentValue + return nil +} + +// TODO +type paymentCollectionMethodChanged struct { + PreviousValue *string `json:"previous_value"` + CurrentValue *string `json:"current_value"` +} + +func (p *paymentCollectionMethodChanged) validate() error { + var errs []string + if p.PreviousValue == nil { + errs = append(errs, "required field `previous_value` is missing for type `Payment Collection Method Changed`") + } + if p.CurrentValue == nil { + errs = append(errs, "required field `current_value` is missing for type `Payment Collection Method Changed`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/payment_for_allocation.go b/models/payment_for_allocation.go index 7d049c0e..825e94c1 100644 --- a/models/payment_for_allocation.go +++ b/models/payment_for_allocation.go @@ -1,61 +1,63 @@ package models import ( - "encoding/json" + "encoding/json" ) -// PaymentForAllocation represents a PaymentForAllocation struct. +// PaymentForAllocation represents a PaymentForAllocation struct. // Information for captured payment, if applicable type PaymentForAllocation struct { - Id *int `json:"id,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - Success *bool `json:"success,omitempty"` - Memo *string `json:"memo,omitempty"` + Id *int `json:"id,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + Success *bool `json:"success,omitempty"` + Memo *string `json:"memo,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PaymentForAllocation. +// MarshalJSON implements the json.Marshaler interface for PaymentForAllocation. // It customizes the JSON marshaling process for PaymentForAllocation objects. func (p *PaymentForAllocation) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PaymentForAllocation object to a map representation for JSON marshaling. func (p *PaymentForAllocation) toMap() map[string]any { - structMap := make(map[string]any) - if p.Id != nil { - structMap["id"] = p.Id - } - if p.AmountInCents != nil { - structMap["amount_in_cents"] = p.AmountInCents - } - if p.Success != nil { - structMap["success"] = p.Success - } - if p.Memo != nil { - structMap["memo"] = p.Memo - } - return structMap + structMap := make(map[string]any) + if p.Id != nil { + structMap["id"] = p.Id + } + if p.AmountInCents != nil { + structMap["amount_in_cents"] = p.AmountInCents + } + if p.Success != nil { + structMap["success"] = p.Success + } + if p.Memo != nil { + structMap["memo"] = p.Memo + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PaymentForAllocation. +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentForAllocation. // It customizes the JSON unmarshaling process for PaymentForAllocation objects. func (p *PaymentForAllocation) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - Success *bool `json:"success,omitempty"` - Memo *string `json:"memo,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Id = temp.Id - p.AmountInCents = temp.AmountInCents - p.Success = temp.Success - p.Memo = temp.Memo - return nil + var temp paymentForAllocation + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Id = temp.Id + p.AmountInCents = temp.AmountInCents + p.Success = temp.Success + p.Memo = temp.Memo + return nil +} + +// TODO +type paymentForAllocation struct { + Id *int `json:"id,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + Success *bool `json:"success,omitempty"` + Memo *string `json:"memo,omitempty"` } diff --git a/models/payment_method_apple_pay.go b/models/payment_method_apple_pay.go index 3062b36f..2285b4f5 100644 --- a/models/payment_method_apple_pay.go +++ b/models/payment_method_apple_pay.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // PaymentMethodApplePay represents a PaymentMethodApplePay struct. type PaymentMethodApplePay struct { - Type InvoiceEventPaymentMethod `json:"type"` + Type InvoiceEventPaymentMethod `json:"type"` } -// MarshalJSON implements the json.Marshaler interface for PaymentMethodApplePay. +// MarshalJSON implements the json.Marshaler interface for PaymentMethodApplePay. // It customizes the JSON marshaling process for PaymentMethodApplePay objects. func (p *PaymentMethodApplePay) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PaymentMethodApplePay object to a map representation for JSON marshaling. func (p *PaymentMethodApplePay) toMap() map[string]any { - structMap := make(map[string]any) - structMap["type"] = p.Type - return structMap + structMap := make(map[string]any) + structMap["type"] = p.Type + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PaymentMethodApplePay. +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentMethodApplePay. // It customizes the JSON unmarshaling process for PaymentMethodApplePay objects. func (p *PaymentMethodApplePay) UnmarshalJSON(input []byte) error { - temp := &struct { - Type InvoiceEventPaymentMethod `json:"type"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Type = temp.Type - return nil + var temp paymentMethodApplePay + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.Type = *temp.Type + return nil +} + +// TODO +type paymentMethodApplePay struct { + Type *InvoiceEventPaymentMethod `json:"type"` +} + +func (p *paymentMethodApplePay) validate() error { + var errs []string + if p.Type == nil { + errs = append(errs, "required field `type` is missing for type `Payment Method Apple Pay`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/payment_method_bank_account.go b/models/payment_method_bank_account.go index 3a9d783a..dd13e0bc 100644 --- a/models/payment_method_bank_account.go +++ b/models/payment_method_bank_account.go @@ -1,48 +1,74 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // PaymentMethodBankAccount represents a PaymentMethodBankAccount struct. type PaymentMethodBankAccount struct { - MaskedAccountNumber string `json:"masked_account_number"` - MaskedRoutingNumber string `json:"masked_routing_number"` - Type InvoiceEventPaymentMethod `json:"type"` + MaskedAccountNumber string `json:"masked_account_number"` + MaskedRoutingNumber string `json:"masked_routing_number"` + Type InvoiceEventPaymentMethod `json:"type"` } -// MarshalJSON implements the json.Marshaler interface for PaymentMethodBankAccount. +// MarshalJSON implements the json.Marshaler interface for PaymentMethodBankAccount. // It customizes the JSON marshaling process for PaymentMethodBankAccount objects. func (p *PaymentMethodBankAccount) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PaymentMethodBankAccount object to a map representation for JSON marshaling. func (p *PaymentMethodBankAccount) toMap() map[string]any { - structMap := make(map[string]any) - structMap["masked_account_number"] = p.MaskedAccountNumber - structMap["masked_routing_number"] = p.MaskedRoutingNumber - structMap["type"] = p.Type - return structMap + structMap := make(map[string]any) + structMap["masked_account_number"] = p.MaskedAccountNumber + structMap["masked_routing_number"] = p.MaskedRoutingNumber + structMap["type"] = p.Type + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PaymentMethodBankAccount. +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentMethodBankAccount. // It customizes the JSON unmarshaling process for PaymentMethodBankAccount objects. func (p *PaymentMethodBankAccount) UnmarshalJSON(input []byte) error { - temp := &struct { - MaskedAccountNumber string `json:"masked_account_number"` - MaskedRoutingNumber string `json:"masked_routing_number"` - Type InvoiceEventPaymentMethod `json:"type"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.MaskedAccountNumber = temp.MaskedAccountNumber - p.MaskedRoutingNumber = temp.MaskedRoutingNumber - p.Type = temp.Type - return nil + var temp paymentMethodBankAccount + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.MaskedAccountNumber = *temp.MaskedAccountNumber + p.MaskedRoutingNumber = *temp.MaskedRoutingNumber + p.Type = *temp.Type + return nil +} + +// TODO +type paymentMethodBankAccount struct { + MaskedAccountNumber *string `json:"masked_account_number"` + MaskedRoutingNumber *string `json:"masked_routing_number"` + Type *InvoiceEventPaymentMethod `json:"type"` +} + +func (p *paymentMethodBankAccount) validate() error { + var errs []string + if p.MaskedAccountNumber == nil { + errs = append(errs, "required field `masked_account_number` is missing for type `Payment Method Bank Account`") + } + if p.MaskedRoutingNumber == nil { + errs = append(errs, "required field `masked_routing_number` is missing for type `Payment Method Bank Account`") + } + if p.Type == nil { + errs = append(errs, "required field `type` is missing for type `Payment Method Bank Account`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/payment_method_credit_card.go b/models/payment_method_credit_card.go index 9998a267..b5633137 100644 --- a/models/payment_method_credit_card.go +++ b/models/payment_method_credit_card.go @@ -1,60 +1,90 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // PaymentMethodCreditCard represents a PaymentMethodCreditCard struct. type PaymentMethodCreditCard struct { - CardBrand string `json:"card_brand"` - CardExpiration *string `json:"card_expiration,omitempty"` - LastFour Optional[string] `json:"last_four"` - MaskedCardNumber string `json:"masked_card_number"` - Type InvoiceEventPaymentMethod `json:"type"` + CardBrand string `json:"card_brand"` + CardExpiration *string `json:"card_expiration,omitempty"` + LastFour Optional[string] `json:"last_four"` + MaskedCardNumber string `json:"masked_card_number"` + Type InvoiceEventPaymentMethod `json:"type"` } -// MarshalJSON implements the json.Marshaler interface for PaymentMethodCreditCard. +// MarshalJSON implements the json.Marshaler interface for PaymentMethodCreditCard. // It customizes the JSON marshaling process for PaymentMethodCreditCard objects. func (p *PaymentMethodCreditCard) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PaymentMethodCreditCard object to a map representation for JSON marshaling. func (p *PaymentMethodCreditCard) toMap() map[string]any { - structMap := make(map[string]any) - structMap["card_brand"] = p.CardBrand - if p.CardExpiration != nil { - structMap["card_expiration"] = p.CardExpiration - } - if p.LastFour.IsValueSet() { - structMap["last_four"] = p.LastFour.Value() - } - structMap["masked_card_number"] = p.MaskedCardNumber - structMap["type"] = p.Type - return structMap + structMap := make(map[string]any) + structMap["card_brand"] = p.CardBrand + if p.CardExpiration != nil { + structMap["card_expiration"] = p.CardExpiration + } + if p.LastFour.IsValueSet() { + if p.LastFour.Value() != nil { + structMap["last_four"] = p.LastFour.Value() + } else { + structMap["last_four"] = nil + } + } + structMap["masked_card_number"] = p.MaskedCardNumber + structMap["type"] = p.Type + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PaymentMethodCreditCard. +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentMethodCreditCard. // It customizes the JSON unmarshaling process for PaymentMethodCreditCard objects. func (p *PaymentMethodCreditCard) UnmarshalJSON(input []byte) error { - temp := &struct { - CardBrand string `json:"card_brand"` - CardExpiration *string `json:"card_expiration,omitempty"` - LastFour Optional[string] `json:"last_four"` - MaskedCardNumber string `json:"masked_card_number"` - Type InvoiceEventPaymentMethod `json:"type"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.CardBrand = temp.CardBrand - p.CardExpiration = temp.CardExpiration - p.LastFour = temp.LastFour - p.MaskedCardNumber = temp.MaskedCardNumber - p.Type = temp.Type - return nil + var temp paymentMethodCreditCard + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.CardBrand = *temp.CardBrand + p.CardExpiration = temp.CardExpiration + p.LastFour = temp.LastFour + p.MaskedCardNumber = *temp.MaskedCardNumber + p.Type = *temp.Type + return nil +} + +// TODO +type paymentMethodCreditCard struct { + CardBrand *string `json:"card_brand"` + CardExpiration *string `json:"card_expiration,omitempty"` + LastFour Optional[string] `json:"last_four"` + MaskedCardNumber *string `json:"masked_card_number"` + Type *InvoiceEventPaymentMethod `json:"type"` +} + +func (p *paymentMethodCreditCard) validate() error { + var errs []string + if p.CardBrand == nil { + errs = append(errs, "required field `card_brand` is missing for type `Payment Method Credit Card`") + } + if p.MaskedCardNumber == nil { + errs = append(errs, "required field `masked_card_number` is missing for type `Payment Method Credit Card`") + } + if p.Type == nil { + errs = append(errs, "required field `type` is missing for type `Payment Method Credit Card`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/payment_method_external.go b/models/payment_method_external.go index 8859bc58..769de3f7 100644 --- a/models/payment_method_external.go +++ b/models/payment_method_external.go @@ -1,52 +1,83 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // PaymentMethodExternal represents a PaymentMethodExternal struct. type PaymentMethodExternal struct { - Details *string `json:"details"` - Kind string `json:"kind"` - Memo *string `json:"memo"` - Type InvoiceEventPaymentMethod `json:"type"` + Details *string `json:"details"` + Kind string `json:"kind"` + Memo *string `json:"memo"` + Type InvoiceEventPaymentMethod `json:"type"` } -// MarshalJSON implements the json.Marshaler interface for PaymentMethodExternal. +// MarshalJSON implements the json.Marshaler interface for PaymentMethodExternal. // It customizes the JSON marshaling process for PaymentMethodExternal objects. func (p *PaymentMethodExternal) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PaymentMethodExternal object to a map representation for JSON marshaling. func (p *PaymentMethodExternal) toMap() map[string]any { - structMap := make(map[string]any) - structMap["details"] = p.Details - structMap["kind"] = p.Kind - structMap["memo"] = p.Memo - structMap["type"] = p.Type - return structMap + structMap := make(map[string]any) + if p.Details != nil { + structMap["details"] = p.Details + } else { + structMap["details"] = nil + } + structMap["kind"] = p.Kind + if p.Memo != nil { + structMap["memo"] = p.Memo + } else { + structMap["memo"] = nil + } + structMap["type"] = p.Type + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PaymentMethodExternal. +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentMethodExternal. // It customizes the JSON unmarshaling process for PaymentMethodExternal objects. func (p *PaymentMethodExternal) UnmarshalJSON(input []byte) error { - temp := &struct { - Details *string `json:"details"` - Kind string `json:"kind"` - Memo *string `json:"memo"` - Type InvoiceEventPaymentMethod `json:"type"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Details = temp.Details - p.Kind = temp.Kind - p.Memo = temp.Memo - p.Type = temp.Type - return nil + var temp paymentMethodExternal + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.Details = temp.Details + p.Kind = *temp.Kind + p.Memo = temp.Memo + p.Type = *temp.Type + return nil +} + +// TODO +type paymentMethodExternal struct { + Details *string `json:"details"` + Kind *string `json:"kind"` + Memo *string `json:"memo"` + Type *InvoiceEventPaymentMethod `json:"type"` +} + +func (p *paymentMethodExternal) validate() error { + var errs []string + if p.Kind == nil { + errs = append(errs, "required field `kind` is missing for type `Payment Method External`") + } + if p.Type == nil { + errs = append(errs, "required field `type` is missing for type `Payment Method External`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/payment_method_paypal.go b/models/payment_method_paypal.go index fd62b709..b07e939f 100644 --- a/models/payment_method_paypal.go +++ b/models/payment_method_paypal.go @@ -1,44 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // PaymentMethodPaypal represents a PaymentMethodPaypal struct. type PaymentMethodPaypal struct { - Email string `json:"email"` - Type InvoiceEventPaymentMethod `json:"type"` + Email string `json:"email"` + Type InvoiceEventPaymentMethod `json:"type"` } -// MarshalJSON implements the json.Marshaler interface for PaymentMethodPaypal. +// MarshalJSON implements the json.Marshaler interface for PaymentMethodPaypal. // It customizes the JSON marshaling process for PaymentMethodPaypal objects. func (p *PaymentMethodPaypal) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PaymentMethodPaypal object to a map representation for JSON marshaling. func (p *PaymentMethodPaypal) toMap() map[string]any { - structMap := make(map[string]any) - structMap["email"] = p.Email - structMap["type"] = p.Type - return structMap + structMap := make(map[string]any) + structMap["email"] = p.Email + structMap["type"] = p.Type + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PaymentMethodPaypal. +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentMethodPaypal. // It customizes the JSON unmarshaling process for PaymentMethodPaypal objects. func (p *PaymentMethodPaypal) UnmarshalJSON(input []byte) error { - temp := &struct { - Email string `json:"email"` - Type InvoiceEventPaymentMethod `json:"type"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Email = temp.Email - p.Type = temp.Type - return nil + var temp paymentMethodPaypal + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.Email = *temp.Email + p.Type = *temp.Type + return nil +} + +// TODO +type paymentMethodPaypal struct { + Email *string `json:"email"` + Type *InvoiceEventPaymentMethod `json:"type"` +} + +func (p *paymentMethodPaypal) validate() error { + var errs []string + if p.Email == nil { + errs = append(errs, "required field `email` is missing for type `Payment Method Paypal`") + } + if p.Type == nil { + errs = append(errs, "required field `type` is missing for type `Payment Method Paypal`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/payment_profile_attributes.go b/models/payment_profile_attributes.go index 034b57e4..5b8d4a14 100644 --- a/models/payment_profile_attributes.go +++ b/models/payment_profile_attributes.go @@ -1,207 +1,213 @@ package models import ( - "encoding/json" + "encoding/json" ) -// PaymentProfileAttributes represents a PaymentProfileAttributes struct. +// PaymentProfileAttributes represents a PaymentProfileAttributes struct. // alias to credit_card_attributes type PaymentProfileAttributes struct { - // (Optional) Token received after sending billing informations using chargify.js. This token must be passed as a sole attribute of `payment_profile_attributes` (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) - ChargifyToken *string `json:"chargify_token,omitempty"` - Id *int `json:"id,omitempty"` - PaymentType *string `json:"payment_type,omitempty"` - // (Optional) First name on card or bank account. If omitted, the first_name from customer attributes will be used. - FirstName *string `json:"first_name,omitempty"` - // (Optional) Last name on card or bank account. If omitted, the last_name from customer attributes will be used. - LastName *string `json:"last_name,omitempty"` - MaskedCardNumber *string `json:"masked_card_number,omitempty"` - // The full credit card number (string representation, i.e. 5424000000000015) - FullNumber *string `json:"full_number,omitempty"` - // (Optional, used only for Subscription Import) If you know the card type (i.e. Visa, MC, etc) you may supply it here so that we may display the card type in the UI. - CardType *CardType `json:"card_type,omitempty"` - // (Optional when performing a Subscription Import via vault_token, required otherwise) The 1- or 2-digit credit card expiration month, as an integer or string, i.e. 5 - ExpirationMonth *interface{} `json:"expiration_month,omitempty"` - // (Optional when performing a Subscription Import via vault_token, required otherwise) The 4-digit credit card expiration year, as an integer or string, i.e. 2012 - ExpirationYear *interface{} `json:"expiration_year,omitempty"` - // (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. - BillingAddress *string `json:"billing_address,omitempty"` - // (Optional) Second line of the customer’s billing address i.e. Apt. 100 - BillingAddress2 Optional[string] `json:"billing_address_2"` - // (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. - BillingCity *string `json:"billing_city,omitempty"` - // (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. - BillingState *string `json:"billing_state,omitempty"` - // (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. - BillingCountry *string `json:"billing_country,omitempty"` - // (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. - BillingZip *string `json:"billing_zip,omitempty"` - // (Optional, used only for Subscription Import) The vault that stores the payment profile with the provided vault_token. - CurrentVault *CurrentVault `json:"current_vault,omitempty"` - // (Optional, used only for Subscription Import) The “token” provided by your vault storage for an already stored payment profile - VaultToken *string `json:"vault_token,omitempty"` - // (Optional, used only for Subscription Import) (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token - CustomerVaultToken *string `json:"customer_vault_token,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - PaypalEmail *string `json:"paypal_email,omitempty"` - // (Required for Square unless importing with vault_token and customer_vault_token) The nonce generated by the Square Javascript library (SqPaymentForm) - PaymentMethodNonce *string `json:"payment_method_nonce,omitempty"` - // (Optional) This attribute is only available if MultiGateway feature is enabled for your Site. This feature is in the Private Beta currently. gateway_handle is used to directly select a gateway where a payment profile will be stored in. Every connected gateway must have a unique gateway handle specified. Read [Multigateway description](https://chargify.zendesk.com/hc/en-us/articles/4407761759643#connecting-with-multiple-gateways) to learn more about new concepts that MultiGateway introduces and the default behavior when this attribute is not passed. - GatewayHandle *string `json:"gateway_handle,omitempty"` - // (Optional, may be required by your gateway settings) The 3- or 4-digit Card Verification Value. This value is merely passed through to the payment gateway. - Cvv *string `json:"cvv,omitempty"` - // (Optional, used only for Subscription Import) If you have the last 4 digits of the credit card number, you may supply them here so that we may create a masked card number (i.e. XXXX-XXXX-XXXX-1234) for display in the UI. Last 4 digits are required for refunds in Auth.Net. - LastFour *string `json:"last_four,omitempty"` + // (Optional) Token received after sending billing informations using chargify.js. This token must be passed as a sole attribute of `payment_profile_attributes` (i.e. tok_9g6hw85pnpt6knmskpwp4ttt) + ChargifyToken *string `json:"chargify_token,omitempty"` + Id *int `json:"id,omitempty"` + PaymentType *string `json:"payment_type,omitempty"` + // (Optional) First name on card or bank account. If omitted, the first_name from customer attributes will be used. + FirstName *string `json:"first_name,omitempty"` + // (Optional) Last name on card or bank account. If omitted, the last_name from customer attributes will be used. + LastName *string `json:"last_name,omitempty"` + MaskedCardNumber *string `json:"masked_card_number,omitempty"` + // The full credit card number (string representation, i.e. 5424000000000015) + FullNumber *string `json:"full_number,omitempty"` + // (Optional, used only for Subscription Import) If you know the card type (i.e. Visa, MC, etc) you may supply it here so that we may display the card type in the UI. + CardType *CardType `json:"card_type,omitempty"` + // (Optional when performing a Subscription Import via vault_token, required otherwise) The 1- or 2-digit credit card expiration month, as an integer or string, i.e. 5 + ExpirationMonth *PaymentProfileAttributesExpirationMonth `json:"expiration_month,omitempty"` + // (Optional when performing a Subscription Import via vault_token, required otherwise) The 4-digit credit card expiration year, as an integer or string, i.e. 2012 + ExpirationYear *PaymentProfileAttributesExpirationYear `json:"expiration_year,omitempty"` + // (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. + BillingAddress *string `json:"billing_address,omitempty"` + // (Optional) Second line of the customer’s billing address i.e. Apt. 100 + BillingAddress2 Optional[string] `json:"billing_address_2"` + // (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. + BillingCity *string `json:"billing_city,omitempty"` + // (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. + BillingState *string `json:"billing_state,omitempty"` + // (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. + BillingCountry *string `json:"billing_country,omitempty"` + // (Optional, may be required by your product configuration or gateway settings) The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. + BillingZip *string `json:"billing_zip,omitempty"` + // (Optional, used only for Subscription Import) The vault that stores the payment profile with the provided vault_token. + CurrentVault *CurrentVault `json:"current_vault,omitempty"` + // (Optional, used only for Subscription Import) The “token” provided by your vault storage for an already stored payment profile + VaultToken *string `json:"vault_token,omitempty"` + // (Optional, used only for Subscription Import) (only for Authorize.Net CIM storage or Square) The customerProfileId for the owner of the customerPaymentProfileId provided as the vault_token + CustomerVaultToken *string `json:"customer_vault_token,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaypalEmail *string `json:"paypal_email,omitempty"` + // (Required for Square unless importing with vault_token and customer_vault_token) The nonce generated by the Square Javascript library (SqPaymentForm) + PaymentMethodNonce *string `json:"payment_method_nonce,omitempty"` + // (Optional) This attribute is only available if MultiGateway feature is enabled for your Site. This feature is in the Private Beta currently. gateway_handle is used to directly select a gateway where a payment profile will be stored in. Every connected gateway must have a unique gateway handle specified. Read [Multigateway description](https://chargify.zendesk.com/hc/en-us/articles/4407761759643#connecting-with-multiple-gateways) to learn more about new concepts that MultiGateway introduces and the default behavior when this attribute is not passed. + GatewayHandle *string `json:"gateway_handle,omitempty"` + // (Optional, may be required by your gateway settings) The 3- or 4-digit Card Verification Value. This value is merely passed through to the payment gateway. + Cvv *string `json:"cvv,omitempty"` + // (Optional, used only for Subscription Import) If you have the last 4 digits of the credit card number, you may supply them here so that we may create a masked card number (i.e. XXXX-XXXX-XXXX-1234) for display in the UI. Last 4 digits are required for refunds in Auth.Net. + LastFour *string `json:"last_four,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PaymentProfileAttributes. +// MarshalJSON implements the json.Marshaler interface for PaymentProfileAttributes. // It customizes the JSON marshaling process for PaymentProfileAttributes objects. func (p *PaymentProfileAttributes) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PaymentProfileAttributes object to a map representation for JSON marshaling. func (p *PaymentProfileAttributes) toMap() map[string]any { - structMap := make(map[string]any) - if p.ChargifyToken != nil { - structMap["chargify_token"] = p.ChargifyToken - } - if p.Id != nil { - structMap["id"] = p.Id - } - if p.PaymentType != nil { - structMap["payment_type"] = p.PaymentType - } - if p.FirstName != nil { - structMap["first_name"] = p.FirstName - } - if p.LastName != nil { - structMap["last_name"] = p.LastName - } - if p.MaskedCardNumber != nil { - structMap["masked_card_number"] = p.MaskedCardNumber - } - if p.FullNumber != nil { - structMap["full_number"] = p.FullNumber - } - if p.CardType != nil { - structMap["card_type"] = p.CardType - } - if p.ExpirationMonth != nil { - structMap["expiration_month"] = p.ExpirationMonth - } - if p.ExpirationYear != nil { - structMap["expiration_year"] = p.ExpirationYear - } - if p.BillingAddress != nil { - structMap["billing_address"] = p.BillingAddress - } - if p.BillingAddress2.IsValueSet() { - structMap["billing_address_2"] = p.BillingAddress2.Value() - } - if p.BillingCity != nil { - structMap["billing_city"] = p.BillingCity - } - if p.BillingState != nil { - structMap["billing_state"] = p.BillingState - } - if p.BillingCountry != nil { - structMap["billing_country"] = p.BillingCountry - } - if p.BillingZip != nil { - structMap["billing_zip"] = p.BillingZip - } - if p.CurrentVault != nil { - structMap["current_vault"] = p.CurrentVault - } - if p.VaultToken != nil { - structMap["vault_token"] = p.VaultToken - } - if p.CustomerVaultToken != nil { - structMap["customer_vault_token"] = p.CustomerVaultToken - } - if p.CustomerId != nil { - structMap["customer_id"] = p.CustomerId - } - if p.PaypalEmail != nil { - structMap["paypal_email"] = p.PaypalEmail - } - if p.PaymentMethodNonce != nil { - structMap["payment_method_nonce"] = p.PaymentMethodNonce - } - if p.GatewayHandle != nil { - structMap["gateway_handle"] = p.GatewayHandle - } - if p.Cvv != nil { - structMap["cvv"] = p.Cvv - } - if p.LastFour != nil { - structMap["last_four"] = p.LastFour - } - return structMap + structMap := make(map[string]any) + if p.ChargifyToken != nil { + structMap["chargify_token"] = p.ChargifyToken + } + if p.Id != nil { + structMap["id"] = p.Id + } + if p.PaymentType != nil { + structMap["payment_type"] = p.PaymentType + } + if p.FirstName != nil { + structMap["first_name"] = p.FirstName + } + if p.LastName != nil { + structMap["last_name"] = p.LastName + } + if p.MaskedCardNumber != nil { + structMap["masked_card_number"] = p.MaskedCardNumber + } + if p.FullNumber != nil { + structMap["full_number"] = p.FullNumber + } + if p.CardType != nil { + structMap["card_type"] = p.CardType + } + if p.ExpirationMonth != nil { + structMap["expiration_month"] = p.ExpirationMonth.toMap() + } + if p.ExpirationYear != nil { + structMap["expiration_year"] = p.ExpirationYear.toMap() + } + if p.BillingAddress != nil { + structMap["billing_address"] = p.BillingAddress + } + if p.BillingAddress2.IsValueSet() { + if p.BillingAddress2.Value() != nil { + structMap["billing_address_2"] = p.BillingAddress2.Value() + } else { + structMap["billing_address_2"] = nil + } + } + if p.BillingCity != nil { + structMap["billing_city"] = p.BillingCity + } + if p.BillingState != nil { + structMap["billing_state"] = p.BillingState + } + if p.BillingCountry != nil { + structMap["billing_country"] = p.BillingCountry + } + if p.BillingZip != nil { + structMap["billing_zip"] = p.BillingZip + } + if p.CurrentVault != nil { + structMap["current_vault"] = p.CurrentVault + } + if p.VaultToken != nil { + structMap["vault_token"] = p.VaultToken + } + if p.CustomerVaultToken != nil { + structMap["customer_vault_token"] = p.CustomerVaultToken + } + if p.CustomerId != nil { + structMap["customer_id"] = p.CustomerId + } + if p.PaypalEmail != nil { + structMap["paypal_email"] = p.PaypalEmail + } + if p.PaymentMethodNonce != nil { + structMap["payment_method_nonce"] = p.PaymentMethodNonce + } + if p.GatewayHandle != nil { + structMap["gateway_handle"] = p.GatewayHandle + } + if p.Cvv != nil { + structMap["cvv"] = p.Cvv + } + if p.LastFour != nil { + structMap["last_four"] = p.LastFour + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PaymentProfileAttributes. +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentProfileAttributes. // It customizes the JSON unmarshaling process for PaymentProfileAttributes objects. func (p *PaymentProfileAttributes) UnmarshalJSON(input []byte) error { - temp := &struct { - ChargifyToken *string `json:"chargify_token,omitempty"` - Id *int `json:"id,omitempty"` - PaymentType *string `json:"payment_type,omitempty"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - MaskedCardNumber *string `json:"masked_card_number,omitempty"` - FullNumber *string `json:"full_number,omitempty"` - CardType *CardType `json:"card_type,omitempty"` - ExpirationMonth *interface{} `json:"expiration_month,omitempty"` - ExpirationYear *interface{} `json:"expiration_year,omitempty"` - BillingAddress *string `json:"billing_address,omitempty"` - BillingAddress2 Optional[string] `json:"billing_address_2"` - BillingCity *string `json:"billing_city,omitempty"` - BillingState *string `json:"billing_state,omitempty"` - BillingCountry *string `json:"billing_country,omitempty"` - BillingZip *string `json:"billing_zip,omitempty"` - CurrentVault *CurrentVault `json:"current_vault,omitempty"` - VaultToken *string `json:"vault_token,omitempty"` - CustomerVaultToken *string `json:"customer_vault_token,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - PaypalEmail *string `json:"paypal_email,omitempty"` - PaymentMethodNonce *string `json:"payment_method_nonce,omitempty"` - GatewayHandle *string `json:"gateway_handle,omitempty"` - Cvv *string `json:"cvv,omitempty"` - LastFour *string `json:"last_four,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.ChargifyToken = temp.ChargifyToken - p.Id = temp.Id - p.PaymentType = temp.PaymentType - p.FirstName = temp.FirstName - p.LastName = temp.LastName - p.MaskedCardNumber = temp.MaskedCardNumber - p.FullNumber = temp.FullNumber - p.CardType = temp.CardType - p.ExpirationMonth = temp.ExpirationMonth - p.ExpirationYear = temp.ExpirationYear - p.BillingAddress = temp.BillingAddress - p.BillingAddress2 = temp.BillingAddress2 - p.BillingCity = temp.BillingCity - p.BillingState = temp.BillingState - p.BillingCountry = temp.BillingCountry - p.BillingZip = temp.BillingZip - p.CurrentVault = temp.CurrentVault - p.VaultToken = temp.VaultToken - p.CustomerVaultToken = temp.CustomerVaultToken - p.CustomerId = temp.CustomerId - p.PaypalEmail = temp.PaypalEmail - p.PaymentMethodNonce = temp.PaymentMethodNonce - p.GatewayHandle = temp.GatewayHandle - p.Cvv = temp.Cvv - p.LastFour = temp.LastFour - return nil + var temp paymentProfileAttributes + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.ChargifyToken = temp.ChargifyToken + p.Id = temp.Id + p.PaymentType = temp.PaymentType + p.FirstName = temp.FirstName + p.LastName = temp.LastName + p.MaskedCardNumber = temp.MaskedCardNumber + p.FullNumber = temp.FullNumber + p.CardType = temp.CardType + p.ExpirationMonth = temp.ExpirationMonth + p.ExpirationYear = temp.ExpirationYear + p.BillingAddress = temp.BillingAddress + p.BillingAddress2 = temp.BillingAddress2 + p.BillingCity = temp.BillingCity + p.BillingState = temp.BillingState + p.BillingCountry = temp.BillingCountry + p.BillingZip = temp.BillingZip + p.CurrentVault = temp.CurrentVault + p.VaultToken = temp.VaultToken + p.CustomerVaultToken = temp.CustomerVaultToken + p.CustomerId = temp.CustomerId + p.PaypalEmail = temp.PaypalEmail + p.PaymentMethodNonce = temp.PaymentMethodNonce + p.GatewayHandle = temp.GatewayHandle + p.Cvv = temp.Cvv + p.LastFour = temp.LastFour + return nil +} + +// TODO +type paymentProfileAttributes struct { + ChargifyToken *string `json:"chargify_token,omitempty"` + Id *int `json:"id,omitempty"` + PaymentType *string `json:"payment_type,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + MaskedCardNumber *string `json:"masked_card_number,omitempty"` + FullNumber *string `json:"full_number,omitempty"` + CardType *CardType `json:"card_type,omitempty"` + ExpirationMonth *PaymentProfileAttributesExpirationMonth `json:"expiration_month,omitempty"` + ExpirationYear *PaymentProfileAttributesExpirationYear `json:"expiration_year,omitempty"` + BillingAddress *string `json:"billing_address,omitempty"` + BillingAddress2 Optional[string] `json:"billing_address_2"` + BillingCity *string `json:"billing_city,omitempty"` + BillingState *string `json:"billing_state,omitempty"` + BillingCountry *string `json:"billing_country,omitempty"` + BillingZip *string `json:"billing_zip,omitempty"` + CurrentVault *CurrentVault `json:"current_vault,omitempty"` + VaultToken *string `json:"vault_token,omitempty"` + CustomerVaultToken *string `json:"customer_vault_token,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaypalEmail *string `json:"paypal_email,omitempty"` + PaymentMethodNonce *string `json:"payment_method_nonce,omitempty"` + GatewayHandle *string `json:"gateway_handle,omitempty"` + Cvv *string `json:"cvv,omitempty"` + LastFour *string `json:"last_four,omitempty"` } diff --git a/models/payment_profile_attributes_expiration_month.go b/models/payment_profile_attributes_expiration_month.go new file mode 100644 index 00000000..0c7a22be --- /dev/null +++ b/models/payment_profile_attributes_expiration_month.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PaymentProfileAttributesExpirationMonth represents a PaymentProfileAttributesExpirationMonth struct. +// This is a container for one-of cases. +type PaymentProfileAttributesExpirationMonth struct { + value any + isNumber bool + isString bool +} + +// String converts the PaymentProfileAttributesExpirationMonth object to a string representation. +func (p PaymentProfileAttributesExpirationMonth) String() string { + if bytes, err := json.Marshal(p.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for PaymentProfileAttributesExpirationMonth. +// It customizes the JSON marshaling process for PaymentProfileAttributesExpirationMonth objects. +func (p *PaymentProfileAttributesExpirationMonth) MarshalJSON() ( + []byte, + error) { + if p.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.PaymentProfileAttributesExpirationMonthContainer.From*` functions to initialize the PaymentProfileAttributesExpirationMonth object.") + } + return json.Marshal(p.toMap()) +} + +// toMap converts the PaymentProfileAttributesExpirationMonth object to a map representation for JSON marshaling. +func (p *PaymentProfileAttributesExpirationMonth) toMap() any { + switch obj := p.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentProfileAttributesExpirationMonth. +// It customizes the JSON unmarshaling process for PaymentProfileAttributesExpirationMonth objects. +func (p *PaymentProfileAttributesExpirationMonth) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &p.isNumber), + NewTypeHolder(new(string), false, &p.isString), + ) + + p.value = result + return err +} + +func (p *PaymentProfileAttributesExpirationMonth) AsNumber() ( + *int, + bool) { + if !p.isNumber { + return nil, false + } + return p.value.(*int), true +} + +func (p *PaymentProfileAttributesExpirationMonth) AsString() ( + *string, + bool) { + if !p.isString { + return nil, false + } + return p.value.(*string), true +} + +// internalPaymentProfileAttributesExpirationMonth represents a paymentProfileAttributesExpirationMonth struct. +// This is a container for one-of cases. +type internalPaymentProfileAttributesExpirationMonth struct{} + +var PaymentProfileAttributesExpirationMonthContainer internalPaymentProfileAttributesExpirationMonth + +func (p *internalPaymentProfileAttributesExpirationMonth) FromNumber(val int) PaymentProfileAttributesExpirationMonth { + return PaymentProfileAttributesExpirationMonth{value: &val} +} + +func (p *internalPaymentProfileAttributesExpirationMonth) FromString(val string) PaymentProfileAttributesExpirationMonth { + return PaymentProfileAttributesExpirationMonth{value: &val} +} diff --git a/models/payment_profile_attributes_expiration_year.go b/models/payment_profile_attributes_expiration_year.go new file mode 100644 index 00000000..26c8c33a --- /dev/null +++ b/models/payment_profile_attributes_expiration_year.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PaymentProfileAttributesExpirationYear represents a PaymentProfileAttributesExpirationYear struct. +// This is a container for one-of cases. +type PaymentProfileAttributesExpirationYear struct { + value any + isNumber bool + isString bool +} + +// String converts the PaymentProfileAttributesExpirationYear object to a string representation. +func (p PaymentProfileAttributesExpirationYear) String() string { + if bytes, err := json.Marshal(p.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for PaymentProfileAttributesExpirationYear. +// It customizes the JSON marshaling process for PaymentProfileAttributesExpirationYear objects. +func (p *PaymentProfileAttributesExpirationYear) MarshalJSON() ( + []byte, + error) { + if p.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.PaymentProfileAttributesExpirationYearContainer.From*` functions to initialize the PaymentProfileAttributesExpirationYear object.") + } + return json.Marshal(p.toMap()) +} + +// toMap converts the PaymentProfileAttributesExpirationYear object to a map representation for JSON marshaling. +func (p *PaymentProfileAttributesExpirationYear) toMap() any { + switch obj := p.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentProfileAttributesExpirationYear. +// It customizes the JSON unmarshaling process for PaymentProfileAttributesExpirationYear objects. +func (p *PaymentProfileAttributesExpirationYear) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &p.isNumber), + NewTypeHolder(new(string), false, &p.isString), + ) + + p.value = result + return err +} + +func (p *PaymentProfileAttributesExpirationYear) AsNumber() ( + *int, + bool) { + if !p.isNumber { + return nil, false + } + return p.value.(*int), true +} + +func (p *PaymentProfileAttributesExpirationYear) AsString() ( + *string, + bool) { + if !p.isString { + return nil, false + } + return p.value.(*string), true +} + +// internalPaymentProfileAttributesExpirationYear represents a paymentProfileAttributesExpirationYear struct. +// This is a container for one-of cases. +type internalPaymentProfileAttributesExpirationYear struct{} + +var PaymentProfileAttributesExpirationYearContainer internalPaymentProfileAttributesExpirationYear + +func (p *internalPaymentProfileAttributesExpirationYear) FromNumber(val int) PaymentProfileAttributesExpirationYear { + return PaymentProfileAttributesExpirationYear{value: &val} +} + +func (p *internalPaymentProfileAttributesExpirationYear) FromString(val string) PaymentProfileAttributesExpirationYear { + return PaymentProfileAttributesExpirationYear{value: &val} +} diff --git a/models/payment_profile_response.go b/models/payment_profile_response.go index 910e903d..e1f26f69 100644 --- a/models/payment_profile_response.go +++ b/models/payment_profile_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // PaymentProfileResponse represents a PaymentProfileResponse struct. type PaymentProfileResponse struct { - PaymentProfile interface{} `json:"payment_profile"` + PaymentProfile PaymentProfileResponsePaymentProfile `json:"payment_profile"` } -// MarshalJSON implements the json.Marshaler interface for PaymentProfileResponse. +// MarshalJSON implements the json.Marshaler interface for PaymentProfileResponse. // It customizes the JSON marshaling process for PaymentProfileResponse objects. func (p *PaymentProfileResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PaymentProfileResponse object to a map representation for JSON marshaling. func (p *PaymentProfileResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["payment_profile"] = p.PaymentProfile - return structMap + structMap := make(map[string]any) + structMap["payment_profile"] = p.PaymentProfile.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PaymentProfileResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentProfileResponse. // It customizes the JSON unmarshaling process for PaymentProfileResponse objects. func (p *PaymentProfileResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - PaymentProfile interface{} `json:"payment_profile"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.PaymentProfile = temp.PaymentProfile - return nil + var temp paymentProfileResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.PaymentProfile = *temp.PaymentProfile + return nil +} + +// TODO +type paymentProfileResponse struct { + PaymentProfile *PaymentProfileResponsePaymentProfile `json:"payment_profile"` +} + +func (p *paymentProfileResponse) validate() error { + var errs []string + if p.PaymentProfile == nil { + errs = append(errs, "required field `payment_profile` is missing for type `Payment Profile Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/payment_profile_response_payment_profile.go b/models/payment_profile_response_payment_profile.go new file mode 100644 index 00000000..b1ee2d7d --- /dev/null +++ b/models/payment_profile_response_payment_profile.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PaymentProfileResponsePaymentProfile represents a PaymentProfileResponsePaymentProfile struct. +// This is a container for one-of cases. +type PaymentProfileResponsePaymentProfile struct { + value any + isBankAccountPaymentProfile bool + isCreditCardPaymentProfile bool +} + +// String converts the PaymentProfileResponsePaymentProfile object to a string representation. +func (p PaymentProfileResponsePaymentProfile) String() string { + if bytes, err := json.Marshal(p.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for PaymentProfileResponsePaymentProfile. +// It customizes the JSON marshaling process for PaymentProfileResponsePaymentProfile objects. +func (p *PaymentProfileResponsePaymentProfile) MarshalJSON() ( + []byte, + error) { + if p.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.PaymentProfileResponsePaymentProfileContainer.From*` functions to initialize the PaymentProfileResponsePaymentProfile object.") + } + return json.Marshal(p.toMap()) +} + +// toMap converts the PaymentProfileResponsePaymentProfile object to a map representation for JSON marshaling. +func (p *PaymentProfileResponsePaymentProfile) toMap() any { + switch obj := p.value.(type) { + case *BankAccountPaymentProfile: + return obj.toMap() + case *CreditCardPaymentProfile: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentProfileResponsePaymentProfile. +// It customizes the JSON unmarshaling process for PaymentProfileResponsePaymentProfile objects. +func (p *PaymentProfileResponsePaymentProfile) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&BankAccountPaymentProfile{}, false, &p.isBankAccountPaymentProfile), + NewTypeHolder(&CreditCardPaymentProfile{}, false, &p.isCreditCardPaymentProfile), + ) + + p.value = result + return err +} + +func (p *PaymentProfileResponsePaymentProfile) AsBankAccountPaymentProfile() ( + *BankAccountPaymentProfile, + bool) { + if !p.isBankAccountPaymentProfile { + return nil, false + } + return p.value.(*BankAccountPaymentProfile), true +} + +func (p *PaymentProfileResponsePaymentProfile) AsCreditCardPaymentProfile() ( + *CreditCardPaymentProfile, + bool) { + if !p.isCreditCardPaymentProfile { + return nil, false + } + return p.value.(*CreditCardPaymentProfile), true +} + +// internalPaymentProfileResponsePaymentProfile represents a paymentProfileResponsePaymentProfile struct. +// This is a container for one-of cases. +type internalPaymentProfileResponsePaymentProfile struct{} + +var PaymentProfileResponsePaymentProfileContainer internalPaymentProfileResponsePaymentProfile + +func (p *internalPaymentProfileResponsePaymentProfile) FromBankAccountPaymentProfile(val BankAccountPaymentProfile) PaymentProfileResponsePaymentProfile { + return PaymentProfileResponsePaymentProfile{value: &val} +} + +func (p *internalPaymentProfileResponsePaymentProfile) FromCreditCardPaymentProfile(val CreditCardPaymentProfile) PaymentProfileResponsePaymentProfile { + return PaymentProfileResponsePaymentProfile{value: &val} +} diff --git a/models/payment_related_events.go b/models/payment_related_events.go new file mode 100644 index 00000000..4bfddfa4 --- /dev/null +++ b/models/payment_related_events.go @@ -0,0 +1,67 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PaymentRelatedEvents represents a PaymentRelatedEvents struct. +type PaymentRelatedEvents struct { + ProductId int `json:"product_id"` + AccountTransactionId int `json:"account_transaction_id"` +} + +// MarshalJSON implements the json.Marshaler interface for PaymentRelatedEvents. +// It customizes the JSON marshaling process for PaymentRelatedEvents objects. +func (p *PaymentRelatedEvents) MarshalJSON() ( + []byte, + error) { + return json.Marshal(p.toMap()) +} + +// toMap converts the PaymentRelatedEvents object to a map representation for JSON marshaling. +func (p *PaymentRelatedEvents) toMap() map[string]any { + structMap := make(map[string]any) + structMap["product_id"] = p.ProductId + structMap["account_transaction_id"] = p.AccountTransactionId + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PaymentRelatedEvents. +// It customizes the JSON unmarshaling process for PaymentRelatedEvents objects. +func (p *PaymentRelatedEvents) UnmarshalJSON(input []byte) error { + var temp paymentRelatedEvents + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.ProductId = *temp.ProductId + p.AccountTransactionId = *temp.AccountTransactionId + return nil +} + +// TODO +type paymentRelatedEvents struct { + ProductId *int `json:"product_id"` + AccountTransactionId *int `json:"account_transaction_id"` +} + +func (p *paymentRelatedEvents) validate() error { + var errs []string + if p.ProductId == nil { + errs = append(errs, "required field `product_id` is missing for type `Payment Related Events`") + } + if p.AccountTransactionId == nil { + errs = append(errs, "required field `account_transaction_id` is missing for type `Payment Related Events`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/pending_cancellation_change.go b/models/pending_cancellation_change.go new file mode 100644 index 00000000..d13a4120 --- /dev/null +++ b/models/pending_cancellation_change.go @@ -0,0 +1,73 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// PendingCancellationChange represents a PendingCancellationChange struct. +type PendingCancellationChange struct { + CancellationState string `json:"cancellation_state"` + CancelsAt time.Time `json:"cancels_at"` +} + +// MarshalJSON implements the json.Marshaler interface for PendingCancellationChange. +// It customizes the JSON marshaling process for PendingCancellationChange objects. +func (p *PendingCancellationChange) MarshalJSON() ( + []byte, + error) { + return json.Marshal(p.toMap()) +} + +// toMap converts the PendingCancellationChange object to a map representation for JSON marshaling. +func (p *PendingCancellationChange) toMap() map[string]any { + structMap := make(map[string]any) + structMap["cancellation_state"] = p.CancellationState + structMap["cancels_at"] = p.CancelsAt.Format(time.RFC3339) + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PendingCancellationChange. +// It customizes the JSON unmarshaling process for PendingCancellationChange objects. +func (p *PendingCancellationChange) UnmarshalJSON(input []byte) error { + var temp pendingCancellationChange + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.CancellationState = *temp.CancellationState + CancelsAtVal, err := time.Parse(time.RFC3339, *temp.CancelsAt) + if err != nil { + log.Fatalf("Cannot Parse cancels_at as % s format.", time.RFC3339) + } + p.CancelsAt = CancelsAtVal + return nil +} + +// TODO +type pendingCancellationChange struct { + CancellationState *string `json:"cancellation_state"` + CancelsAt *string `json:"cancels_at"` +} + +func (p *pendingCancellationChange) validate() error { + var errs []string + if p.CancellationState == nil { + errs = append(errs, "required field `cancellation_state` is missing for type `Pending Cancellation Change`") + } + if p.CancelsAt == nil { + errs = append(errs, "required field `cancels_at` is missing for type `Pending Cancellation Change`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/portal_management_link.go b/models/portal_management_link.go index c4b13160..9c2e27c9 100644 --- a/models/portal_management_link.go +++ b/models/portal_management_link.go @@ -1,104 +1,110 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // PortalManagementLink represents a PortalManagementLink struct. type PortalManagementLink struct { - Url *string `json:"url,omitempty"` - FetchCount *int `json:"fetch_count,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - NewLinkAvailableAt *time.Time `json:"new_link_available_at,omitempty"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` - LastInviteSentAt Optional[time.Time] `json:"last_invite_sent_at"` + Url *string `json:"url,omitempty"` + FetchCount *int `json:"fetch_count,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + NewLinkAvailableAt *time.Time `json:"new_link_available_at,omitempty"` + ExpiresAt *time.Time `json:"expires_at,omitempty"` + LastInviteSentAt Optional[time.Time] `json:"last_invite_sent_at"` } -// MarshalJSON implements the json.Marshaler interface for PortalManagementLink. +// MarshalJSON implements the json.Marshaler interface for PortalManagementLink. // It customizes the JSON marshaling process for PortalManagementLink objects. func (p *PortalManagementLink) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PortalManagementLink object to a map representation for JSON marshaling. func (p *PortalManagementLink) toMap() map[string]any { - structMap := make(map[string]any) - if p.Url != nil { - structMap["url"] = p.Url - } - if p.FetchCount != nil { - structMap["fetch_count"] = p.FetchCount - } - if p.CreatedAt != nil { - structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) - } - if p.NewLinkAvailableAt != nil { - structMap["new_link_available_at"] = p.NewLinkAvailableAt.Format(time.RFC3339) - } - if p.ExpiresAt != nil { - structMap["expires_at"] = p.ExpiresAt.Format(time.RFC3339) - } - if p.LastInviteSentAt.IsValueSet() { - var LastInviteSentAtVal *string = nil - if p.LastInviteSentAt.Value() != nil { - val := p.LastInviteSentAt.Value().Format(time.RFC3339) - LastInviteSentAtVal = &val - } - structMap["last_invite_sent_at"] = LastInviteSentAtVal - } - return structMap + structMap := make(map[string]any) + if p.Url != nil { + structMap["url"] = p.Url + } + if p.FetchCount != nil { + structMap["fetch_count"] = p.FetchCount + } + if p.CreatedAt != nil { + structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) + } + if p.NewLinkAvailableAt != nil { + structMap["new_link_available_at"] = p.NewLinkAvailableAt.Format(time.RFC3339) + } + if p.ExpiresAt != nil { + structMap["expires_at"] = p.ExpiresAt.Format(time.RFC3339) + } + if p.LastInviteSentAt.IsValueSet() { + var LastInviteSentAtVal *string = nil + if p.LastInviteSentAt.Value() != nil { + val := p.LastInviteSentAt.Value().Format(time.RFC3339) + LastInviteSentAtVal = &val + } + if p.LastInviteSentAt.Value() != nil { + structMap["last_invite_sent_at"] = LastInviteSentAtVal + } else { + structMap["last_invite_sent_at"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PortalManagementLink. +// UnmarshalJSON implements the json.Unmarshaler interface for PortalManagementLink. // It customizes the JSON unmarshaling process for PortalManagementLink objects. func (p *PortalManagementLink) UnmarshalJSON(input []byte) error { - temp := &struct { - Url *string `json:"url,omitempty"` - FetchCount *int `json:"fetch_count,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - NewLinkAvailableAt *string `json:"new_link_available_at,omitempty"` - ExpiresAt *string `json:"expires_at,omitempty"` - LastInviteSentAt Optional[string] `json:"last_invite_sent_at"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Url = temp.Url - p.FetchCount = temp.FetchCount - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - p.CreatedAt = &CreatedAtVal - } - if temp.NewLinkAvailableAt != nil { - NewLinkAvailableAtVal, err := time.Parse(time.RFC3339, *temp.NewLinkAvailableAt) - if err != nil { - log.Fatalf("Cannot Parse new_link_available_at as % s format.", time.RFC3339) - } - p.NewLinkAvailableAt = &NewLinkAvailableAtVal - } - if temp.ExpiresAt != nil { - ExpiresAtVal, err := time.Parse(time.RFC3339, *temp.ExpiresAt) - if err != nil { - log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) - } - p.ExpiresAt = &ExpiresAtVal - } - p.LastInviteSentAt.ShouldSetValue(temp.LastInviteSentAt.IsValueSet()) - if temp.LastInviteSentAt.Value() != nil { - LastInviteSentAtVal, err := time.Parse(time.RFC3339, (*temp.LastInviteSentAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse last_invite_sent_at as % s format.", time.RFC3339) - } - p.LastInviteSentAt.SetValue(&LastInviteSentAtVal) - } - return nil + var temp portalManagementLink + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Url = temp.Url + p.FetchCount = temp.FetchCount + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + p.CreatedAt = &CreatedAtVal + } + if temp.NewLinkAvailableAt != nil { + NewLinkAvailableAtVal, err := time.Parse(time.RFC3339, *temp.NewLinkAvailableAt) + if err != nil { + log.Fatalf("Cannot Parse new_link_available_at as % s format.", time.RFC3339) + } + p.NewLinkAvailableAt = &NewLinkAvailableAtVal + } + if temp.ExpiresAt != nil { + ExpiresAtVal, err := time.Parse(time.RFC3339, *temp.ExpiresAt) + if err != nil { + log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) + } + p.ExpiresAt = &ExpiresAtVal + } + p.LastInviteSentAt.ShouldSetValue(temp.LastInviteSentAt.IsValueSet()) + if temp.LastInviteSentAt.Value() != nil { + LastInviteSentAtVal, err := time.Parse(time.RFC3339, (*temp.LastInviteSentAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse last_invite_sent_at as % s format.", time.RFC3339) + } + p.LastInviteSentAt.SetValue(&LastInviteSentAtVal) + } + return nil +} + +// TODO +type portalManagementLink struct { + Url *string `json:"url,omitempty"` + FetchCount *int `json:"fetch_count,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + NewLinkAvailableAt *string `json:"new_link_available_at,omitempty"` + ExpiresAt *string `json:"expires_at,omitempty"` + LastInviteSentAt Optional[string] `json:"last_invite_sent_at"` } diff --git a/models/prepaid_component_price_point.go b/models/prepaid_component_price_point.go index 59532c00..879c72bd 100644 --- a/models/prepaid_component_price_point.go +++ b/models/prepaid_component_price_point.go @@ -1,67 +1,69 @@ package models import ( - "encoding/json" + "encoding/json" ) // PrepaidComponentPricePoint represents a PrepaidComponentPricePoint struct. type PrepaidComponentPricePoint struct { - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - Prices []Price `json:"prices,omitempty"` - OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + Prices []Price `json:"prices,omitempty"` + OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PrepaidComponentPricePoint. +// MarshalJSON implements the json.Marshaler interface for PrepaidComponentPricePoint. // It customizes the JSON marshaling process for PrepaidComponentPricePoint objects. func (p *PrepaidComponentPricePoint) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PrepaidComponentPricePoint object to a map representation for JSON marshaling. func (p *PrepaidComponentPricePoint) toMap() map[string]any { - structMap := make(map[string]any) - if p.Name != nil { - structMap["name"] = p.Name - } - if p.Handle != nil { - structMap["handle"] = p.Handle - } - if p.PricingScheme != nil { - structMap["pricing_scheme"] = p.PricingScheme - } - if p.Prices != nil { - structMap["prices"] = p.Prices - } - if p.OveragePricing != nil { - structMap["overage_pricing"] = p.OveragePricing.toMap() - } - return structMap + structMap := make(map[string]any) + if p.Name != nil { + structMap["name"] = p.Name + } + if p.Handle != nil { + structMap["handle"] = p.Handle + } + if p.PricingScheme != nil { + structMap["pricing_scheme"] = p.PricingScheme + } + if p.Prices != nil { + structMap["prices"] = p.Prices + } + if p.OveragePricing != nil { + structMap["overage_pricing"] = p.OveragePricing.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidComponentPricePoint. +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidComponentPricePoint. // It customizes the JSON unmarshaling process for PrepaidComponentPricePoint objects. func (p *PrepaidComponentPricePoint) UnmarshalJSON(input []byte) error { - temp := &struct { - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - Prices []Price `json:"prices,omitempty"` - OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Name = temp.Name - p.Handle = temp.Handle - p.PricingScheme = temp.PricingScheme - p.Prices = temp.Prices - p.OveragePricing = temp.OveragePricing - return nil + var temp prepaidComponentPricePoint + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Name = temp.Name + p.Handle = temp.Handle + p.PricingScheme = temp.PricingScheme + p.Prices = temp.Prices + p.OveragePricing = temp.OveragePricing + return nil +} + +// TODO +type prepaidComponentPricePoint struct { + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + Prices []Price `json:"prices,omitempty"` + OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` } diff --git a/models/prepaid_configuration.go b/models/prepaid_configuration.go index 757233da..05479ac8 100644 --- a/models/prepaid_configuration.go +++ b/models/prepaid_configuration.go @@ -1,66 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" ) // PrepaidConfiguration represents a PrepaidConfiguration struct. type PrepaidConfiguration struct { - Id *int `json:"id,omitempty"` - InitialFundingAmountInCents *int64 `json:"initial_funding_amount_in_cents,omitempty"` - ReplenishToAmountInCents *int64 `json:"replenish_to_amount_in_cents,omitempty"` - AutoReplenish *bool `json:"auto_replenish,omitempty"` - ReplenishThresholdAmountInCents *int64 `json:"replenish_threshold_amount_in_cents,omitempty"` + Id *int `json:"id,omitempty"` + InitialFundingAmountInCents *int64 `json:"initial_funding_amount_in_cents,omitempty"` + ReplenishToAmountInCents *int64 `json:"replenish_to_amount_in_cents,omitempty"` + AutoReplenish *bool `json:"auto_replenish,omitempty"` + ReplenishThresholdAmountInCents *int64 `json:"replenish_threshold_amount_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PrepaidConfiguration. +// MarshalJSON implements the json.Marshaler interface for PrepaidConfiguration. // It customizes the JSON marshaling process for PrepaidConfiguration objects. func (p *PrepaidConfiguration) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PrepaidConfiguration object to a map representation for JSON marshaling. func (p *PrepaidConfiguration) toMap() map[string]any { - structMap := make(map[string]any) - if p.Id != nil { - structMap["id"] = p.Id - } - if p.InitialFundingAmountInCents != nil { - structMap["initial_funding_amount_in_cents"] = p.InitialFundingAmountInCents - } - if p.ReplenishToAmountInCents != nil { - structMap["replenish_to_amount_in_cents"] = p.ReplenishToAmountInCents - } - if p.AutoReplenish != nil { - structMap["auto_replenish"] = p.AutoReplenish - } - if p.ReplenishThresholdAmountInCents != nil { - structMap["replenish_threshold_amount_in_cents"] = p.ReplenishThresholdAmountInCents - } - return structMap + structMap := make(map[string]any) + if p.Id != nil { + structMap["id"] = p.Id + } + if p.InitialFundingAmountInCents != nil { + structMap["initial_funding_amount_in_cents"] = p.InitialFundingAmountInCents + } + if p.ReplenishToAmountInCents != nil { + structMap["replenish_to_amount_in_cents"] = p.ReplenishToAmountInCents + } + if p.AutoReplenish != nil { + structMap["auto_replenish"] = p.AutoReplenish + } + if p.ReplenishThresholdAmountInCents != nil { + structMap["replenish_threshold_amount_in_cents"] = p.ReplenishThresholdAmountInCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidConfiguration. +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidConfiguration. // It customizes the JSON unmarshaling process for PrepaidConfiguration objects. func (p *PrepaidConfiguration) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - InitialFundingAmountInCents *int64 `json:"initial_funding_amount_in_cents,omitempty"` - ReplenishToAmountInCents *int64 `json:"replenish_to_amount_in_cents,omitempty"` - AutoReplenish *bool `json:"auto_replenish,omitempty"` - ReplenishThresholdAmountInCents *int64 `json:"replenish_threshold_amount_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Id = temp.Id - p.InitialFundingAmountInCents = temp.InitialFundingAmountInCents - p.ReplenishToAmountInCents = temp.ReplenishToAmountInCents - p.AutoReplenish = temp.AutoReplenish - p.ReplenishThresholdAmountInCents = temp.ReplenishThresholdAmountInCents - return nil + var temp prepaidConfiguration + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Id = temp.Id + p.InitialFundingAmountInCents = temp.InitialFundingAmountInCents + p.ReplenishToAmountInCents = temp.ReplenishToAmountInCents + p.AutoReplenish = temp.AutoReplenish + p.ReplenishThresholdAmountInCents = temp.ReplenishThresholdAmountInCents + return nil +} + +// TODO +type prepaidConfiguration struct { + Id *int `json:"id,omitempty"` + InitialFundingAmountInCents *int64 `json:"initial_funding_amount_in_cents,omitempty"` + ReplenishToAmountInCents *int64 `json:"replenish_to_amount_in_cents,omitempty"` + AutoReplenish *bool `json:"auto_replenish,omitempty"` + ReplenishThresholdAmountInCents *int64 `json:"replenish_threshold_amount_in_cents,omitempty"` } diff --git a/models/prepaid_configuration_response.go b/models/prepaid_configuration_response.go index 92dd6637..4a33ac66 100644 --- a/models/prepaid_configuration_response.go +++ b/models/prepaid_configuration_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // PrepaidConfigurationResponse represents a PrepaidConfigurationResponse struct. type PrepaidConfigurationResponse struct { - PrepaidConfiguration PrepaidConfiguration `json:"prepaid_configuration"` + PrepaidConfiguration PrepaidConfiguration `json:"prepaid_configuration"` } -// MarshalJSON implements the json.Marshaler interface for PrepaidConfigurationResponse. +// MarshalJSON implements the json.Marshaler interface for PrepaidConfigurationResponse. // It customizes the JSON marshaling process for PrepaidConfigurationResponse objects. func (p *PrepaidConfigurationResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PrepaidConfigurationResponse object to a map representation for JSON marshaling. func (p *PrepaidConfigurationResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["prepaid_configuration"] = p.PrepaidConfiguration.toMap() - return structMap + structMap := make(map[string]any) + structMap["prepaid_configuration"] = p.PrepaidConfiguration.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidConfigurationResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidConfigurationResponse. // It customizes the JSON unmarshaling process for PrepaidConfigurationResponse objects. func (p *PrepaidConfigurationResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - PrepaidConfiguration PrepaidConfiguration `json:"prepaid_configuration"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.PrepaidConfiguration = temp.PrepaidConfiguration - return nil + var temp prepaidConfigurationResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.PrepaidConfiguration = *temp.PrepaidConfiguration + return nil +} + +// TODO +type prepaidConfigurationResponse struct { + PrepaidConfiguration *PrepaidConfiguration `json:"prepaid_configuration"` +} + +func (p *prepaidConfigurationResponse) validate() error { + var errs []string + if p.PrepaidConfiguration == nil { + errs = append(errs, "required field `prepaid_configuration` is missing for type `Prepaid Configuration Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/prepaid_subscription_balance_changed.go b/models/prepaid_subscription_balance_changed.go new file mode 100644 index 00000000..367583ab --- /dev/null +++ b/models/prepaid_subscription_balance_changed.go @@ -0,0 +1,81 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PrepaidSubscriptionBalanceChanged represents a PrepaidSubscriptionBalanceChanged struct. +type PrepaidSubscriptionBalanceChanged struct { + Reason string `json:"reason"` + CurrentAccountBalanceInCents int64 `json:"current_account_balance_in_cents"` + PrepaymentAccountBalanceInCents int64 `json:"prepayment_account_balance_in_cents"` + CurrentUsageAmountInCents int64 `json:"current_usage_amount_in_cents"` +} + +// MarshalJSON implements the json.Marshaler interface for PrepaidSubscriptionBalanceChanged. +// It customizes the JSON marshaling process for PrepaidSubscriptionBalanceChanged objects. +func (p *PrepaidSubscriptionBalanceChanged) MarshalJSON() ( + []byte, + error) { + return json.Marshal(p.toMap()) +} + +// toMap converts the PrepaidSubscriptionBalanceChanged object to a map representation for JSON marshaling. +func (p *PrepaidSubscriptionBalanceChanged) toMap() map[string]any { + structMap := make(map[string]any) + structMap["reason"] = p.Reason + structMap["current_account_balance_in_cents"] = p.CurrentAccountBalanceInCents + structMap["prepayment_account_balance_in_cents"] = p.PrepaymentAccountBalanceInCents + structMap["current_usage_amount_in_cents"] = p.CurrentUsageAmountInCents + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidSubscriptionBalanceChanged. +// It customizes the JSON unmarshaling process for PrepaidSubscriptionBalanceChanged objects. +func (p *PrepaidSubscriptionBalanceChanged) UnmarshalJSON(input []byte) error { + var temp prepaidSubscriptionBalanceChanged + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.Reason = *temp.Reason + p.CurrentAccountBalanceInCents = *temp.CurrentAccountBalanceInCents + p.PrepaymentAccountBalanceInCents = *temp.PrepaymentAccountBalanceInCents + p.CurrentUsageAmountInCents = *temp.CurrentUsageAmountInCents + return nil +} + +// TODO +type prepaidSubscriptionBalanceChanged struct { + Reason *string `json:"reason"` + CurrentAccountBalanceInCents *int64 `json:"current_account_balance_in_cents"` + PrepaymentAccountBalanceInCents *int64 `json:"prepayment_account_balance_in_cents"` + CurrentUsageAmountInCents *int64 `json:"current_usage_amount_in_cents"` +} + +func (p *prepaidSubscriptionBalanceChanged) validate() error { + var errs []string + if p.Reason == nil { + errs = append(errs, "required field `reason` is missing for type `Prepaid Subscription Balance Changed`") + } + if p.CurrentAccountBalanceInCents == nil { + errs = append(errs, "required field `current_account_balance_in_cents` is missing for type `Prepaid Subscription Balance Changed`") + } + if p.PrepaymentAccountBalanceInCents == nil { + errs = append(errs, "required field `prepayment_account_balance_in_cents` is missing for type `Prepaid Subscription Balance Changed`") + } + if p.CurrentUsageAmountInCents == nil { + errs = append(errs, "required field `current_usage_amount_in_cents` is missing for type `Prepaid Subscription Balance Changed`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/prepaid_usage.go b/models/prepaid_usage.go new file mode 100644 index 00000000..1269d6e6 --- /dev/null +++ b/models/prepaid_usage.go @@ -0,0 +1,123 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PrepaidUsage represents a PrepaidUsage struct. +type PrepaidUsage struct { + PreviousUnitBalance string `json:"previous_unit_balance"` + PreviousOverageUnitBalance string `json:"previous_overage_unit_balance"` + NewUnitBalance int `json:"new_unit_balance"` + NewOverageUnitBalance int `json:"new_overage_unit_balance"` + UsageQuantity int `json:"usage_quantity"` + OverageUsageQuantity int `json:"overage_usage_quantity"` + ComponentId int `json:"component_id"` + ComponentHandle string `json:"component_handle"` + Memo string `json:"memo"` + AllocationDetails []PrepaidUsageAllocationDetail `json:"allocation_details"` +} + +// MarshalJSON implements the json.Marshaler interface for PrepaidUsage. +// It customizes the JSON marshaling process for PrepaidUsage objects. +func (p *PrepaidUsage) MarshalJSON() ( + []byte, + error) { + return json.Marshal(p.toMap()) +} + +// toMap converts the PrepaidUsage object to a map representation for JSON marshaling. +func (p *PrepaidUsage) toMap() map[string]any { + structMap := make(map[string]any) + structMap["previous_unit_balance"] = p.PreviousUnitBalance + structMap["previous_overage_unit_balance"] = p.PreviousOverageUnitBalance + structMap["new_unit_balance"] = p.NewUnitBalance + structMap["new_overage_unit_balance"] = p.NewOverageUnitBalance + structMap["usage_quantity"] = p.UsageQuantity + structMap["overage_usage_quantity"] = p.OverageUsageQuantity + structMap["component_id"] = p.ComponentId + structMap["component_handle"] = p.ComponentHandle + structMap["memo"] = p.Memo + structMap["allocation_details"] = p.AllocationDetails + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidUsage. +// It customizes the JSON unmarshaling process for PrepaidUsage objects. +func (p *PrepaidUsage) UnmarshalJSON(input []byte) error { + var temp prepaidUsage + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.PreviousUnitBalance = *temp.PreviousUnitBalance + p.PreviousOverageUnitBalance = *temp.PreviousOverageUnitBalance + p.NewUnitBalance = *temp.NewUnitBalance + p.NewOverageUnitBalance = *temp.NewOverageUnitBalance + p.UsageQuantity = *temp.UsageQuantity + p.OverageUsageQuantity = *temp.OverageUsageQuantity + p.ComponentId = *temp.ComponentId + p.ComponentHandle = *temp.ComponentHandle + p.Memo = *temp.Memo + p.AllocationDetails = *temp.AllocationDetails + return nil +} + +// TODO +type prepaidUsage struct { + PreviousUnitBalance *string `json:"previous_unit_balance"` + PreviousOverageUnitBalance *string `json:"previous_overage_unit_balance"` + NewUnitBalance *int `json:"new_unit_balance"` + NewOverageUnitBalance *int `json:"new_overage_unit_balance"` + UsageQuantity *int `json:"usage_quantity"` + OverageUsageQuantity *int `json:"overage_usage_quantity"` + ComponentId *int `json:"component_id"` + ComponentHandle *string `json:"component_handle"` + Memo *string `json:"memo"` + AllocationDetails *[]PrepaidUsageAllocationDetail `json:"allocation_details"` +} + +func (p *prepaidUsage) validate() error { + var errs []string + if p.PreviousUnitBalance == nil { + errs = append(errs, "required field `previous_unit_balance` is missing for type `Prepaid Usage`") + } + if p.PreviousOverageUnitBalance == nil { + errs = append(errs, "required field `previous_overage_unit_balance` is missing for type `Prepaid Usage`") + } + if p.NewUnitBalance == nil { + errs = append(errs, "required field `new_unit_balance` is missing for type `Prepaid Usage`") + } + if p.NewOverageUnitBalance == nil { + errs = append(errs, "required field `new_overage_unit_balance` is missing for type `Prepaid Usage`") + } + if p.UsageQuantity == nil { + errs = append(errs, "required field `usage_quantity` is missing for type `Prepaid Usage`") + } + if p.OverageUsageQuantity == nil { + errs = append(errs, "required field `overage_usage_quantity` is missing for type `Prepaid Usage`") + } + if p.ComponentId == nil { + errs = append(errs, "required field `component_id` is missing for type `Prepaid Usage`") + } + if p.ComponentHandle == nil { + errs = append(errs, "required field `component_handle` is missing for type `Prepaid Usage`") + } + if p.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Prepaid Usage`") + } + if p.AllocationDetails == nil { + errs = append(errs, "required field `allocation_details` is missing for type `Prepaid Usage`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/prepaid_usage_allocation_detail.go b/models/prepaid_usage_allocation_detail.go new file mode 100644 index 00000000..f4f8eec0 --- /dev/null +++ b/models/prepaid_usage_allocation_detail.go @@ -0,0 +1,56 @@ +package models + +import ( + "encoding/json" +) + +// PrepaidUsageAllocationDetail represents a PrepaidUsageAllocationDetail struct. +type PrepaidUsageAllocationDetail struct { + AllocationId *int `json:"allocation_id,omitempty"` + ChargeId *int `json:"charge_id,omitempty"` + UsageQuantity *int `json:"usage_quantity,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for PrepaidUsageAllocationDetail. +// It customizes the JSON marshaling process for PrepaidUsageAllocationDetail objects. +func (p *PrepaidUsageAllocationDetail) MarshalJSON() ( + []byte, + error) { + return json.Marshal(p.toMap()) +} + +// toMap converts the PrepaidUsageAllocationDetail object to a map representation for JSON marshaling. +func (p *PrepaidUsageAllocationDetail) toMap() map[string]any { + structMap := make(map[string]any) + if p.AllocationId != nil { + structMap["allocation_id"] = p.AllocationId + } + if p.ChargeId != nil { + structMap["charge_id"] = p.ChargeId + } + if p.UsageQuantity != nil { + structMap["usage_quantity"] = p.UsageQuantity + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidUsageAllocationDetail. +// It customizes the JSON unmarshaling process for PrepaidUsageAllocationDetail objects. +func (p *PrepaidUsageAllocationDetail) UnmarshalJSON(input []byte) error { + var temp prepaidUsageAllocationDetail + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.AllocationId = temp.AllocationId + p.ChargeId = temp.ChargeId + p.UsageQuantity = temp.UsageQuantity + return nil +} + +// TODO +type prepaidUsageAllocationDetail struct { + AllocationId *int `json:"allocation_id,omitempty"` + ChargeId *int `json:"charge_id,omitempty"` + UsageQuantity *int `json:"usage_quantity,omitempty"` +} diff --git a/models/prepaid_usage_component.go b/models/prepaid_usage_component.go index 4e4d2846..7f3cd660 100644 --- a/models/prepaid_usage_component.go +++ b/models/prepaid_usage_component.go @@ -1,184 +1,212 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // PrepaidUsageComponent represents a PrepaidUsageComponent struct. type PrepaidUsageComponent struct { - // A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". - Name string `json:"name"` - // The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item - UnitName *string `json:"unit_name,omitempty"` - // A description for the component that will be displayed to the user on the hosted signup page. - Description *string `json:"description,omitempty"` - // A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'. - Handle *string `json:"handle,omitempty"` - // Boolean flag describing whether a component is taxable or not. - Taxable *bool `json:"taxable,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - // (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#general-price-bracket-rules) for an overview of how price brackets work for different pricing schemes. - Prices []Price `json:"prices,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePoints []PrepaidComponentPricePoint `json:"price_points,omitempty"` - // The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 - UnitPrice *interface{} `json:"unit_price,omitempty"` - // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. - TaxCode *string `json:"tax_code,omitempty"` - // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - // deprecated May 2011 - use unit_price instead - PriceInCents *string `json:"price_in_cents,omitempty"` - OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` - // Boolean which controls whether or not remaining units should be rolled over to the next period - RolloverPrepaidRemainder *bool `json:"rollover_prepaid_remainder,omitempty"` - // Boolean which controls whether or not the allocated quantity should be renewed at the beginning of each period - RenewPrepaidAllocation *bool `json:"renew_prepaid_allocation,omitempty"` - // (only for prepaid usage components where rollover_prepaid_remainder is true) The number of `expiration_interval_unit`s after which rollover amounts should expire - ExpirationInterval *float64 `json:"expiration_interval,omitempty"` - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` + // A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". + Name string `json:"name"` + // The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item + UnitName *string `json:"unit_name,omitempty"` + // A description for the component that will be displayed to the user on the hosted signup page. + Description *string `json:"description,omitempty"` + // A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'. + Handle *string `json:"handle,omitempty"` + // Boolean flag describing whether a component is taxable or not. + Taxable *bool `json:"taxable,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + // (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#general-price-bracket-rules) for an overview of how price brackets work for different pricing schemes. + Prices []Price `json:"prices,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePoints []PrepaidComponentPricePoint `json:"price_points,omitempty"` + // The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 + UnitPrice *PrepaidUsageComponentUnitPrice `json:"unit_price,omitempty"` + // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. + TaxCode *string `json:"tax_code,omitempty"` + // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + // deprecated May 2011 - use unit_price instead + PriceInCents *string `json:"price_in_cents,omitempty"` + OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` + // Boolean which controls whether or not remaining units should be rolled over to the next period + RolloverPrepaidRemainder *bool `json:"rollover_prepaid_remainder,omitempty"` + // Boolean which controls whether or not the allocated quantity should be renewed at the beginning of each period + RenewPrepaidAllocation *bool `json:"renew_prepaid_allocation,omitempty"` + // (only for prepaid usage components where rollover_prepaid_remainder is true) The number of `expiration_interval_unit`s after which rollover amounts should expire + ExpirationInterval *float64 `json:"expiration_interval,omitempty"` + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PrepaidUsageComponent. +// MarshalJSON implements the json.Marshaler interface for PrepaidUsageComponent. // It customizes the JSON marshaling process for PrepaidUsageComponent objects. func (p *PrepaidUsageComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PrepaidUsageComponent object to a map representation for JSON marshaling. func (p *PrepaidUsageComponent) toMap() map[string]any { - structMap := make(map[string]any) - structMap["name"] = p.Name - if p.UnitName != nil { - structMap["unit_name"] = p.UnitName - } - if p.Description != nil { - structMap["description"] = p.Description - } - if p.Handle != nil { - structMap["handle"] = p.Handle - } - if p.Taxable != nil { - structMap["taxable"] = p.Taxable - } - if p.PricingScheme != nil { - structMap["pricing_scheme"] = p.PricingScheme - } - if p.Prices != nil { - structMap["prices"] = p.Prices - } - if p.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = p.UpgradeCharge.Value() - } - if p.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = p.DowngradeCredit.Value() - } - if p.PricePoints != nil { - structMap["price_points"] = p.PricePoints - } - if p.UnitPrice != nil { - structMap["unit_price"] = p.UnitPrice - } - if p.TaxCode != nil { - structMap["tax_code"] = p.TaxCode - } - if p.HideDateRangeOnInvoice != nil { - structMap["hide_date_range_on_invoice"] = p.HideDateRangeOnInvoice - } - if p.PriceInCents != nil { - structMap["price_in_cents"] = p.PriceInCents - } - if p.OveragePricing != nil { - structMap["overage_pricing"] = p.OveragePricing.toMap() - } - if p.RolloverPrepaidRemainder != nil { - structMap["rollover_prepaid_remainder"] = p.RolloverPrepaidRemainder - } - if p.RenewPrepaidAllocation != nil { - structMap["renew_prepaid_allocation"] = p.RenewPrepaidAllocation - } - if p.ExpirationInterval != nil { - structMap["expiration_interval"] = p.ExpirationInterval - } - if p.ExpirationIntervalUnit != nil { - structMap["expiration_interval_unit"] = p.ExpirationIntervalUnit - } - if p.DisplayOnHostedPage != nil { - structMap["display_on_hosted_page"] = p.DisplayOnHostedPage - } - if p.AllowFractionalQuantities != nil { - structMap["allow_fractional_quantities"] = p.AllowFractionalQuantities - } - if p.PublicSignupPageIds != nil { - structMap["public_signup_page_ids"] = p.PublicSignupPageIds - } - return structMap + structMap := make(map[string]any) + structMap["name"] = p.Name + if p.UnitName != nil { + structMap["unit_name"] = p.UnitName + } + if p.Description != nil { + structMap["description"] = p.Description + } + if p.Handle != nil { + structMap["handle"] = p.Handle + } + if p.Taxable != nil { + structMap["taxable"] = p.Taxable + } + if p.PricingScheme != nil { + structMap["pricing_scheme"] = p.PricingScheme + } + if p.Prices != nil { + structMap["prices"] = p.Prices + } + if p.UpgradeCharge.IsValueSet() { + if p.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = p.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if p.DowngradeCredit.IsValueSet() { + if p.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = p.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if p.PricePoints != nil { + structMap["price_points"] = p.PricePoints + } + if p.UnitPrice != nil { + structMap["unit_price"] = p.UnitPrice.toMap() + } + if p.TaxCode != nil { + structMap["tax_code"] = p.TaxCode + } + if p.HideDateRangeOnInvoice != nil { + structMap["hide_date_range_on_invoice"] = p.HideDateRangeOnInvoice + } + if p.PriceInCents != nil { + structMap["price_in_cents"] = p.PriceInCents + } + if p.OveragePricing != nil { + structMap["overage_pricing"] = p.OveragePricing.toMap() + } + if p.RolloverPrepaidRemainder != nil { + structMap["rollover_prepaid_remainder"] = p.RolloverPrepaidRemainder + } + if p.RenewPrepaidAllocation != nil { + structMap["renew_prepaid_allocation"] = p.RenewPrepaidAllocation + } + if p.ExpirationInterval != nil { + structMap["expiration_interval"] = p.ExpirationInterval + } + if p.ExpirationIntervalUnit != nil { + structMap["expiration_interval_unit"] = p.ExpirationIntervalUnit + } + if p.DisplayOnHostedPage != nil { + structMap["display_on_hosted_page"] = p.DisplayOnHostedPage + } + if p.AllowFractionalQuantities != nil { + structMap["allow_fractional_quantities"] = p.AllowFractionalQuantities + } + if p.PublicSignupPageIds != nil { + structMap["public_signup_page_ids"] = p.PublicSignupPageIds + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidUsageComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidUsageComponent. // It customizes the JSON unmarshaling process for PrepaidUsageComponent objects. func (p *PrepaidUsageComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - Name string `json:"name"` - UnitName *string `json:"unit_name,omitempty"` - Description *string `json:"description,omitempty"` - Handle *string `json:"handle,omitempty"` - Taxable *bool `json:"taxable,omitempty"` - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - Prices []Price `json:"prices,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePoints []PrepaidComponentPricePoint `json:"price_points,omitempty"` - UnitPrice *interface{} `json:"unit_price,omitempty"` - TaxCode *string `json:"tax_code,omitempty"` - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - PriceInCents *string `json:"price_in_cents,omitempty"` - OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` - RolloverPrepaidRemainder *bool `json:"rollover_prepaid_remainder,omitempty"` - RenewPrepaidAllocation *bool `json:"renew_prepaid_allocation,omitempty"` - ExpirationInterval *float64 `json:"expiration_interval,omitempty"` - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Name = temp.Name - p.UnitName = temp.UnitName - p.Description = temp.Description - p.Handle = temp.Handle - p.Taxable = temp.Taxable - p.PricingScheme = temp.PricingScheme - p.Prices = temp.Prices - p.UpgradeCharge = temp.UpgradeCharge - p.DowngradeCredit = temp.DowngradeCredit - p.PricePoints = temp.PricePoints - p.UnitPrice = temp.UnitPrice - p.TaxCode = temp.TaxCode - p.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice - p.PriceInCents = temp.PriceInCents - p.OveragePricing = temp.OveragePricing - p.RolloverPrepaidRemainder = temp.RolloverPrepaidRemainder - p.RenewPrepaidAllocation = temp.RenewPrepaidAllocation - p.ExpirationInterval = temp.ExpirationInterval - p.ExpirationIntervalUnit = temp.ExpirationIntervalUnit - p.DisplayOnHostedPage = temp.DisplayOnHostedPage - p.AllowFractionalQuantities = temp.AllowFractionalQuantities - p.PublicSignupPageIds = temp.PublicSignupPageIds - return nil + var temp prepaidUsageComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.Name = *temp.Name + p.UnitName = temp.UnitName + p.Description = temp.Description + p.Handle = temp.Handle + p.Taxable = temp.Taxable + p.PricingScheme = temp.PricingScheme + p.Prices = temp.Prices + p.UpgradeCharge = temp.UpgradeCharge + p.DowngradeCredit = temp.DowngradeCredit + p.PricePoints = temp.PricePoints + p.UnitPrice = temp.UnitPrice + p.TaxCode = temp.TaxCode + p.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice + p.PriceInCents = temp.PriceInCents + p.OveragePricing = temp.OveragePricing + p.RolloverPrepaidRemainder = temp.RolloverPrepaidRemainder + p.RenewPrepaidAllocation = temp.RenewPrepaidAllocation + p.ExpirationInterval = temp.ExpirationInterval + p.ExpirationIntervalUnit = temp.ExpirationIntervalUnit + p.DisplayOnHostedPage = temp.DisplayOnHostedPage + p.AllowFractionalQuantities = temp.AllowFractionalQuantities + p.PublicSignupPageIds = temp.PublicSignupPageIds + return nil +} + +// TODO +type prepaidUsageComponent struct { + Name *string `json:"name"` + UnitName *string `json:"unit_name,omitempty"` + Description *string `json:"description,omitempty"` + Handle *string `json:"handle,omitempty"` + Taxable *bool `json:"taxable,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + Prices []Price `json:"prices,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePoints []PrepaidComponentPricePoint `json:"price_points,omitempty"` + UnitPrice *PrepaidUsageComponentUnitPrice `json:"unit_price,omitempty"` + TaxCode *string `json:"tax_code,omitempty"` + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + PriceInCents *string `json:"price_in_cents,omitempty"` + OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` + RolloverPrepaidRemainder *bool `json:"rollover_prepaid_remainder,omitempty"` + RenewPrepaidAllocation *bool `json:"renew_prepaid_allocation,omitempty"` + ExpirationInterval *float64 `json:"expiration_interval,omitempty"` + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` +} + +func (p *prepaidUsageComponent) validate() error { + var errs []string + if p.Name == nil { + errs = append(errs, "required field `name` is missing for type `Prepaid Usage Component`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/prepaid_usage_component_unit_price.go b/models/prepaid_usage_component_unit_price.go new file mode 100644 index 00000000..c477f2fb --- /dev/null +++ b/models/prepaid_usage_component_unit_price.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PrepaidUsageComponentUnitPrice represents a PrepaidUsageComponentUnitPrice struct. +// This is a container for one-of cases. +type PrepaidUsageComponentUnitPrice struct { + value any + isString bool + isPrecision bool +} + +// String converts the PrepaidUsageComponentUnitPrice object to a string representation. +func (p PrepaidUsageComponentUnitPrice) String() string { + if bytes, err := json.Marshal(p.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for PrepaidUsageComponentUnitPrice. +// It customizes the JSON marshaling process for PrepaidUsageComponentUnitPrice objects. +func (p *PrepaidUsageComponentUnitPrice) MarshalJSON() ( + []byte, + error) { + if p.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.PrepaidUsageComponentUnitPriceContainer.From*` functions to initialize the PrepaidUsageComponentUnitPrice object.") + } + return json.Marshal(p.toMap()) +} + +// toMap converts the PrepaidUsageComponentUnitPrice object to a map representation for JSON marshaling. +func (p *PrepaidUsageComponentUnitPrice) toMap() any { + switch obj := p.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaidUsageComponentUnitPrice. +// It customizes the JSON unmarshaling process for PrepaidUsageComponentUnitPrice objects. +func (p *PrepaidUsageComponentUnitPrice) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &p.isString), + NewTypeHolder(new(float64), false, &p.isPrecision), + ) + + p.value = result + return err +} + +func (p *PrepaidUsageComponentUnitPrice) AsString() ( + *string, + bool) { + if !p.isString { + return nil, false + } + return p.value.(*string), true +} + +func (p *PrepaidUsageComponentUnitPrice) AsPrecision() ( + *float64, + bool) { + if !p.isPrecision { + return nil, false + } + return p.value.(*float64), true +} + +// internalPrepaidUsageComponentUnitPrice represents a prepaidUsageComponentUnitPrice struct. +// This is a container for one-of cases. +type internalPrepaidUsageComponentUnitPrice struct{} + +var PrepaidUsageComponentUnitPriceContainer internalPrepaidUsageComponentUnitPrice + +func (p *internalPrepaidUsageComponentUnitPrice) FromString(val string) PrepaidUsageComponentUnitPrice { + return PrepaidUsageComponentUnitPrice{value: &val} +} + +func (p *internalPrepaidUsageComponentUnitPrice) FromPrecision(val float64) PrepaidUsageComponentUnitPrice { + return PrepaidUsageComponentUnitPrice{value: &val} +} diff --git a/models/prepayment.go b/models/prepayment.go index 19946c27..7cb0f0e7 100644 --- a/models/prepayment.go +++ b/models/prepayment.go @@ -1,89 +1,127 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "errors" + "log" + "strings" + "time" ) // Prepayment represents a Prepayment struct. type Prepayment struct { - Id int `json:"id"` - SubscriptionId int `json:"subscription_id"` - AmountInCents int64 `json:"amount_in_cents"` - RemainingAmountInCents int64 `json:"remaining_amount_in_cents"` - RefundedAmountInCents *int64 `json:"refunded_amount_in_cents,omitempty"` - Details *string `json:"details,omitempty"` - External bool `json:"external"` - Memo string `json:"memo"` - // The payment type of the prepayment. - PaymentType *PrepaymentMethod `json:"payment_type,omitempty"` - CreatedAt time.Time `json:"created_at"` + Id int `json:"id"` + SubscriptionId int `json:"subscription_id"` + AmountInCents int64 `json:"amount_in_cents"` + RemainingAmountInCents int64 `json:"remaining_amount_in_cents"` + RefundedAmountInCents *int64 `json:"refunded_amount_in_cents,omitempty"` + Details *string `json:"details,omitempty"` + External bool `json:"external"` + Memo string `json:"memo"` + // The payment type of the prepayment. + PaymentType *PrepaymentMethod `json:"payment_type,omitempty"` + CreatedAt time.Time `json:"created_at"` } -// MarshalJSON implements the json.Marshaler interface for Prepayment. +// MarshalJSON implements the json.Marshaler interface for Prepayment. // It customizes the JSON marshaling process for Prepayment objects. func (p *Prepayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the Prepayment object to a map representation for JSON marshaling. func (p *Prepayment) toMap() map[string]any { - structMap := make(map[string]any) - structMap["id"] = p.Id - structMap["subscription_id"] = p.SubscriptionId - structMap["amount_in_cents"] = p.AmountInCents - structMap["remaining_amount_in_cents"] = p.RemainingAmountInCents - if p.RefundedAmountInCents != nil { - structMap["refunded_amount_in_cents"] = p.RefundedAmountInCents - } - if p.Details != nil { - structMap["details"] = p.Details - } - structMap["external"] = p.External - structMap["memo"] = p.Memo - if p.PaymentType != nil { - structMap["payment_type"] = p.PaymentType - } - structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) - return structMap + structMap := make(map[string]any) + structMap["id"] = p.Id + structMap["subscription_id"] = p.SubscriptionId + structMap["amount_in_cents"] = p.AmountInCents + structMap["remaining_amount_in_cents"] = p.RemainingAmountInCents + if p.RefundedAmountInCents != nil { + structMap["refunded_amount_in_cents"] = p.RefundedAmountInCents + } + if p.Details != nil { + structMap["details"] = p.Details + } + structMap["external"] = p.External + structMap["memo"] = p.Memo + if p.PaymentType != nil { + structMap["payment_type"] = p.PaymentType + } + structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Prepayment. +// UnmarshalJSON implements the json.Unmarshaler interface for Prepayment. // It customizes the JSON unmarshaling process for Prepayment objects. func (p *Prepayment) UnmarshalJSON(input []byte) error { - temp := &struct { - Id int `json:"id"` - SubscriptionId int `json:"subscription_id"` - AmountInCents int64 `json:"amount_in_cents"` - RemainingAmountInCents int64 `json:"remaining_amount_in_cents"` - RefundedAmountInCents *int64 `json:"refunded_amount_in_cents,omitempty"` - Details *string `json:"details,omitempty"` - External bool `json:"external"` - Memo string `json:"memo"` - PaymentType *PrepaymentMethod `json:"payment_type,omitempty"` - CreatedAt string `json:"created_at"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Id = temp.Id - p.SubscriptionId = temp.SubscriptionId - p.AmountInCents = temp.AmountInCents - p.RemainingAmountInCents = temp.RemainingAmountInCents - p.RefundedAmountInCents = temp.RefundedAmountInCents - p.Details = temp.Details - p.External = temp.External - p.Memo = temp.Memo - p.PaymentType = temp.PaymentType - CreatedAtVal, err := time.Parse(time.RFC3339, temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - p.CreatedAt = CreatedAtVal - return nil + var temp prepayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.Id = *temp.Id + p.SubscriptionId = *temp.SubscriptionId + p.AmountInCents = *temp.AmountInCents + p.RemainingAmountInCents = *temp.RemainingAmountInCents + p.RefundedAmountInCents = temp.RefundedAmountInCents + p.Details = temp.Details + p.External = *temp.External + p.Memo = *temp.Memo + p.PaymentType = temp.PaymentType + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + p.CreatedAt = CreatedAtVal + return nil +} + +// TODO +type prepayment struct { + Id *int `json:"id"` + SubscriptionId *int `json:"subscription_id"` + AmountInCents *int64 `json:"amount_in_cents"` + RemainingAmountInCents *int64 `json:"remaining_amount_in_cents"` + RefundedAmountInCents *int64 `json:"refunded_amount_in_cents,omitempty"` + Details *string `json:"details,omitempty"` + External *bool `json:"external"` + Memo *string `json:"memo"` + PaymentType *PrepaymentMethod `json:"payment_type,omitempty"` + CreatedAt *string `json:"created_at"` +} + +func (p *prepayment) validate() error { + var errs []string + if p.Id == nil { + errs = append(errs, "required field `id` is missing for type `Prepayment`") + } + if p.SubscriptionId == nil { + errs = append(errs, "required field `subscription_id` is missing for type `Prepayment`") + } + if p.AmountInCents == nil { + errs = append(errs, "required field `amount_in_cents` is missing for type `Prepayment`") + } + if p.RemainingAmountInCents == nil { + errs = append(errs, "required field `remaining_amount_in_cents` is missing for type `Prepayment`") + } + if p.External == nil { + errs = append(errs, "required field `external` is missing for type `Prepayment`") + } + if p.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Prepayment`") + } + if p.CreatedAt == nil { + errs = append(errs, "required field `created_at` is missing for type `Prepayment`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/prepayment_account_balance_changed.go b/models/prepayment_account_balance_changed.go new file mode 100644 index 00000000..3402dabd --- /dev/null +++ b/models/prepayment_account_balance_changed.go @@ -0,0 +1,81 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PrepaymentAccountBalanceChanged represents a PrepaymentAccountBalanceChanged struct. +type PrepaymentAccountBalanceChanged struct { + Reason string `json:"reason"` + PrepaymentAccountBalanceInCents int64 `json:"prepayment_account_balance_in_cents"` + PrepaymentBalanceChangeInCents int64 `json:"prepayment_balance_change_in_cents"` + CurrencyCode string `json:"currency_code"` +} + +// MarshalJSON implements the json.Marshaler interface for PrepaymentAccountBalanceChanged. +// It customizes the JSON marshaling process for PrepaymentAccountBalanceChanged objects. +func (p *PrepaymentAccountBalanceChanged) MarshalJSON() ( + []byte, + error) { + return json.Marshal(p.toMap()) +} + +// toMap converts the PrepaymentAccountBalanceChanged object to a map representation for JSON marshaling. +func (p *PrepaymentAccountBalanceChanged) toMap() map[string]any { + structMap := make(map[string]any) + structMap["reason"] = p.Reason + structMap["prepayment_account_balance_in_cents"] = p.PrepaymentAccountBalanceInCents + structMap["prepayment_balance_change_in_cents"] = p.PrepaymentBalanceChangeInCents + structMap["currency_code"] = p.CurrencyCode + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaymentAccountBalanceChanged. +// It customizes the JSON unmarshaling process for PrepaymentAccountBalanceChanged objects. +func (p *PrepaymentAccountBalanceChanged) UnmarshalJSON(input []byte) error { + var temp prepaymentAccountBalanceChanged + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.Reason = *temp.Reason + p.PrepaymentAccountBalanceInCents = *temp.PrepaymentAccountBalanceInCents + p.PrepaymentBalanceChangeInCents = *temp.PrepaymentBalanceChangeInCents + p.CurrencyCode = *temp.CurrencyCode + return nil +} + +// TODO +type prepaymentAccountBalanceChanged struct { + Reason *string `json:"reason"` + PrepaymentAccountBalanceInCents *int64 `json:"prepayment_account_balance_in_cents"` + PrepaymentBalanceChangeInCents *int64 `json:"prepayment_balance_change_in_cents"` + CurrencyCode *string `json:"currency_code"` +} + +func (p *prepaymentAccountBalanceChanged) validate() error { + var errs []string + if p.Reason == nil { + errs = append(errs, "required field `reason` is missing for type `Prepayment Account Balance Changed`") + } + if p.PrepaymentAccountBalanceInCents == nil { + errs = append(errs, "required field `prepayment_account_balance_in_cents` is missing for type `Prepayment Account Balance Changed`") + } + if p.PrepaymentBalanceChangeInCents == nil { + errs = append(errs, "required field `prepayment_balance_change_in_cents` is missing for type `Prepayment Account Balance Changed`") + } + if p.CurrencyCode == nil { + errs = append(errs, "required field `currency_code` is missing for type `Prepayment Account Balance Changed`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/prepayment_aggregated_error.go b/models/prepayment_aggregated_error.go index 56a09066..a825af77 100644 --- a/models/prepayment_aggregated_error.go +++ b/models/prepayment_aggregated_error.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // PrepaymentAggregatedError represents a PrepaymentAggregatedError struct. type PrepaymentAggregatedError struct { - AmountInCents []string `json:"amount_in_cents,omitempty"` - Base []string `json:"base,omitempty"` - External []string `json:"external,omitempty"` + AmountInCents []string `json:"amount_in_cents,omitempty"` + Base []string `json:"base,omitempty"` + External []string `json:"external,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PrepaymentAggregatedError. +// MarshalJSON implements the json.Marshaler interface for PrepaymentAggregatedError. // It customizes the JSON marshaling process for PrepaymentAggregatedError objects. func (p *PrepaymentAggregatedError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PrepaymentAggregatedError object to a map representation for JSON marshaling. func (p *PrepaymentAggregatedError) toMap() map[string]any { - structMap := make(map[string]any) - if p.AmountInCents != nil { - structMap["amount_in_cents"] = p.AmountInCents - } - if p.Base != nil { - structMap["base"] = p.Base - } - if p.External != nil { - structMap["external"] = p.External - } - return structMap + structMap := make(map[string]any) + if p.AmountInCents != nil { + structMap["amount_in_cents"] = p.AmountInCents + } + if p.Base != nil { + structMap["base"] = p.Base + } + if p.External != nil { + structMap["external"] = p.External + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PrepaymentAggregatedError. +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaymentAggregatedError. // It customizes the JSON unmarshaling process for PrepaymentAggregatedError objects. func (p *PrepaymentAggregatedError) UnmarshalJSON(input []byte) error { - temp := &struct { - AmountInCents []string `json:"amount_in_cents,omitempty"` - Base []string `json:"base,omitempty"` - External []string `json:"external,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.AmountInCents = temp.AmountInCents - p.Base = temp.Base - p.External = temp.External - return nil + var temp prepaymentAggregatedError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.AmountInCents = temp.AmountInCents + p.Base = temp.Base + p.External = temp.External + return nil +} + +// TODO +type prepaymentAggregatedError struct { + AmountInCents []string `json:"amount_in_cents,omitempty"` + Base []string `json:"base,omitempty"` + External []string `json:"external,omitempty"` } diff --git a/models/prepayment_response.go b/models/prepayment_response.go index 7a4349c9..38c4d7da 100644 --- a/models/prepayment_response.go +++ b/models/prepayment_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // PrepaymentResponse represents a PrepaymentResponse struct. type PrepaymentResponse struct { - Prepayment Prepayment `json:"prepayment"` + Prepayment Prepayment `json:"prepayment"` } -// MarshalJSON implements the json.Marshaler interface for PrepaymentResponse. +// MarshalJSON implements the json.Marshaler interface for PrepaymentResponse. // It customizes the JSON marshaling process for PrepaymentResponse objects. func (p *PrepaymentResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PrepaymentResponse object to a map representation for JSON marshaling. func (p *PrepaymentResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["prepayment"] = p.Prepayment.toMap() - return structMap + structMap := make(map[string]any) + structMap["prepayment"] = p.Prepayment.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PrepaymentResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaymentResponse. // It customizes the JSON unmarshaling process for PrepaymentResponse objects. func (p *PrepaymentResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Prepayment Prepayment `json:"prepayment"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Prepayment = temp.Prepayment - return nil + var temp prepaymentResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.Prepayment = *temp.Prepayment + return nil +} + +// TODO +type prepaymentResponse struct { + Prepayment *Prepayment `json:"prepayment"` +} + +func (p *prepaymentResponse) validate() error { + var errs []string + if p.Prepayment == nil { + errs = append(errs, "required field `prepayment` is missing for type `Prepayment Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/prepayments_response.go b/models/prepayments_response.go index 9e0d219b..33de6987 100644 --- a/models/prepayments_response.go +++ b/models/prepayments_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // PrepaymentsResponse represents a PrepaymentsResponse struct. type PrepaymentsResponse struct { - Prepayments []Prepayment `json:"prepayments,omitempty"` + Prepayments []Prepayment `json:"prepayments,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PrepaymentsResponse. +// MarshalJSON implements the json.Marshaler interface for PrepaymentsResponse. // It customizes the JSON marshaling process for PrepaymentsResponse objects. func (p *PrepaymentsResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PrepaymentsResponse object to a map representation for JSON marshaling. func (p *PrepaymentsResponse) toMap() map[string]any { - structMap := make(map[string]any) - if p.Prepayments != nil { - structMap["prepayments"] = p.Prepayments - } - return structMap + structMap := make(map[string]any) + if p.Prepayments != nil { + structMap["prepayments"] = p.Prepayments + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PrepaymentsResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for PrepaymentsResponse. // It customizes the JSON unmarshaling process for PrepaymentsResponse objects. func (p *PrepaymentsResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Prepayments []Prepayment `json:"prepayments,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Prepayments = temp.Prepayments - return nil + var temp prepaymentsResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Prepayments = temp.Prepayments + return nil +} + +// TODO +type prepaymentsResponse struct { + Prepayments []Prepayment `json:"prepayments,omitempty"` } diff --git a/models/preview_allocations_request.go b/models/preview_allocations_request.go index 7770a312..47653991 100644 --- a/models/preview_allocations_request.go +++ b/models/preview_allocations_request.go @@ -1,71 +1,99 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "errors" + "log" + "strings" + "time" ) // PreviewAllocationsRequest represents a PreviewAllocationsRequest struct. type PreviewAllocationsRequest struct { - Allocations []CreateAllocation `json:"allocations"` - // To calculate proration amounts for a future time. Only within a current subscription period. Only ISO8601 format is supported. - EffectiveProrationDate *time.Time `json:"effective_proration_date,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + Allocations []CreateAllocation `json:"allocations"` + // To calculate proration amounts for a future time. Only within a current subscription period. Only ISO8601 format is supported. + EffectiveProrationDate *time.Time `json:"effective_proration_date,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` } -// MarshalJSON implements the json.Marshaler interface for PreviewAllocationsRequest. +// MarshalJSON implements the json.Marshaler interface for PreviewAllocationsRequest. // It customizes the JSON marshaling process for PreviewAllocationsRequest objects. func (p *PreviewAllocationsRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PreviewAllocationsRequest object to a map representation for JSON marshaling. func (p *PreviewAllocationsRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["allocations"] = p.Allocations - if p.EffectiveProrationDate != nil { - structMap["effective_proration_date"] = p.EffectiveProrationDate.Format(DEFAULT_DATE) - } - if p.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = p.UpgradeCharge.Value() - } - if p.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = p.DowngradeCredit.Value() - } - return structMap + structMap := make(map[string]any) + structMap["allocations"] = p.Allocations + if p.EffectiveProrationDate != nil { + structMap["effective_proration_date"] = p.EffectiveProrationDate.Format(DEFAULT_DATE) + } + if p.UpgradeCharge.IsValueSet() { + if p.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = p.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if p.DowngradeCredit.IsValueSet() { + if p.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = p.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PreviewAllocationsRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for PreviewAllocationsRequest. // It customizes the JSON unmarshaling process for PreviewAllocationsRequest objects. func (p *PreviewAllocationsRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Allocations []CreateAllocation `json:"allocations"` - EffectiveProrationDate *string `json:"effective_proration_date,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Allocations = temp.Allocations - if temp.EffectiveProrationDate != nil { - EffectiveProrationDateVal, err := time.Parse(DEFAULT_DATE, *temp.EffectiveProrationDate) - if err != nil { - log.Fatalf("Cannot Parse effective_proration_date as % s format.", DEFAULT_DATE) - } - p.EffectiveProrationDate = &EffectiveProrationDateVal - } - p.UpgradeCharge = temp.UpgradeCharge - p.DowngradeCredit = temp.DowngradeCredit - return nil + var temp previewAllocationsRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.Allocations = *temp.Allocations + if temp.EffectiveProrationDate != nil { + EffectiveProrationDateVal, err := time.Parse(DEFAULT_DATE, *temp.EffectiveProrationDate) + if err != nil { + log.Fatalf("Cannot Parse effective_proration_date as % s format.", DEFAULT_DATE) + } + p.EffectiveProrationDate = &EffectiveProrationDateVal + } + p.UpgradeCharge = temp.UpgradeCharge + p.DowngradeCredit = temp.DowngradeCredit + return nil +} + +// TODO +type previewAllocationsRequest struct { + Allocations *[]CreateAllocation `json:"allocations"` + EffectiveProrationDate *string `json:"effective_proration_date,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` +} + +func (p *previewAllocationsRequest) validate() error { + var errs []string + if p.Allocations == nil { + errs = append(errs, "required field `allocations` is missing for type `Preview Allocations Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/price.go b/models/price.go index e6387e16..493e0edc 100644 --- a/models/price.go +++ b/models/price.go @@ -1,51 +1,78 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // Price represents a Price struct. type Price struct { - StartingQuantity interface{} `json:"starting_quantity"` - EndingQuantity Optional[interface{}] `json:"ending_quantity"` - // The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 - UnitPrice interface{} `json:"unit_price"` + StartingQuantity PriceStartingQuantity `json:"starting_quantity"` + EndingQuantity Optional[PriceEndingQuantity] `json:"ending_quantity"` + // The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 + UnitPrice PriceUnitPrice `json:"unit_price"` } -// MarshalJSON implements the json.Marshaler interface for Price. +// MarshalJSON implements the json.Marshaler interface for Price. // It customizes the JSON marshaling process for Price objects. func (p *Price) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the Price object to a map representation for JSON marshaling. func (p *Price) toMap() map[string]any { - structMap := make(map[string]any) - structMap["starting_quantity"] = p.StartingQuantity - if p.EndingQuantity.IsValueSet() { - structMap["ending_quantity"] = p.EndingQuantity.Value() - } - structMap["unit_price"] = p.UnitPrice - return structMap + structMap := make(map[string]any) + structMap["starting_quantity"] = p.StartingQuantity.toMap() + if p.EndingQuantity.IsValueSet() { + if p.EndingQuantity.Value() != nil { + structMap["ending_quantity"] = p.EndingQuantity.Value().toMap() + } else { + structMap["ending_quantity"] = nil + } + } + structMap["unit_price"] = p.UnitPrice.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Price. +// UnmarshalJSON implements the json.Unmarshaler interface for Price. // It customizes the JSON unmarshaling process for Price objects. func (p *Price) UnmarshalJSON(input []byte) error { - temp := &struct { - StartingQuantity interface{} `json:"starting_quantity"` - EndingQuantity Optional[interface{}] `json:"ending_quantity"` - UnitPrice interface{} `json:"unit_price"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.StartingQuantity = temp.StartingQuantity - p.EndingQuantity = temp.EndingQuantity - p.UnitPrice = temp.UnitPrice - return nil + var temp price + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.StartingQuantity = *temp.StartingQuantity + p.EndingQuantity = temp.EndingQuantity + p.UnitPrice = *temp.UnitPrice + return nil +} + +// TODO +type price struct { + StartingQuantity *PriceStartingQuantity `json:"starting_quantity"` + EndingQuantity Optional[PriceEndingQuantity] `json:"ending_quantity"` + UnitPrice *PriceUnitPrice `json:"unit_price"` +} + +func (p *price) validate() error { + var errs []string + if p.StartingQuantity == nil { + errs = append(errs, "required field `starting_quantity` is missing for type `Price`") + } + if p.UnitPrice == nil { + errs = append(errs, "required field `unit_price` is missing for type `Price`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/price_ending_quantity.go b/models/price_ending_quantity.go new file mode 100644 index 00000000..cc6dd984 --- /dev/null +++ b/models/price_ending_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PriceEndingQuantity represents a PriceEndingQuantity struct. +// This is a container for one-of cases. +type PriceEndingQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the PriceEndingQuantity object to a string representation. +func (p PriceEndingQuantity) String() string { + if bytes, err := json.Marshal(p.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for PriceEndingQuantity. +// It customizes the JSON marshaling process for PriceEndingQuantity objects. +func (p *PriceEndingQuantity) MarshalJSON() ( + []byte, + error) { + if p.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.PriceEndingQuantityContainer.From*` functions to initialize the PriceEndingQuantity object.") + } + return json.Marshal(p.toMap()) +} + +// toMap converts the PriceEndingQuantity object to a map representation for JSON marshaling. +func (p *PriceEndingQuantity) toMap() any { + switch obj := p.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PriceEndingQuantity. +// It customizes the JSON unmarshaling process for PriceEndingQuantity objects. +func (p *PriceEndingQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &p.isNumber), + NewTypeHolder(new(string), false, &p.isString), + ) + + p.value = result + return err +} + +func (p *PriceEndingQuantity) AsNumber() ( + *int, + bool) { + if !p.isNumber { + return nil, false + } + return p.value.(*int), true +} + +func (p *PriceEndingQuantity) AsString() ( + *string, + bool) { + if !p.isString { + return nil, false + } + return p.value.(*string), true +} + +// internalPriceEndingQuantity represents a priceEndingQuantity struct. +// This is a container for one-of cases. +type internalPriceEndingQuantity struct{} + +var PriceEndingQuantityContainer internalPriceEndingQuantity + +func (p *internalPriceEndingQuantity) FromNumber(val int) PriceEndingQuantity { + return PriceEndingQuantity{value: &val} +} + +func (p *internalPriceEndingQuantity) FromString(val string) PriceEndingQuantity { + return PriceEndingQuantity{value: &val} +} diff --git a/models/price_point.go b/models/price_point.go index d4145545..342dc9d4 100644 --- a/models/price_point.go +++ b/models/price_point.go @@ -1,122 +1,124 @@ package models import ( - "encoding/json" + "encoding/json" ) // PricePoint represents a PricePoint struct. type PricePoint struct { - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - Prices []Price `json:"prices,omitempty"` - // Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` - // Whether or not the price point includes tax - TaxIncluded *bool `json:"tax_included,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` - // Boolean which controls whether or not remaining units should be rolled over to the next period - RolloverPrepaidRemainder *bool `json:"rollover_prepaid_remainder,omitempty"` - // Boolean which controls whether or not the allocated quantity should be renewed at the beginning of each period - RenewPrepaidAllocation *bool `json:"renew_prepaid_allocation,omitempty"` - // (only for prepaid usage components where rollover_prepaid_remainder is true) The number of `expiration_interval_unit`s after which rollover amounts should expire - ExpirationInterval *float64 `json:"expiration_interval,omitempty"` - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + Prices []Price `json:"prices,omitempty"` + // Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + // Whether or not the price point includes tax + TaxIncluded *bool `json:"tax_included,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` + // Boolean which controls whether or not remaining units should be rolled over to the next period + RolloverPrepaidRemainder *bool `json:"rollover_prepaid_remainder,omitempty"` + // Boolean which controls whether or not the allocated quantity should be renewed at the beginning of each period + RenewPrepaidAllocation *bool `json:"renew_prepaid_allocation,omitempty"` + // (only for prepaid usage components where rollover_prepaid_remainder is true) The number of `expiration_interval_unit`s after which rollover amounts should expire + ExpirationInterval *float64 `json:"expiration_interval,omitempty"` + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PricePoint. +// MarshalJSON implements the json.Marshaler interface for PricePoint. // It customizes the JSON marshaling process for PricePoint objects. func (p *PricePoint) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PricePoint object to a map representation for JSON marshaling. func (p *PricePoint) toMap() map[string]any { - structMap := make(map[string]any) - if p.Name != nil { - structMap["name"] = p.Name - } - if p.Handle != nil { - structMap["handle"] = p.Handle - } - if p.PricingScheme != nil { - structMap["pricing_scheme"] = p.PricingScheme - } - if p.Prices != nil { - structMap["prices"] = p.Prices - } - if p.UseSiteExchangeRate != nil { - structMap["use_site_exchange_rate"] = p.UseSiteExchangeRate - } - if p.TaxIncluded != nil { - structMap["tax_included"] = p.TaxIncluded - } - if p.Interval != nil { - structMap["interval"] = p.Interval - } - if p.IntervalUnit != nil { - structMap["interval_unit"] = p.IntervalUnit - } - if p.OveragePricing != nil { - structMap["overage_pricing"] = p.OveragePricing.toMap() - } - if p.RolloverPrepaidRemainder != nil { - structMap["rollover_prepaid_remainder"] = p.RolloverPrepaidRemainder - } - if p.RenewPrepaidAllocation != nil { - structMap["renew_prepaid_allocation"] = p.RenewPrepaidAllocation - } - if p.ExpirationInterval != nil { - structMap["expiration_interval"] = p.ExpirationInterval - } - if p.ExpirationIntervalUnit != nil { - structMap["expiration_interval_unit"] = p.ExpirationIntervalUnit - } - return structMap + structMap := make(map[string]any) + if p.Name != nil { + structMap["name"] = p.Name + } + if p.Handle != nil { + structMap["handle"] = p.Handle + } + if p.PricingScheme != nil { + structMap["pricing_scheme"] = p.PricingScheme + } + if p.Prices != nil { + structMap["prices"] = p.Prices + } + if p.UseSiteExchangeRate != nil { + structMap["use_site_exchange_rate"] = p.UseSiteExchangeRate + } + if p.TaxIncluded != nil { + structMap["tax_included"] = p.TaxIncluded + } + if p.Interval != nil { + structMap["interval"] = p.Interval + } + if p.IntervalUnit != nil { + structMap["interval_unit"] = p.IntervalUnit + } + if p.OveragePricing != nil { + structMap["overage_pricing"] = p.OveragePricing.toMap() + } + if p.RolloverPrepaidRemainder != nil { + structMap["rollover_prepaid_remainder"] = p.RolloverPrepaidRemainder + } + if p.RenewPrepaidAllocation != nil { + structMap["renew_prepaid_allocation"] = p.RenewPrepaidAllocation + } + if p.ExpirationInterval != nil { + structMap["expiration_interval"] = p.ExpirationInterval + } + if p.ExpirationIntervalUnit != nil { + structMap["expiration_interval_unit"] = p.ExpirationIntervalUnit + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PricePoint. +// UnmarshalJSON implements the json.Unmarshaler interface for PricePoint. // It customizes the JSON unmarshaling process for PricePoint objects. func (p *PricePoint) UnmarshalJSON(input []byte) error { - temp := &struct { - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - Prices []Price `json:"prices,omitempty"` - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` - TaxIncluded *bool `json:"tax_included,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` - RolloverPrepaidRemainder *bool `json:"rollover_prepaid_remainder,omitempty"` - RenewPrepaidAllocation *bool `json:"renew_prepaid_allocation,omitempty"` - ExpirationInterval *float64 `json:"expiration_interval,omitempty"` - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Name = temp.Name - p.Handle = temp.Handle - p.PricingScheme = temp.PricingScheme - p.Prices = temp.Prices - p.UseSiteExchangeRate = temp.UseSiteExchangeRate - p.TaxIncluded = temp.TaxIncluded - p.Interval = temp.Interval - p.IntervalUnit = temp.IntervalUnit - p.OveragePricing = temp.OveragePricing - p.RolloverPrepaidRemainder = temp.RolloverPrepaidRemainder - p.RenewPrepaidAllocation = temp.RenewPrepaidAllocation - p.ExpirationInterval = temp.ExpirationInterval - p.ExpirationIntervalUnit = temp.ExpirationIntervalUnit - return nil + var temp pricePoint + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Name = temp.Name + p.Handle = temp.Handle + p.PricingScheme = temp.PricingScheme + p.Prices = temp.Prices + p.UseSiteExchangeRate = temp.UseSiteExchangeRate + p.TaxIncluded = temp.TaxIncluded + p.Interval = temp.Interval + p.IntervalUnit = temp.IntervalUnit + p.OveragePricing = temp.OveragePricing + p.RolloverPrepaidRemainder = temp.RolloverPrepaidRemainder + p.RenewPrepaidAllocation = temp.RenewPrepaidAllocation + p.ExpirationInterval = temp.ExpirationInterval + p.ExpirationIntervalUnit = temp.ExpirationIntervalUnit + return nil +} + +// TODO +type pricePoint struct { + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + Prices []Price `json:"prices,omitempty"` + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + TaxIncluded *bool `json:"tax_included,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + OveragePricing *OveragePricing `json:"overage_pricing,omitempty"` + RolloverPrepaidRemainder *bool `json:"rollover_prepaid_remainder,omitempty"` + RenewPrepaidAllocation *bool `json:"renew_prepaid_allocation,omitempty"` + ExpirationInterval *float64 `json:"expiration_interval,omitempty"` + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` } diff --git a/models/price_starting_quantity.go b/models/price_starting_quantity.go new file mode 100644 index 00000000..f35762f0 --- /dev/null +++ b/models/price_starting_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PriceStartingQuantity represents a PriceStartingQuantity struct. +// This is a container for one-of cases. +type PriceStartingQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the PriceStartingQuantity object to a string representation. +func (p PriceStartingQuantity) String() string { + if bytes, err := json.Marshal(p.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for PriceStartingQuantity. +// It customizes the JSON marshaling process for PriceStartingQuantity objects. +func (p *PriceStartingQuantity) MarshalJSON() ( + []byte, + error) { + if p.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.PriceStartingQuantityContainer.From*` functions to initialize the PriceStartingQuantity object.") + } + return json.Marshal(p.toMap()) +} + +// toMap converts the PriceStartingQuantity object to a map representation for JSON marshaling. +func (p *PriceStartingQuantity) toMap() any { + switch obj := p.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PriceStartingQuantity. +// It customizes the JSON unmarshaling process for PriceStartingQuantity objects. +func (p *PriceStartingQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &p.isNumber), + NewTypeHolder(new(string), false, &p.isString), + ) + + p.value = result + return err +} + +func (p *PriceStartingQuantity) AsNumber() ( + *int, + bool) { + if !p.isNumber { + return nil, false + } + return p.value.(*int), true +} + +func (p *PriceStartingQuantity) AsString() ( + *string, + bool) { + if !p.isString { + return nil, false + } + return p.value.(*string), true +} + +// internalPriceStartingQuantity represents a priceStartingQuantity struct. +// This is a container for one-of cases. +type internalPriceStartingQuantity struct{} + +var PriceStartingQuantityContainer internalPriceStartingQuantity + +func (p *internalPriceStartingQuantity) FromNumber(val int) PriceStartingQuantity { + return PriceStartingQuantity{value: &val} +} + +func (p *internalPriceStartingQuantity) FromString(val string) PriceStartingQuantity { + return PriceStartingQuantity{value: &val} +} diff --git a/models/price_unit_price.go b/models/price_unit_price.go new file mode 100644 index 00000000..1ca699bb --- /dev/null +++ b/models/price_unit_price.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// PriceUnitPrice represents a PriceUnitPrice struct. +// This is a container for one-of cases. +type PriceUnitPrice struct { + value any + isPrecision bool + isString bool +} + +// String converts the PriceUnitPrice object to a string representation. +func (p PriceUnitPrice) String() string { + if bytes, err := json.Marshal(p.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for PriceUnitPrice. +// It customizes the JSON marshaling process for PriceUnitPrice objects. +func (p *PriceUnitPrice) MarshalJSON() ( + []byte, + error) { + if p.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.PriceUnitPriceContainer.From*` functions to initialize the PriceUnitPrice object.") + } + return json.Marshal(p.toMap()) +} + +// toMap converts the PriceUnitPrice object to a map representation for JSON marshaling. +func (p *PriceUnitPrice) toMap() any { + switch obj := p.value.(type) { + case *float64: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for PriceUnitPrice. +// It customizes the JSON unmarshaling process for PriceUnitPrice objects. +func (p *PriceUnitPrice) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(float64), false, &p.isPrecision), + NewTypeHolder(new(string), false, &p.isString), + ) + + p.value = result + return err +} + +func (p *PriceUnitPrice) AsPrecision() ( + *float64, + bool) { + if !p.isPrecision { + return nil, false + } + return p.value.(*float64), true +} + +func (p *PriceUnitPrice) AsString() ( + *string, + bool) { + if !p.isString { + return nil, false + } + return p.value.(*string), true +} + +// internalPriceUnitPrice represents a priceUnitPrice struct. +// This is a container for one-of cases. +type internalPriceUnitPrice struct{} + +var PriceUnitPriceContainer internalPriceUnitPrice + +func (p *internalPriceUnitPrice) FromPrecision(val float64) PriceUnitPrice { + return PriceUnitPrice{value: &val} +} + +func (p *internalPriceUnitPrice) FromString(val string) PriceUnitPrice { + return PriceUnitPrice{value: &val} +} diff --git a/models/product.go b/models/product.go index 7cbb1dc0..12c68e1a 100644 --- a/models/product.go +++ b/models/product.go @@ -1,310 +1,380 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Product represents a Product struct. type Product struct { - Id *int `json:"id,omitempty"` - // The product name - Name *string `json:"name,omitempty"` - // The product API handle - Handle Optional[string] `json:"handle"` - // The product description - Description Optional[string] `json:"description"` - // E.g. Internal ID or SKU Number - AccountingCode Optional[string] `json:"accounting_code"` - // Deprecated value that can be ignored unless you have legacy hosted pages. For Public Signup Page users, please read this attribute from under the signup page. - RequestCreditCard *bool `json:"request_credit_card,omitempty"` - // A numerical interval for the length a subscription to this product will run before it expires. See the description of interval for a description of how this value is coupled with an interval unit to calculate the full interval - ExpirationInterval Optional[int] `json:"expiration_interval"` - // A string representing the expiration interval unit for this product, either month or day - ExpirationIntervalUnit Optional[ExtendedIntervalUnit] `json:"expiration_interval_unit"` - // Timestamp indicating when this product was created - CreatedAt *time.Time `json:"created_at,omitempty"` - // Timestamp indicating when this product was last updated - UpdatedAt *time.Time `json:"updated_at,omitempty"` - // The product price, in integer cents - PriceInCents *int64 `json:"price_in_cents,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product would renew every 30 days - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this product, either month or day - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - // The up front charge you have specified. - InitialChargeInCents Optional[int64] `json:"initial_charge_in_cents"` - // The price of the trial period for a subscription to this product, in integer cents. - TrialPriceInCents Optional[int64] `json:"trial_price_in_cents"` - // A numerical interval for the length of the trial period of a subscription to this product. See the description of interval for a description of how this value is coupled with an interval unit to calculate the full interval - TrialInterval Optional[int] `json:"trial_interval"` - // A string representing the trial interval unit for this product, either month or day - TrialIntervalUnit Optional[IntervalUnit] `json:"trial_interval_unit"` - // Timestamp indicating when this product was archived - ArchivedAt Optional[time.Time] `json:"archived_at"` - // Boolean that controls whether a payment profile is required to be entered for customers wishing to sign up on this product. - RequireCreditCard *bool `json:"require_credit_card,omitempty"` - ReturnParams Optional[string] `json:"return_params"` - Taxable *bool `json:"taxable,omitempty"` - // The url to which a customer will be returned after a successful account update - UpdateReturnUrl Optional[string] `json:"update_return_url"` - InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` - // The version of the product - VersionNumber *int `json:"version_number,omitempty"` - // The parameters will append to the url after a successful account update. See [help documentation](https://help.chargify.com/products/product-editing.html#return-parameters-after-account-update) - UpdateReturnParams Optional[string] `json:"update_return_params"` - ProductFamily *ProductFamily `json:"product_family,omitempty"` - PublicSignupPages []PublicSignupPage `json:"public_signup_pages,omitempty"` - ProductPricePointName *string `json:"product_price_point_name,omitempty"` - // A boolean indicating whether to request a billing address on any Self-Service Pages that are used by subscribers of this product. - RequestBillingAddress *bool `json:"request_billing_address,omitempty"` - // A boolean indicating whether a billing address is required to add a payment profile, especially at signup. - RequireBillingAddress *bool `json:"require_billing_address,omitempty"` - // A boolean indicating whether a shipping address is required for the customer, especially at signup. - RequireShippingAddress *bool `json:"require_shipping_address,omitempty"` - // A string representing the tax code related to the product type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. - TaxCode Optional[string] `json:"tax_code"` - DefaultProductPricePointId *int `json:"default_product_price_point_id,omitempty"` - UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` - // One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other - ItemCategory Optional[string] `json:"item_category"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - ProductPricePointHandle Optional[string] `json:"product_price_point_handle"` + Id *int `json:"id,omitempty"` + // The product name + Name *string `json:"name,omitempty"` + // The product API handle + Handle Optional[string] `json:"handle"` + // The product description + Description Optional[string] `json:"description"` + // E.g. Internal ID or SKU Number + AccountingCode Optional[string] `json:"accounting_code"` + // Deprecated value that can be ignored unless you have legacy hosted pages. For Public Signup Page users, please read this attribute from under the signup page. + RequestCreditCard *bool `json:"request_credit_card,omitempty"` + // A numerical interval for the length a subscription to this product will run before it expires. See the description of interval for a description of how this value is coupled with an interval unit to calculate the full interval + ExpirationInterval Optional[int] `json:"expiration_interval"` + // A string representing the expiration interval unit for this product, either month or day + ExpirationIntervalUnit Optional[ProductExpirationIntervalUnit] `json:"expiration_interval_unit"` + // Timestamp indicating when this product was created + CreatedAt *time.Time `json:"created_at,omitempty"` + // Timestamp indicating when this product was last updated + UpdatedAt *time.Time `json:"updated_at,omitempty"` + // The product price, in integer cents + PriceInCents *int64 `json:"price_in_cents,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product would renew every 30 days + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this product, either month or day + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + // The up front charge you have specified. + InitialChargeInCents Optional[int64] `json:"initial_charge_in_cents"` + // The price of the trial period for a subscription to this product, in integer cents. + TrialPriceInCents Optional[int64] `json:"trial_price_in_cents"` + // A numerical interval for the length of the trial period of a subscription to this product. See the description of interval for a description of how this value is coupled with an interval unit to calculate the full interval + TrialInterval Optional[int] `json:"trial_interval"` + // A string representing the trial interval unit for this product, either month or day + TrialIntervalUnit Optional[ProductTrialIntervalUnit] `json:"trial_interval_unit"` + // Timestamp indicating when this product was archived + ArchivedAt Optional[time.Time] `json:"archived_at"` + // Boolean that controls whether a payment profile is required to be entered for customers wishing to sign up on this product. + RequireCreditCard *bool `json:"require_credit_card,omitempty"` + ReturnParams Optional[string] `json:"return_params"` + Taxable *bool `json:"taxable,omitempty"` + // The url to which a customer will be returned after a successful account update + UpdateReturnUrl Optional[string] `json:"update_return_url"` + InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` + // The version of the product + VersionNumber *int `json:"version_number,omitempty"` + // The parameters will append to the url after a successful account update. See [help documentation](https://help.chargify.com/products/product-editing.html#return-parameters-after-account-update) + UpdateReturnParams Optional[string] `json:"update_return_params"` + ProductFamily *ProductFamily `json:"product_family,omitempty"` + PublicSignupPages []PublicSignupPage `json:"public_signup_pages,omitempty"` + ProductPricePointName *string `json:"product_price_point_name,omitempty"` + // A boolean indicating whether to request a billing address on any Self-Service Pages that are used by subscribers of this product. + RequestBillingAddress *bool `json:"request_billing_address,omitempty"` + // A boolean indicating whether a billing address is required to add a payment profile, especially at signup. + RequireBillingAddress *bool `json:"require_billing_address,omitempty"` + // A boolean indicating whether a shipping address is required for the customer, especially at signup. + RequireShippingAddress *bool `json:"require_shipping_address,omitempty"` + // A string representing the tax code related to the product type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. + TaxCode Optional[string] `json:"tax_code"` + DefaultProductPricePointId *int `json:"default_product_price_point_id,omitempty"` + UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` + // One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other + ItemCategory Optional[string] `json:"item_category"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + ProductPricePointHandle Optional[string] `json:"product_price_point_handle"` } -// MarshalJSON implements the json.Marshaler interface for Product. +// MarshalJSON implements the json.Marshaler interface for Product. // It customizes the JSON marshaling process for Product objects. func (p *Product) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the Product object to a map representation for JSON marshaling. func (p *Product) toMap() map[string]any { - structMap := make(map[string]any) - if p.Id != nil { - structMap["id"] = p.Id - } - if p.Name != nil { - structMap["name"] = p.Name - } - if p.Handle.IsValueSet() { - structMap["handle"] = p.Handle.Value() - } - if p.Description.IsValueSet() { - structMap["description"] = p.Description.Value() - } - if p.AccountingCode.IsValueSet() { - structMap["accounting_code"] = p.AccountingCode.Value() - } - if p.RequestCreditCard != nil { - structMap["request_credit_card"] = p.RequestCreditCard - } - if p.ExpirationInterval.IsValueSet() { - structMap["expiration_interval"] = p.ExpirationInterval.Value() - } - if p.ExpirationIntervalUnit.IsValueSet() { - structMap["expiration_interval_unit"] = p.ExpirationIntervalUnit.Value() - } - if p.CreatedAt != nil { - structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) - } - if p.UpdatedAt != nil { - structMap["updated_at"] = p.UpdatedAt.Format(time.RFC3339) - } - if p.PriceInCents != nil { - structMap["price_in_cents"] = p.PriceInCents - } - if p.Interval != nil { - structMap["interval"] = p.Interval - } - if p.IntervalUnit != nil { - structMap["interval_unit"] = p.IntervalUnit - } - if p.InitialChargeInCents.IsValueSet() { - structMap["initial_charge_in_cents"] = p.InitialChargeInCents.Value() - } - if p.TrialPriceInCents.IsValueSet() { - structMap["trial_price_in_cents"] = p.TrialPriceInCents.Value() - } - if p.TrialInterval.IsValueSet() { - structMap["trial_interval"] = p.TrialInterval.Value() - } - if p.TrialIntervalUnit.IsValueSet() { - structMap["trial_interval_unit"] = p.TrialIntervalUnit.Value() - } - if p.ArchivedAt.IsValueSet() { - var ArchivedAtVal *string = nil - if p.ArchivedAt.Value() != nil { - val := p.ArchivedAt.Value().Format(time.RFC3339) - ArchivedAtVal = &val - } - structMap["archived_at"] = ArchivedAtVal - } - if p.RequireCreditCard != nil { - structMap["require_credit_card"] = p.RequireCreditCard - } - if p.ReturnParams.IsValueSet() { - structMap["return_params"] = p.ReturnParams.Value() - } - if p.Taxable != nil { - structMap["taxable"] = p.Taxable - } - if p.UpdateReturnUrl.IsValueSet() { - structMap["update_return_url"] = p.UpdateReturnUrl.Value() - } - if p.InitialChargeAfterTrial != nil { - structMap["initial_charge_after_trial"] = p.InitialChargeAfterTrial - } - if p.VersionNumber != nil { - structMap["version_number"] = p.VersionNumber - } - if p.UpdateReturnParams.IsValueSet() { - structMap["update_return_params"] = p.UpdateReturnParams.Value() - } - if p.ProductFamily != nil { - structMap["product_family"] = p.ProductFamily.toMap() - } - if p.PublicSignupPages != nil { - structMap["public_signup_pages"] = p.PublicSignupPages - } - if p.ProductPricePointName != nil { - structMap["product_price_point_name"] = p.ProductPricePointName - } - if p.RequestBillingAddress != nil { - structMap["request_billing_address"] = p.RequestBillingAddress - } - if p.RequireBillingAddress != nil { - structMap["require_billing_address"] = p.RequireBillingAddress - } - if p.RequireShippingAddress != nil { - structMap["require_shipping_address"] = p.RequireShippingAddress - } - if p.TaxCode.IsValueSet() { - structMap["tax_code"] = p.TaxCode.Value() - } - if p.DefaultProductPricePointId != nil { - structMap["default_product_price_point_id"] = p.DefaultProductPricePointId - } - if p.UseSiteExchangeRate.IsValueSet() { - structMap["use_site_exchange_rate"] = p.UseSiteExchangeRate.Value() - } - if p.ItemCategory.IsValueSet() { - structMap["item_category"] = p.ItemCategory.Value() - } - if p.ProductPricePointId != nil { - structMap["product_price_point_id"] = p.ProductPricePointId - } - if p.ProductPricePointHandle.IsValueSet() { - structMap["product_price_point_handle"] = p.ProductPricePointHandle.Value() - } - return structMap + structMap := make(map[string]any) + if p.Id != nil { + structMap["id"] = p.Id + } + if p.Name != nil { + structMap["name"] = p.Name + } + if p.Handle.IsValueSet() { + if p.Handle.Value() != nil { + structMap["handle"] = p.Handle.Value() + } else { + structMap["handle"] = nil + } + } + if p.Description.IsValueSet() { + if p.Description.Value() != nil { + structMap["description"] = p.Description.Value() + } else { + structMap["description"] = nil + } + } + if p.AccountingCode.IsValueSet() { + if p.AccountingCode.Value() != nil { + structMap["accounting_code"] = p.AccountingCode.Value() + } else { + structMap["accounting_code"] = nil + } + } + if p.RequestCreditCard != nil { + structMap["request_credit_card"] = p.RequestCreditCard + } + if p.ExpirationInterval.IsValueSet() { + if p.ExpirationInterval.Value() != nil { + structMap["expiration_interval"] = p.ExpirationInterval.Value() + } else { + structMap["expiration_interval"] = nil + } + } + if p.ExpirationIntervalUnit.IsValueSet() { + if p.ExpirationIntervalUnit.Value() != nil { + structMap["expiration_interval_unit"] = p.ExpirationIntervalUnit.Value().toMap() + } else { + structMap["expiration_interval_unit"] = nil + } + } + if p.CreatedAt != nil { + structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) + } + if p.UpdatedAt != nil { + structMap["updated_at"] = p.UpdatedAt.Format(time.RFC3339) + } + if p.PriceInCents != nil { + structMap["price_in_cents"] = p.PriceInCents + } + if p.Interval != nil { + structMap["interval"] = p.Interval + } + if p.IntervalUnit != nil { + structMap["interval_unit"] = p.IntervalUnit + } + if p.InitialChargeInCents.IsValueSet() { + if p.InitialChargeInCents.Value() != nil { + structMap["initial_charge_in_cents"] = p.InitialChargeInCents.Value() + } else { + structMap["initial_charge_in_cents"] = nil + } + } + if p.TrialPriceInCents.IsValueSet() { + if p.TrialPriceInCents.Value() != nil { + structMap["trial_price_in_cents"] = p.TrialPriceInCents.Value() + } else { + structMap["trial_price_in_cents"] = nil + } + } + if p.TrialInterval.IsValueSet() { + if p.TrialInterval.Value() != nil { + structMap["trial_interval"] = p.TrialInterval.Value() + } else { + structMap["trial_interval"] = nil + } + } + if p.TrialIntervalUnit.IsValueSet() { + if p.TrialIntervalUnit.Value() != nil { + structMap["trial_interval_unit"] = p.TrialIntervalUnit.Value().toMap() + } else { + structMap["trial_interval_unit"] = nil + } + } + if p.ArchivedAt.IsValueSet() { + var ArchivedAtVal *string = nil + if p.ArchivedAt.Value() != nil { + val := p.ArchivedAt.Value().Format(time.RFC3339) + ArchivedAtVal = &val + } + if p.ArchivedAt.Value() != nil { + structMap["archived_at"] = ArchivedAtVal + } else { + structMap["archived_at"] = nil + } + } + if p.RequireCreditCard != nil { + structMap["require_credit_card"] = p.RequireCreditCard + } + if p.ReturnParams.IsValueSet() { + if p.ReturnParams.Value() != nil { + structMap["return_params"] = p.ReturnParams.Value() + } else { + structMap["return_params"] = nil + } + } + if p.Taxable != nil { + structMap["taxable"] = p.Taxable + } + if p.UpdateReturnUrl.IsValueSet() { + if p.UpdateReturnUrl.Value() != nil { + structMap["update_return_url"] = p.UpdateReturnUrl.Value() + } else { + structMap["update_return_url"] = nil + } + } + if p.InitialChargeAfterTrial != nil { + structMap["initial_charge_after_trial"] = p.InitialChargeAfterTrial + } + if p.VersionNumber != nil { + structMap["version_number"] = p.VersionNumber + } + if p.UpdateReturnParams.IsValueSet() { + if p.UpdateReturnParams.Value() != nil { + structMap["update_return_params"] = p.UpdateReturnParams.Value() + } else { + structMap["update_return_params"] = nil + } + } + if p.ProductFamily != nil { + structMap["product_family"] = p.ProductFamily.toMap() + } + if p.PublicSignupPages != nil { + structMap["public_signup_pages"] = p.PublicSignupPages + } + if p.ProductPricePointName != nil { + structMap["product_price_point_name"] = p.ProductPricePointName + } + if p.RequestBillingAddress != nil { + structMap["request_billing_address"] = p.RequestBillingAddress + } + if p.RequireBillingAddress != nil { + structMap["require_billing_address"] = p.RequireBillingAddress + } + if p.RequireShippingAddress != nil { + structMap["require_shipping_address"] = p.RequireShippingAddress + } + if p.TaxCode.IsValueSet() { + if p.TaxCode.Value() != nil { + structMap["tax_code"] = p.TaxCode.Value() + } else { + structMap["tax_code"] = nil + } + } + if p.DefaultProductPricePointId != nil { + structMap["default_product_price_point_id"] = p.DefaultProductPricePointId + } + if p.UseSiteExchangeRate.IsValueSet() { + if p.UseSiteExchangeRate.Value() != nil { + structMap["use_site_exchange_rate"] = p.UseSiteExchangeRate.Value() + } else { + structMap["use_site_exchange_rate"] = nil + } + } + if p.ItemCategory.IsValueSet() { + if p.ItemCategory.Value() != nil { + structMap["item_category"] = p.ItemCategory.Value() + } else { + structMap["item_category"] = nil + } + } + if p.ProductPricePointId != nil { + structMap["product_price_point_id"] = p.ProductPricePointId + } + if p.ProductPricePointHandle.IsValueSet() { + if p.ProductPricePointHandle.Value() != nil { + structMap["product_price_point_handle"] = p.ProductPricePointHandle.Value() + } else { + structMap["product_price_point_handle"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Product. +// UnmarshalJSON implements the json.Unmarshaler interface for Product. // It customizes the JSON unmarshaling process for Product objects. func (p *Product) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Handle Optional[string] `json:"handle"` - Description Optional[string] `json:"description"` - AccountingCode Optional[string] `json:"accounting_code"` - RequestCreditCard *bool `json:"request_credit_card,omitempty"` - ExpirationInterval Optional[int] `json:"expiration_interval"` - ExpirationIntervalUnit Optional[ExtendedIntervalUnit] `json:"expiration_interval_unit"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - PriceInCents *int64 `json:"price_in_cents,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - InitialChargeInCents Optional[int64] `json:"initial_charge_in_cents"` - TrialPriceInCents Optional[int64] `json:"trial_price_in_cents"` - TrialInterval Optional[int] `json:"trial_interval"` - TrialIntervalUnit Optional[IntervalUnit] `json:"trial_interval_unit"` - ArchivedAt Optional[string] `json:"archived_at"` - RequireCreditCard *bool `json:"require_credit_card,omitempty"` - ReturnParams Optional[string] `json:"return_params"` - Taxable *bool `json:"taxable,omitempty"` - UpdateReturnUrl Optional[string] `json:"update_return_url"` - InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` - VersionNumber *int `json:"version_number,omitempty"` - UpdateReturnParams Optional[string] `json:"update_return_params"` - ProductFamily *ProductFamily `json:"product_family,omitempty"` - PublicSignupPages []PublicSignupPage `json:"public_signup_pages,omitempty"` - ProductPricePointName *string `json:"product_price_point_name,omitempty"` - RequestBillingAddress *bool `json:"request_billing_address,omitempty"` - RequireBillingAddress *bool `json:"require_billing_address,omitempty"` - RequireShippingAddress *bool `json:"require_shipping_address,omitempty"` - TaxCode Optional[string] `json:"tax_code"` - DefaultProductPricePointId *int `json:"default_product_price_point_id,omitempty"` - UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` - ItemCategory Optional[string] `json:"item_category"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - ProductPricePointHandle Optional[string] `json:"product_price_point_handle"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Id = temp.Id - p.Name = temp.Name - p.Handle = temp.Handle - p.Description = temp.Description - p.AccountingCode = temp.AccountingCode - p.RequestCreditCard = temp.RequestCreditCard - p.ExpirationInterval = temp.ExpirationInterval - p.ExpirationIntervalUnit = temp.ExpirationIntervalUnit - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - p.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - p.UpdatedAt = &UpdatedAtVal - } - p.PriceInCents = temp.PriceInCents - p.Interval = temp.Interval - p.IntervalUnit = temp.IntervalUnit - p.InitialChargeInCents = temp.InitialChargeInCents - p.TrialPriceInCents = temp.TrialPriceInCents - p.TrialInterval = temp.TrialInterval - p.TrialIntervalUnit = temp.TrialIntervalUnit - p.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) - if temp.ArchivedAt.Value() != nil { - ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) - } - p.ArchivedAt.SetValue(&ArchivedAtVal) - } - p.RequireCreditCard = temp.RequireCreditCard - p.ReturnParams = temp.ReturnParams - p.Taxable = temp.Taxable - p.UpdateReturnUrl = temp.UpdateReturnUrl - p.InitialChargeAfterTrial = temp.InitialChargeAfterTrial - p.VersionNumber = temp.VersionNumber - p.UpdateReturnParams = temp.UpdateReturnParams - p.ProductFamily = temp.ProductFamily - p.PublicSignupPages = temp.PublicSignupPages - p.ProductPricePointName = temp.ProductPricePointName - p.RequestBillingAddress = temp.RequestBillingAddress - p.RequireBillingAddress = temp.RequireBillingAddress - p.RequireShippingAddress = temp.RequireShippingAddress - p.TaxCode = temp.TaxCode - p.DefaultProductPricePointId = temp.DefaultProductPricePointId - p.UseSiteExchangeRate = temp.UseSiteExchangeRate - p.ItemCategory = temp.ItemCategory - p.ProductPricePointId = temp.ProductPricePointId - p.ProductPricePointHandle = temp.ProductPricePointHandle - return nil + var temp product + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Id = temp.Id + p.Name = temp.Name + p.Handle = temp.Handle + p.Description = temp.Description + p.AccountingCode = temp.AccountingCode + p.RequestCreditCard = temp.RequestCreditCard + p.ExpirationInterval = temp.ExpirationInterval + p.ExpirationIntervalUnit = temp.ExpirationIntervalUnit + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + p.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + p.UpdatedAt = &UpdatedAtVal + } + p.PriceInCents = temp.PriceInCents + p.Interval = temp.Interval + p.IntervalUnit = temp.IntervalUnit + p.InitialChargeInCents = temp.InitialChargeInCents + p.TrialPriceInCents = temp.TrialPriceInCents + p.TrialInterval = temp.TrialInterval + p.TrialIntervalUnit = temp.TrialIntervalUnit + p.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) + if temp.ArchivedAt.Value() != nil { + ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) + } + p.ArchivedAt.SetValue(&ArchivedAtVal) + } + p.RequireCreditCard = temp.RequireCreditCard + p.ReturnParams = temp.ReturnParams + p.Taxable = temp.Taxable + p.UpdateReturnUrl = temp.UpdateReturnUrl + p.InitialChargeAfterTrial = temp.InitialChargeAfterTrial + p.VersionNumber = temp.VersionNumber + p.UpdateReturnParams = temp.UpdateReturnParams + p.ProductFamily = temp.ProductFamily + p.PublicSignupPages = temp.PublicSignupPages + p.ProductPricePointName = temp.ProductPricePointName + p.RequestBillingAddress = temp.RequestBillingAddress + p.RequireBillingAddress = temp.RequireBillingAddress + p.RequireShippingAddress = temp.RequireShippingAddress + p.TaxCode = temp.TaxCode + p.DefaultProductPricePointId = temp.DefaultProductPricePointId + p.UseSiteExchangeRate = temp.UseSiteExchangeRate + p.ItemCategory = temp.ItemCategory + p.ProductPricePointId = temp.ProductPricePointId + p.ProductPricePointHandle = temp.ProductPricePointHandle + return nil +} + +// TODO +type product struct { + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Handle Optional[string] `json:"handle"` + Description Optional[string] `json:"description"` + AccountingCode Optional[string] `json:"accounting_code"` + RequestCreditCard *bool `json:"request_credit_card,omitempty"` + ExpirationInterval Optional[int] `json:"expiration_interval"` + ExpirationIntervalUnit Optional[ProductExpirationIntervalUnit] `json:"expiration_interval_unit"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + PriceInCents *int64 `json:"price_in_cents,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + InitialChargeInCents Optional[int64] `json:"initial_charge_in_cents"` + TrialPriceInCents Optional[int64] `json:"trial_price_in_cents"` + TrialInterval Optional[int] `json:"trial_interval"` + TrialIntervalUnit Optional[ProductTrialIntervalUnit] `json:"trial_interval_unit"` + ArchivedAt Optional[string] `json:"archived_at"` + RequireCreditCard *bool `json:"require_credit_card,omitempty"` + ReturnParams Optional[string] `json:"return_params"` + Taxable *bool `json:"taxable,omitempty"` + UpdateReturnUrl Optional[string] `json:"update_return_url"` + InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` + VersionNumber *int `json:"version_number,omitempty"` + UpdateReturnParams Optional[string] `json:"update_return_params"` + ProductFamily *ProductFamily `json:"product_family,omitempty"` + PublicSignupPages []PublicSignupPage `json:"public_signup_pages,omitempty"` + ProductPricePointName *string `json:"product_price_point_name,omitempty"` + RequestBillingAddress *bool `json:"request_billing_address,omitempty"` + RequireBillingAddress *bool `json:"require_billing_address,omitempty"` + RequireShippingAddress *bool `json:"require_shipping_address,omitempty"` + TaxCode Optional[string] `json:"tax_code"` + DefaultProductPricePointId *int `json:"default_product_price_point_id,omitempty"` + UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` + ItemCategory Optional[string] `json:"item_category"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + ProductPricePointHandle Optional[string] `json:"product_price_point_handle"` } diff --git a/models/product_expiration_interval_unit.go b/models/product_expiration_interval_unit.go new file mode 100644 index 00000000..f40f8979 --- /dev/null +++ b/models/product_expiration_interval_unit.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ProductExpirationIntervalUnit represents a ProductExpirationIntervalUnit struct. +// This is a container for one-of cases. +type ProductExpirationIntervalUnit struct { + value any + isExtendedIntervalUnit bool +} + +// String converts the ProductExpirationIntervalUnit object to a string representation. +func (p ProductExpirationIntervalUnit) String() string { + if bytes, err := json.Marshal(p.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ProductExpirationIntervalUnit. +// It customizes the JSON marshaling process for ProductExpirationIntervalUnit objects. +func (p *ProductExpirationIntervalUnit) MarshalJSON() ( + []byte, + error) { + if p.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ProductExpirationIntervalUnitContainer.From*` functions to initialize the ProductExpirationIntervalUnit object.") + } + return json.Marshal(p.toMap()) +} + +// toMap converts the ProductExpirationIntervalUnit object to a map representation for JSON marshaling. +func (p *ProductExpirationIntervalUnit) toMap() any { + switch obj := p.value.(type) { + case *ExtendedIntervalUnit: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ProductExpirationIntervalUnit. +// It customizes the JSON unmarshaling process for ProductExpirationIntervalUnit objects. +func (p *ProductExpirationIntervalUnit) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(ExtendedIntervalUnit), false, &p.isExtendedIntervalUnit), + ) + + p.value = result + return err +} + +func (p *ProductExpirationIntervalUnit) AsExtendedIntervalUnit() ( + *ExtendedIntervalUnit, + bool) { + if !p.isExtendedIntervalUnit { + return nil, false + } + return p.value.(*ExtendedIntervalUnit), true +} + +// internalProductExpirationIntervalUnit represents a productExpirationIntervalUnit struct. +// This is a container for one-of cases. +type internalProductExpirationIntervalUnit struct{} + +var ProductExpirationIntervalUnitContainer internalProductExpirationIntervalUnit + +func (p *internalProductExpirationIntervalUnit) FromExtendedIntervalUnit(val ExtendedIntervalUnit) ProductExpirationIntervalUnit { + return ProductExpirationIntervalUnit{value: &val} +} diff --git a/models/product_family.go b/models/product_family.go index 51f165c2..7e0dcee8 100644 --- a/models/product_family.go +++ b/models/product_family.go @@ -1,92 +1,102 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // ProductFamily represents a ProductFamily struct. type ProductFamily struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - AccountingCode Optional[string] `json:"accounting_code"` - Description Optional[string] `json:"description"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + AccountingCode Optional[string] `json:"accounting_code"` + Description Optional[string] `json:"description"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ProductFamily. +// MarshalJSON implements the json.Marshaler interface for ProductFamily. // It customizes the JSON marshaling process for ProductFamily objects. func (p *ProductFamily) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProductFamily object to a map representation for JSON marshaling. func (p *ProductFamily) toMap() map[string]any { - structMap := make(map[string]any) - if p.Id != nil { - structMap["id"] = p.Id - } - if p.Name != nil { - structMap["name"] = p.Name - } - if p.Handle != nil { - structMap["handle"] = p.Handle - } - if p.AccountingCode.IsValueSet() { - structMap["accounting_code"] = p.AccountingCode.Value() - } - if p.Description.IsValueSet() { - structMap["description"] = p.Description.Value() - } - if p.CreatedAt != nil { - structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) - } - if p.UpdatedAt != nil { - structMap["updated_at"] = p.UpdatedAt.Format(time.RFC3339) - } - return structMap + structMap := make(map[string]any) + if p.Id != nil { + structMap["id"] = p.Id + } + if p.Name != nil { + structMap["name"] = p.Name + } + if p.Handle != nil { + structMap["handle"] = p.Handle + } + if p.AccountingCode.IsValueSet() { + if p.AccountingCode.Value() != nil { + structMap["accounting_code"] = p.AccountingCode.Value() + } else { + structMap["accounting_code"] = nil + } + } + if p.Description.IsValueSet() { + if p.Description.Value() != nil { + structMap["description"] = p.Description.Value() + } else { + structMap["description"] = nil + } + } + if p.CreatedAt != nil { + structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) + } + if p.UpdatedAt != nil { + structMap["updated_at"] = p.UpdatedAt.Format(time.RFC3339) + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProductFamily. +// UnmarshalJSON implements the json.Unmarshaler interface for ProductFamily. // It customizes the JSON unmarshaling process for ProductFamily objects. func (p *ProductFamily) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - AccountingCode Optional[string] `json:"accounting_code"` - Description Optional[string] `json:"description"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Id = temp.Id - p.Name = temp.Name - p.Handle = temp.Handle - p.AccountingCode = temp.AccountingCode - p.Description = temp.Description - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - p.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - p.UpdatedAt = &UpdatedAtVal - } - return nil + var temp productFamily + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Id = temp.Id + p.Name = temp.Name + p.Handle = temp.Handle + p.AccountingCode = temp.AccountingCode + p.Description = temp.Description + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + p.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + p.UpdatedAt = &UpdatedAtVal + } + return nil +} + +// TODO +type productFamily struct { + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + AccountingCode Optional[string] `json:"accounting_code"` + Description Optional[string] `json:"description"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` } diff --git a/models/product_family_response.go b/models/product_family_response.go index b0a76307..07ad3d3f 100644 --- a/models/product_family_response.go +++ b/models/product_family_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // ProductFamilyResponse represents a ProductFamilyResponse struct. type ProductFamilyResponse struct { - ProductFamily *ProductFamily `json:"product_family,omitempty"` + ProductFamily *ProductFamily `json:"product_family,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ProductFamilyResponse. +// MarshalJSON implements the json.Marshaler interface for ProductFamilyResponse. // It customizes the JSON marshaling process for ProductFamilyResponse objects. func (p *ProductFamilyResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProductFamilyResponse object to a map representation for JSON marshaling. func (p *ProductFamilyResponse) toMap() map[string]any { - structMap := make(map[string]any) - if p.ProductFamily != nil { - structMap["product_family"] = p.ProductFamily.toMap() - } - return structMap + structMap := make(map[string]any) + if p.ProductFamily != nil { + structMap["product_family"] = p.ProductFamily.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProductFamilyResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ProductFamilyResponse. // It customizes the JSON unmarshaling process for ProductFamilyResponse objects. func (p *ProductFamilyResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - ProductFamily *ProductFamily `json:"product_family,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.ProductFamily = temp.ProductFamily - return nil + var temp productFamilyResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.ProductFamily = temp.ProductFamily + return nil +} + +// TODO +type productFamilyResponse struct { + ProductFamily *ProductFamily `json:"product_family,omitempty"` } diff --git a/models/product_price_point.go b/models/product_price_point.go index f80595d0..32355c12 100644 --- a/models/product_price_point.go +++ b/models/product_price_point.go @@ -1,227 +1,237 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // ProductPricePoint represents a ProductPricePoint struct. type ProductPricePoint struct { - Id *int `json:"id,omitempty"` - // The product price point name - Name *string `json:"name,omitempty"` - // The product price point API handle - Handle *string `json:"handle,omitempty"` - // The product price point price, in integer cents - PriceInCents *int64 `json:"price_in_cents,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product price point would renew every 30 days - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this product price point, either month or day - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - // The product price point trial price, in integer cents - TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` - // The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product price point trial would last 30 days - TrialInterval *int `json:"trial_interval,omitempty"` - // A string representing the trial interval unit for this product price point, either month or day - TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` - TrialType *string `json:"trial_type,omitempty"` - // reserved for future use - IntroductoryOffer *bool `json:"introductory_offer,omitempty"` - // The product price point initial charge, in integer cents - InitialChargeInCents *int64 `json:"initial_charge_in_cents,omitempty"` - InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` - // The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product price point would expire after 30 days - ExpirationInterval *int `json:"expiration_interval,omitempty"` - // A string representing the expiration interval unit for this product price point, either month or day - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` - // The product id this price point belongs to - ProductId *int `json:"product_id,omitempty"` - // Timestamp indicating when this price point was archived - ArchivedAt Optional[time.Time] `json:"archived_at"` - // Timestamp indicating when this price point was created - CreatedAt *time.Time `json:"created_at,omitempty"` - // Timestamp indicating when this price point was last updated - UpdatedAt *time.Time `json:"updated_at,omitempty"` - // Whether or not to use the site's exchange rate or define your own pricing when your site has multiple currencies defined. - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` - // The type of price point - Type *PricePointType `json:"type,omitempty"` - // Whether or not the price point includes tax - TaxIncluded *bool `json:"tax_included,omitempty"` - // The subscription id this price point belongs to - SubscriptionId Optional[int] `json:"subscription_id"` - // An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. - CurrencyPrices []CurrencyPrice `json:"currency_prices,omitempty"` + Id *int `json:"id,omitempty"` + // The product price point name + Name *string `json:"name,omitempty"` + // The product price point API handle + Handle *string `json:"handle,omitempty"` + // The product price point price, in integer cents + PriceInCents *int64 `json:"price_in_cents,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this product price point would renew every 30 days + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this product price point, either month or day + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + // The product price point trial price, in integer cents + TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` + // The numerical trial interval. i.e. an interval of ‘30’ coupled with a trial_interval_unit of day would mean this product price point trial would last 30 days + TrialInterval *int `json:"trial_interval,omitempty"` + // A string representing the trial interval unit for this product price point, either month or day + TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` + TrialType *string `json:"trial_type,omitempty"` + // reserved for future use + IntroductoryOffer *bool `json:"introductory_offer,omitempty"` + // The product price point initial charge, in integer cents + InitialChargeInCents *int64 `json:"initial_charge_in_cents,omitempty"` + InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` + // The numerical expiration interval. i.e. an expiration_interval of ‘30’ coupled with an expiration_interval_unit of day would mean this product price point would expire after 30 days + ExpirationInterval *int `json:"expiration_interval,omitempty"` + // A string representing the expiration interval unit for this product price point, either month or day + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` + // The product id this price point belongs to + ProductId *int `json:"product_id,omitempty"` + // Timestamp indicating when this price point was archived + ArchivedAt Optional[time.Time] `json:"archived_at"` + // Timestamp indicating when this price point was created + CreatedAt *time.Time `json:"created_at,omitempty"` + // Timestamp indicating when this price point was last updated + UpdatedAt *time.Time `json:"updated_at,omitempty"` + // Whether or not to use the site's exchange rate or define your own pricing when your site has multiple currencies defined. + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + // The type of price point + Type *PricePointType `json:"type,omitempty"` + // Whether or not the price point includes tax + TaxIncluded *bool `json:"tax_included,omitempty"` + // The subscription id this price point belongs to + SubscriptionId Optional[int] `json:"subscription_id"` + // An array of currency pricing data is available when multiple currencies are defined for the site. It varies based on the use_site_exchange_rate setting for the price point. This parameter is present only in the response of read endpoints, after including the appropriate query parameter. + CurrencyPrices []CurrencyPrice `json:"currency_prices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ProductPricePoint. +// MarshalJSON implements the json.Marshaler interface for ProductPricePoint. // It customizes the JSON marshaling process for ProductPricePoint objects. func (p *ProductPricePoint) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProductPricePoint object to a map representation for JSON marshaling. func (p *ProductPricePoint) toMap() map[string]any { - structMap := make(map[string]any) - if p.Id != nil { - structMap["id"] = p.Id - } - if p.Name != nil { - structMap["name"] = p.Name - } - if p.Handle != nil { - structMap["handle"] = p.Handle - } - if p.PriceInCents != nil { - structMap["price_in_cents"] = p.PriceInCents - } - if p.Interval != nil { - structMap["interval"] = p.Interval - } - if p.IntervalUnit != nil { - structMap["interval_unit"] = p.IntervalUnit - } - if p.TrialPriceInCents != nil { - structMap["trial_price_in_cents"] = p.TrialPriceInCents - } - if p.TrialInterval != nil { - structMap["trial_interval"] = p.TrialInterval - } - if p.TrialIntervalUnit != nil { - structMap["trial_interval_unit"] = p.TrialIntervalUnit - } - if p.TrialType != nil { - structMap["trial_type"] = p.TrialType - } - if p.IntroductoryOffer != nil { - structMap["introductory_offer"] = p.IntroductoryOffer - } - if p.InitialChargeInCents != nil { - structMap["initial_charge_in_cents"] = p.InitialChargeInCents - } - if p.InitialChargeAfterTrial != nil { - structMap["initial_charge_after_trial"] = p.InitialChargeAfterTrial - } - if p.ExpirationInterval != nil { - structMap["expiration_interval"] = p.ExpirationInterval - } - if p.ExpirationIntervalUnit != nil { - structMap["expiration_interval_unit"] = p.ExpirationIntervalUnit - } - if p.ProductId != nil { - structMap["product_id"] = p.ProductId - } - if p.ArchivedAt.IsValueSet() { - var ArchivedAtVal *string = nil - if p.ArchivedAt.Value() != nil { - val := p.ArchivedAt.Value().Format(time.RFC3339) - ArchivedAtVal = &val - } - structMap["archived_at"] = ArchivedAtVal - } - if p.CreatedAt != nil { - structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) - } - if p.UpdatedAt != nil { - structMap["updated_at"] = p.UpdatedAt.Format(time.RFC3339) - } - if p.UseSiteExchangeRate != nil { - structMap["use_site_exchange_rate"] = p.UseSiteExchangeRate - } - if p.Type != nil { - structMap["type"] = p.Type - } - if p.TaxIncluded != nil { - structMap["tax_included"] = p.TaxIncluded - } - if p.SubscriptionId.IsValueSet() { - structMap["subscription_id"] = p.SubscriptionId.Value() - } - if p.CurrencyPrices != nil { - structMap["currency_prices"] = p.CurrencyPrices - } - return structMap + structMap := make(map[string]any) + if p.Id != nil { + structMap["id"] = p.Id + } + if p.Name != nil { + structMap["name"] = p.Name + } + if p.Handle != nil { + structMap["handle"] = p.Handle + } + if p.PriceInCents != nil { + structMap["price_in_cents"] = p.PriceInCents + } + if p.Interval != nil { + structMap["interval"] = p.Interval + } + if p.IntervalUnit != nil { + structMap["interval_unit"] = p.IntervalUnit + } + if p.TrialPriceInCents != nil { + structMap["trial_price_in_cents"] = p.TrialPriceInCents + } + if p.TrialInterval != nil { + structMap["trial_interval"] = p.TrialInterval + } + if p.TrialIntervalUnit != nil { + structMap["trial_interval_unit"] = p.TrialIntervalUnit + } + if p.TrialType != nil { + structMap["trial_type"] = p.TrialType + } + if p.IntroductoryOffer != nil { + structMap["introductory_offer"] = p.IntroductoryOffer + } + if p.InitialChargeInCents != nil { + structMap["initial_charge_in_cents"] = p.InitialChargeInCents + } + if p.InitialChargeAfterTrial != nil { + structMap["initial_charge_after_trial"] = p.InitialChargeAfterTrial + } + if p.ExpirationInterval != nil { + structMap["expiration_interval"] = p.ExpirationInterval + } + if p.ExpirationIntervalUnit != nil { + structMap["expiration_interval_unit"] = p.ExpirationIntervalUnit + } + if p.ProductId != nil { + structMap["product_id"] = p.ProductId + } + if p.ArchivedAt.IsValueSet() { + var ArchivedAtVal *string = nil + if p.ArchivedAt.Value() != nil { + val := p.ArchivedAt.Value().Format(time.RFC3339) + ArchivedAtVal = &val + } + if p.ArchivedAt.Value() != nil { + structMap["archived_at"] = ArchivedAtVal + } else { + structMap["archived_at"] = nil + } + } + if p.CreatedAt != nil { + structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) + } + if p.UpdatedAt != nil { + structMap["updated_at"] = p.UpdatedAt.Format(time.RFC3339) + } + if p.UseSiteExchangeRate != nil { + structMap["use_site_exchange_rate"] = p.UseSiteExchangeRate + } + if p.Type != nil { + structMap["type"] = p.Type + } + if p.TaxIncluded != nil { + structMap["tax_included"] = p.TaxIncluded + } + if p.SubscriptionId.IsValueSet() { + if p.SubscriptionId.Value() != nil { + structMap["subscription_id"] = p.SubscriptionId.Value() + } else { + structMap["subscription_id"] = nil + } + } + if p.CurrencyPrices != nil { + structMap["currency_prices"] = p.CurrencyPrices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProductPricePoint. +// UnmarshalJSON implements the json.Unmarshaler interface for ProductPricePoint. // It customizes the JSON unmarshaling process for ProductPricePoint objects. func (p *ProductPricePoint) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - PriceInCents *int64 `json:"price_in_cents,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` - TrialInterval *int `json:"trial_interval,omitempty"` - TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` - TrialType *string `json:"trial_type,omitempty"` - IntroductoryOffer *bool `json:"introductory_offer,omitempty"` - InitialChargeInCents *int64 `json:"initial_charge_in_cents,omitempty"` - InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` - ExpirationInterval *int `json:"expiration_interval,omitempty"` - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` - ProductId *int `json:"product_id,omitempty"` - ArchivedAt Optional[string] `json:"archived_at"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` - Type *PricePointType `json:"type,omitempty"` - TaxIncluded *bool `json:"tax_included,omitempty"` - SubscriptionId Optional[int] `json:"subscription_id"` - CurrencyPrices []CurrencyPrice `json:"currency_prices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Id = temp.Id - p.Name = temp.Name - p.Handle = temp.Handle - p.PriceInCents = temp.PriceInCents - p.Interval = temp.Interval - p.IntervalUnit = temp.IntervalUnit - p.TrialPriceInCents = temp.TrialPriceInCents - p.TrialInterval = temp.TrialInterval - p.TrialIntervalUnit = temp.TrialIntervalUnit - p.TrialType = temp.TrialType - p.IntroductoryOffer = temp.IntroductoryOffer - p.InitialChargeInCents = temp.InitialChargeInCents - p.InitialChargeAfterTrial = temp.InitialChargeAfterTrial - p.ExpirationInterval = temp.ExpirationInterval - p.ExpirationIntervalUnit = temp.ExpirationIntervalUnit - p.ProductId = temp.ProductId - p.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) - if temp.ArchivedAt.Value() != nil { - ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) - } - p.ArchivedAt.SetValue(&ArchivedAtVal) - } - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - p.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - p.UpdatedAt = &UpdatedAtVal - } - p.UseSiteExchangeRate = temp.UseSiteExchangeRate - p.Type = temp.Type - p.TaxIncluded = temp.TaxIncluded - p.SubscriptionId = temp.SubscriptionId - p.CurrencyPrices = temp.CurrencyPrices - return nil + var temp productPricePoint + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Id = temp.Id + p.Name = temp.Name + p.Handle = temp.Handle + p.PriceInCents = temp.PriceInCents + p.Interval = temp.Interval + p.IntervalUnit = temp.IntervalUnit + p.TrialPriceInCents = temp.TrialPriceInCents + p.TrialInterval = temp.TrialInterval + p.TrialIntervalUnit = temp.TrialIntervalUnit + p.TrialType = temp.TrialType + p.IntroductoryOffer = temp.IntroductoryOffer + p.InitialChargeInCents = temp.InitialChargeInCents + p.InitialChargeAfterTrial = temp.InitialChargeAfterTrial + p.ExpirationInterval = temp.ExpirationInterval + p.ExpirationIntervalUnit = temp.ExpirationIntervalUnit + p.ProductId = temp.ProductId + p.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) + if temp.ArchivedAt.Value() != nil { + ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) + } + p.ArchivedAt.SetValue(&ArchivedAtVal) + } + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + p.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + p.UpdatedAt = &UpdatedAtVal + } + p.UseSiteExchangeRate = temp.UseSiteExchangeRate + p.Type = temp.Type + p.TaxIncluded = temp.TaxIncluded + p.SubscriptionId = temp.SubscriptionId + p.CurrencyPrices = temp.CurrencyPrices + return nil +} + +// TODO +type productPricePoint struct { + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + PriceInCents *int64 `json:"price_in_cents,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + TrialPriceInCents *int64 `json:"trial_price_in_cents,omitempty"` + TrialInterval *int `json:"trial_interval,omitempty"` + TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` + TrialType *string `json:"trial_type,omitempty"` + IntroductoryOffer *bool `json:"introductory_offer,omitempty"` + InitialChargeInCents *int64 `json:"initial_charge_in_cents,omitempty"` + InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` + ExpirationInterval *int `json:"expiration_interval,omitempty"` + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ArchivedAt Optional[string] `json:"archived_at"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + Type *PricePointType `json:"type,omitempty"` + TaxIncluded *bool `json:"tax_included,omitempty"` + SubscriptionId Optional[int] `json:"subscription_id"` + CurrencyPrices []CurrencyPrice `json:"currency_prices,omitempty"` } diff --git a/models/product_price_point_errors.go b/models/product_price_point_errors.go index 42397423..c09d2cd3 100644 --- a/models/product_price_point_errors.go +++ b/models/product_price_point_errors.go @@ -1,72 +1,74 @@ package models import ( - "encoding/json" + "encoding/json" ) // ProductPricePointErrors represents a ProductPricePointErrors struct. type ProductPricePointErrors struct { - PricePoint *string `json:"price_point,omitempty"` - Interval []string `json:"interval,omitempty"` - IntervalUnit []string `json:"interval_unit,omitempty"` - Name []string `json:"name,omitempty"` - Price []string `json:"price,omitempty"` - PriceInCents []string `json:"price_in_cents,omitempty"` + PricePoint *string `json:"price_point,omitempty"` + Interval []string `json:"interval,omitempty"` + IntervalUnit []string `json:"interval_unit,omitempty"` + Name []string `json:"name,omitempty"` + Price []string `json:"price,omitempty"` + PriceInCents []string `json:"price_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ProductPricePointErrors. +// MarshalJSON implements the json.Marshaler interface for ProductPricePointErrors. // It customizes the JSON marshaling process for ProductPricePointErrors objects. func (p *ProductPricePointErrors) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProductPricePointErrors object to a map representation for JSON marshaling. func (p *ProductPricePointErrors) toMap() map[string]any { - structMap := make(map[string]any) - if p.PricePoint != nil { - structMap["price_point"] = p.PricePoint - } - if p.Interval != nil { - structMap["interval"] = p.Interval - } - if p.IntervalUnit != nil { - structMap["interval_unit"] = p.IntervalUnit - } - if p.Name != nil { - structMap["name"] = p.Name - } - if p.Price != nil { - structMap["price"] = p.Price - } - if p.PriceInCents != nil { - structMap["price_in_cents"] = p.PriceInCents - } - return structMap + structMap := make(map[string]any) + if p.PricePoint != nil { + structMap["price_point"] = p.PricePoint + } + if p.Interval != nil { + structMap["interval"] = p.Interval + } + if p.IntervalUnit != nil { + structMap["interval_unit"] = p.IntervalUnit + } + if p.Name != nil { + structMap["name"] = p.Name + } + if p.Price != nil { + structMap["price"] = p.Price + } + if p.PriceInCents != nil { + structMap["price_in_cents"] = p.PriceInCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProductPricePointErrors. +// UnmarshalJSON implements the json.Unmarshaler interface for ProductPricePointErrors. // It customizes the JSON unmarshaling process for ProductPricePointErrors objects. func (p *ProductPricePointErrors) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoint *string `json:"price_point,omitempty"` - Interval []string `json:"interval,omitempty"` - IntervalUnit []string `json:"interval_unit,omitempty"` - Name []string `json:"name,omitempty"` - Price []string `json:"price,omitempty"` - PriceInCents []string `json:"price_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.PricePoint = temp.PricePoint - p.Interval = temp.Interval - p.IntervalUnit = temp.IntervalUnit - p.Name = temp.Name - p.Price = temp.Price - p.PriceInCents = temp.PriceInCents - return nil + var temp productPricePointErrors + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.PricePoint = temp.PricePoint + p.Interval = temp.Interval + p.IntervalUnit = temp.IntervalUnit + p.Name = temp.Name + p.Price = temp.Price + p.PriceInCents = temp.PriceInCents + return nil +} + +// TODO +type productPricePointErrors struct { + PricePoint *string `json:"price_point,omitempty"` + Interval []string `json:"interval,omitempty"` + IntervalUnit []string `json:"interval_unit,omitempty"` + Name []string `json:"name,omitempty"` + Price []string `json:"price,omitempty"` + PriceInCents []string `json:"price_in_cents,omitempty"` } diff --git a/models/product_price_point_response.go b/models/product_price_point_response.go index f10b3ea9..6daa6295 100644 --- a/models/product_price_point_response.go +++ b/models/product_price_point_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ProductPricePointResponse represents a ProductPricePointResponse struct. type ProductPricePointResponse struct { - PricePoint ProductPricePoint `json:"price_point"` + PricePoint ProductPricePoint `json:"price_point"` } -// MarshalJSON implements the json.Marshaler interface for ProductPricePointResponse. +// MarshalJSON implements the json.Marshaler interface for ProductPricePointResponse. // It customizes the JSON marshaling process for ProductPricePointResponse objects. func (p *ProductPricePointResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProductPricePointResponse object to a map representation for JSON marshaling. func (p *ProductPricePointResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["price_point"] = p.PricePoint.toMap() - return structMap + structMap := make(map[string]any) + structMap["price_point"] = p.PricePoint.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProductPricePointResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ProductPricePointResponse. // It customizes the JSON unmarshaling process for ProductPricePointResponse objects. func (p *ProductPricePointResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoint ProductPricePoint `json:"price_point"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.PricePoint = temp.PricePoint - return nil + var temp productPricePointResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.PricePoint = *temp.PricePoint + return nil +} + +// TODO +type productPricePointResponse struct { + PricePoint *ProductPricePoint `json:"price_point"` +} + +func (p *productPricePointResponse) validate() error { + var errs []string + if p.PricePoint == nil { + errs = append(errs, "required field `price_point` is missing for type `Product Price Point Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/product_response.go b/models/product_response.go index 100a10e5..af10192a 100644 --- a/models/product_response.go +++ b/models/product_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ProductResponse represents a ProductResponse struct. type ProductResponse struct { - Product Product `json:"product"` + Product Product `json:"product"` } -// MarshalJSON implements the json.Marshaler interface for ProductResponse. +// MarshalJSON implements the json.Marshaler interface for ProductResponse. // It customizes the JSON marshaling process for ProductResponse objects. func (p *ProductResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProductResponse object to a map representation for JSON marshaling. func (p *ProductResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["product"] = p.Product.toMap() - return structMap + structMap := make(map[string]any) + structMap["product"] = p.Product.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProductResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ProductResponse. // It customizes the JSON unmarshaling process for ProductResponse objects. func (p *ProductResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Product Product `json:"product"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Product = temp.Product - return nil + var temp productResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.Product = *temp.Product + return nil +} + +// TODO +type productResponse struct { + Product *Product `json:"product"` +} + +func (p *productResponse) validate() error { + var errs []string + if p.Product == nil { + errs = append(errs, "required field `product` is missing for type `Product Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/product_trial_interval_unit.go b/models/product_trial_interval_unit.go new file mode 100644 index 00000000..e01a9cc0 --- /dev/null +++ b/models/product_trial_interval_unit.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ProductTrialIntervalUnit represents a ProductTrialIntervalUnit struct. +// This is a container for one-of cases. +type ProductTrialIntervalUnit struct { + value any + isIntervalUnit bool +} + +// String converts the ProductTrialIntervalUnit object to a string representation. +func (p ProductTrialIntervalUnit) String() string { + if bytes, err := json.Marshal(p.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ProductTrialIntervalUnit. +// It customizes the JSON marshaling process for ProductTrialIntervalUnit objects. +func (p *ProductTrialIntervalUnit) MarshalJSON() ( + []byte, + error) { + if p.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ProductTrialIntervalUnitContainer.From*` functions to initialize the ProductTrialIntervalUnit object.") + } + return json.Marshal(p.toMap()) +} + +// toMap converts the ProductTrialIntervalUnit object to a map representation for JSON marshaling. +func (p *ProductTrialIntervalUnit) toMap() any { + switch obj := p.value.(type) { + case *IntervalUnit: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ProductTrialIntervalUnit. +// It customizes the JSON unmarshaling process for ProductTrialIntervalUnit objects. +func (p *ProductTrialIntervalUnit) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(IntervalUnit), false, &p.isIntervalUnit), + ) + + p.value = result + return err +} + +func (p *ProductTrialIntervalUnit) AsIntervalUnit() ( + *IntervalUnit, + bool) { + if !p.isIntervalUnit { + return nil, false + } + return p.value.(*IntervalUnit), true +} + +// internalProductTrialIntervalUnit represents a productTrialIntervalUnit struct. +// This is a container for one-of cases. +type internalProductTrialIntervalUnit struct{} + +var ProductTrialIntervalUnitContainer internalProductTrialIntervalUnit + +func (p *internalProductTrialIntervalUnit) FromIntervalUnit(val IntervalUnit) ProductTrialIntervalUnit { + return ProductTrialIntervalUnit{value: &val} +} diff --git a/models/proforma_error.go b/models/proforma_error.go index b35412fd..f25f5222 100644 --- a/models/proforma_error.go +++ b/models/proforma_error.go @@ -1,43 +1,45 @@ package models import ( - "encoding/json" + "encoding/json" ) // ProformaError represents a ProformaError struct. type ProformaError struct { - // The error is base if it is not directly associated with a single attribute. - Subscription *BaseStringError `json:"subscription,omitempty"` + // The error is base if it is not directly associated with a single attribute. + Subscription *BaseStringError `json:"subscription,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ProformaError. +// MarshalJSON implements the json.Marshaler interface for ProformaError. // It customizes the JSON marshaling process for ProformaError objects. func (p *ProformaError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProformaError object to a map representation for JSON marshaling. func (p *ProformaError) toMap() map[string]any { - structMap := make(map[string]any) - if p.Subscription != nil { - structMap["subscription"] = p.Subscription.toMap() - } - return structMap + structMap := make(map[string]any) + if p.Subscription != nil { + structMap["subscription"] = p.Subscription.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProformaError. +// UnmarshalJSON implements the json.Unmarshaler interface for ProformaError. // It customizes the JSON unmarshaling process for ProformaError objects. func (p *ProformaError) UnmarshalJSON(input []byte) error { - temp := &struct { - Subscription *BaseStringError `json:"subscription,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Subscription = temp.Subscription - return nil + var temp proformaError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Subscription = temp.Subscription + return nil +} + +// TODO +type proformaError struct { + Subscription *BaseStringError `json:"subscription,omitempty"` } diff --git a/models/proforma_invoice.go b/models/proforma_invoice.go index 37d30e62..440d2180 100644 --- a/models/proforma_invoice.go +++ b/models/proforma_invoice.go @@ -1,276 +1,298 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // ProformaInvoice represents a ProformaInvoice struct. type ProformaInvoice struct { - Uid *string `json:"uid,omitempty"` - SiteId *int `json:"site_id,omitempty"` - CustomerId Optional[int] `json:"customer_id"` - SubscriptionId Optional[int] `json:"subscription_id"` - Number Optional[int] `json:"number"` - SequenceNumber Optional[int] `json:"sequence_number"` - CreatedAt *time.Time `json:"created_at,omitempty"` - DeliveryDate *time.Time `json:"delivery_date,omitempty"` - Status *ProformaInvoiceStatus `json:"status,omitempty"` - // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. - CollectionMethod *CollectionMethod `json:"collection_method,omitempty"` - PaymentInstructions *string `json:"payment_instructions,omitempty"` - Currency *string `json:"currency,omitempty"` - // Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values: - // * "none": A normal invoice with no consolidation. - // * "child": An invoice segment which has been combined into a consolidated invoice. - // * "parent": A consolidated invoice, whose contents are composed of invoice segments. - // "Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments. - // See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). - ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` - ProductName *string `json:"product_name,omitempty"` - ProductFamilyName *string `json:"product_family_name,omitempty"` - // 'proforma' value is deprecated in favor of proforma_adhoc and proforma_automatic - Role *ProformaInvoiceRole `json:"role,omitempty"` - // Information about the seller (merchant) listed on the masthead of the invoice. - Seller *InvoiceSeller `json:"seller,omitempty"` - // Information about the customer who is owner or recipient the invoiced subscription. - Customer *InvoiceCustomer `json:"customer,omitempty"` - Memo *string `json:"memo,omitempty"` - BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` - ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - TotalAmount *string `json:"total_amount,omitempty"` - CreditAmount *string `json:"credit_amount,omitempty"` - PaidAmount *string `json:"paid_amount,omitempty"` - RefundAmount *string `json:"refund_amount,omitempty"` - DueAmount *string `json:"due_amount,omitempty"` - LineItems []InvoiceLineItem `json:"line_items,omitempty"` - Discounts []ProformaInvoiceDiscount `json:"discounts,omitempty"` - Taxes []ProformaInvoiceTax `json:"taxes,omitempty"` - Credits []ProformaInvoiceCredit `json:"credits,omitempty"` - Payments []ProformaInvoicePayment `json:"payments,omitempty"` - CustomFields []InvoiceCustomField `json:"custom_fields,omitempty"` - PublicUrl Optional[string] `json:"public_url"` + Uid *string `json:"uid,omitempty"` + SiteId *int `json:"site_id,omitempty"` + CustomerId Optional[int] `json:"customer_id"` + SubscriptionId Optional[int] `json:"subscription_id"` + Number Optional[int] `json:"number"` + SequenceNumber Optional[int] `json:"sequence_number"` + CreatedAt *time.Time `json:"created_at,omitempty"` + DeliveryDate *time.Time `json:"delivery_date,omitempty"` + Status *ProformaInvoiceStatus `json:"status,omitempty"` + // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. + CollectionMethod *CollectionMethod `json:"collection_method,omitempty"` + PaymentInstructions *string `json:"payment_instructions,omitempty"` + Currency *string `json:"currency,omitempty"` + // Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values: + // * "none": A normal invoice with no consolidation. + // * "child": An invoice segment which has been combined into a consolidated invoice. + // * "parent": A consolidated invoice, whose contents are composed of invoice segments. + // "Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments. + // See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). + ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` + ProductName *string `json:"product_name,omitempty"` + ProductFamilyName *string `json:"product_family_name,omitempty"` + // 'proforma' value is deprecated in favor of proforma_adhoc and proforma_automatic + Role *ProformaInvoiceRole `json:"role,omitempty"` + // Information about the seller (merchant) listed on the masthead of the invoice. + Seller *InvoiceSeller `json:"seller,omitempty"` + // Information about the customer who is owner or recipient the invoiced subscription. + Customer *InvoiceCustomer `json:"customer,omitempty"` + Memo *string `json:"memo,omitempty"` + BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` + ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + TotalAmount *string `json:"total_amount,omitempty"` + CreditAmount *string `json:"credit_amount,omitempty"` + PaidAmount *string `json:"paid_amount,omitempty"` + RefundAmount *string `json:"refund_amount,omitempty"` + DueAmount *string `json:"due_amount,omitempty"` + LineItems []InvoiceLineItem `json:"line_items,omitempty"` + Discounts []ProformaInvoiceDiscount `json:"discounts,omitempty"` + Taxes []ProformaInvoiceTax `json:"taxes,omitempty"` + Credits []ProformaInvoiceCredit `json:"credits,omitempty"` + Payments []ProformaInvoicePayment `json:"payments,omitempty"` + CustomFields []InvoiceCustomField `json:"custom_fields,omitempty"` + PublicUrl Optional[string] `json:"public_url"` } -// MarshalJSON implements the json.Marshaler interface for ProformaInvoice. +// MarshalJSON implements the json.Marshaler interface for ProformaInvoice. // It customizes the JSON marshaling process for ProformaInvoice objects. func (p *ProformaInvoice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProformaInvoice object to a map representation for JSON marshaling. func (p *ProformaInvoice) toMap() map[string]any { - structMap := make(map[string]any) - if p.Uid != nil { - structMap["uid"] = p.Uid - } - if p.SiteId != nil { - structMap["site_id"] = p.SiteId - } - if p.CustomerId.IsValueSet() { - structMap["customer_id"] = p.CustomerId.Value() - } - if p.SubscriptionId.IsValueSet() { - structMap["subscription_id"] = p.SubscriptionId.Value() - } - if p.Number.IsValueSet() { - structMap["number"] = p.Number.Value() - } - if p.SequenceNumber.IsValueSet() { - structMap["sequence_number"] = p.SequenceNumber.Value() - } - if p.CreatedAt != nil { - structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) - } - if p.DeliveryDate != nil { - structMap["delivery_date"] = p.DeliveryDate.Format(DEFAULT_DATE) - } - if p.Status != nil { - structMap["status"] = p.Status - } - if p.CollectionMethod != nil { - structMap["collection_method"] = p.CollectionMethod - } - if p.PaymentInstructions != nil { - structMap["payment_instructions"] = p.PaymentInstructions - } - if p.Currency != nil { - structMap["currency"] = p.Currency - } - if p.ConsolidationLevel != nil { - structMap["consolidation_level"] = p.ConsolidationLevel - } - if p.ProductName != nil { - structMap["product_name"] = p.ProductName - } - if p.ProductFamilyName != nil { - structMap["product_family_name"] = p.ProductFamilyName - } - if p.Role != nil { - structMap["role"] = p.Role - } - if p.Seller != nil { - structMap["seller"] = p.Seller.toMap() - } - if p.Customer != nil { - structMap["customer"] = p.Customer.toMap() - } - if p.Memo != nil { - structMap["memo"] = p.Memo - } - if p.BillingAddress != nil { - structMap["billing_address"] = p.BillingAddress.toMap() - } - if p.ShippingAddress != nil { - structMap["shipping_address"] = p.ShippingAddress.toMap() - } - if p.SubtotalAmount != nil { - structMap["subtotal_amount"] = p.SubtotalAmount - } - if p.DiscountAmount != nil { - structMap["discount_amount"] = p.DiscountAmount - } - if p.TaxAmount != nil { - structMap["tax_amount"] = p.TaxAmount - } - if p.TotalAmount != nil { - structMap["total_amount"] = p.TotalAmount - } - if p.CreditAmount != nil { - structMap["credit_amount"] = p.CreditAmount - } - if p.PaidAmount != nil { - structMap["paid_amount"] = p.PaidAmount - } - if p.RefundAmount != nil { - structMap["refund_amount"] = p.RefundAmount - } - if p.DueAmount != nil { - structMap["due_amount"] = p.DueAmount - } - if p.LineItems != nil { - structMap["line_items"] = p.LineItems - } - if p.Discounts != nil { - structMap["discounts"] = p.Discounts - } - if p.Taxes != nil { - structMap["taxes"] = p.Taxes - } - if p.Credits != nil { - structMap["credits"] = p.Credits - } - if p.Payments != nil { - structMap["payments"] = p.Payments - } - if p.CustomFields != nil { - structMap["custom_fields"] = p.CustomFields - } - if p.PublicUrl.IsValueSet() { - structMap["public_url"] = p.PublicUrl.Value() - } - return structMap + structMap := make(map[string]any) + if p.Uid != nil { + structMap["uid"] = p.Uid + } + if p.SiteId != nil { + structMap["site_id"] = p.SiteId + } + if p.CustomerId.IsValueSet() { + if p.CustomerId.Value() != nil { + structMap["customer_id"] = p.CustomerId.Value() + } else { + structMap["customer_id"] = nil + } + } + if p.SubscriptionId.IsValueSet() { + if p.SubscriptionId.Value() != nil { + structMap["subscription_id"] = p.SubscriptionId.Value() + } else { + structMap["subscription_id"] = nil + } + } + if p.Number.IsValueSet() { + if p.Number.Value() != nil { + structMap["number"] = p.Number.Value() + } else { + structMap["number"] = nil + } + } + if p.SequenceNumber.IsValueSet() { + if p.SequenceNumber.Value() != nil { + structMap["sequence_number"] = p.SequenceNumber.Value() + } else { + structMap["sequence_number"] = nil + } + } + if p.CreatedAt != nil { + structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) + } + if p.DeliveryDate != nil { + structMap["delivery_date"] = p.DeliveryDate.Format(DEFAULT_DATE) + } + if p.Status != nil { + structMap["status"] = p.Status + } + if p.CollectionMethod != nil { + structMap["collection_method"] = p.CollectionMethod + } + if p.PaymentInstructions != nil { + structMap["payment_instructions"] = p.PaymentInstructions + } + if p.Currency != nil { + structMap["currency"] = p.Currency + } + if p.ConsolidationLevel != nil { + structMap["consolidation_level"] = p.ConsolidationLevel + } + if p.ProductName != nil { + structMap["product_name"] = p.ProductName + } + if p.ProductFamilyName != nil { + structMap["product_family_name"] = p.ProductFamilyName + } + if p.Role != nil { + structMap["role"] = p.Role + } + if p.Seller != nil { + structMap["seller"] = p.Seller.toMap() + } + if p.Customer != nil { + structMap["customer"] = p.Customer.toMap() + } + if p.Memo != nil { + structMap["memo"] = p.Memo + } + if p.BillingAddress != nil { + structMap["billing_address"] = p.BillingAddress.toMap() + } + if p.ShippingAddress != nil { + structMap["shipping_address"] = p.ShippingAddress.toMap() + } + if p.SubtotalAmount != nil { + structMap["subtotal_amount"] = p.SubtotalAmount + } + if p.DiscountAmount != nil { + structMap["discount_amount"] = p.DiscountAmount + } + if p.TaxAmount != nil { + structMap["tax_amount"] = p.TaxAmount + } + if p.TotalAmount != nil { + structMap["total_amount"] = p.TotalAmount + } + if p.CreditAmount != nil { + structMap["credit_amount"] = p.CreditAmount + } + if p.PaidAmount != nil { + structMap["paid_amount"] = p.PaidAmount + } + if p.RefundAmount != nil { + structMap["refund_amount"] = p.RefundAmount + } + if p.DueAmount != nil { + structMap["due_amount"] = p.DueAmount + } + if p.LineItems != nil { + structMap["line_items"] = p.LineItems + } + if p.Discounts != nil { + structMap["discounts"] = p.Discounts + } + if p.Taxes != nil { + structMap["taxes"] = p.Taxes + } + if p.Credits != nil { + structMap["credits"] = p.Credits + } + if p.Payments != nil { + structMap["payments"] = p.Payments + } + if p.CustomFields != nil { + structMap["custom_fields"] = p.CustomFields + } + if p.PublicUrl.IsValueSet() { + if p.PublicUrl.Value() != nil { + structMap["public_url"] = p.PublicUrl.Value() + } else { + structMap["public_url"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProformaInvoice. +// UnmarshalJSON implements the json.Unmarshaler interface for ProformaInvoice. // It customizes the JSON unmarshaling process for ProformaInvoice objects. func (p *ProformaInvoice) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - SiteId *int `json:"site_id,omitempty"` - CustomerId Optional[int] `json:"customer_id"` - SubscriptionId Optional[int] `json:"subscription_id"` - Number Optional[int] `json:"number"` - SequenceNumber Optional[int] `json:"sequence_number"` - CreatedAt *string `json:"created_at,omitempty"` - DeliveryDate *string `json:"delivery_date,omitempty"` - Status *ProformaInvoiceStatus `json:"status,omitempty"` - CollectionMethod *CollectionMethod `json:"collection_method,omitempty"` - PaymentInstructions *string `json:"payment_instructions,omitempty"` - Currency *string `json:"currency,omitempty"` - ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` - ProductName *string `json:"product_name,omitempty"` - ProductFamilyName *string `json:"product_family_name,omitempty"` - Role *ProformaInvoiceRole `json:"role,omitempty"` - Seller *InvoiceSeller `json:"seller,omitempty"` - Customer *InvoiceCustomer `json:"customer,omitempty"` - Memo *string `json:"memo,omitempty"` - BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` - ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` - SubtotalAmount *string `json:"subtotal_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - TotalAmount *string `json:"total_amount,omitempty"` - CreditAmount *string `json:"credit_amount,omitempty"` - PaidAmount *string `json:"paid_amount,omitempty"` - RefundAmount *string `json:"refund_amount,omitempty"` - DueAmount *string `json:"due_amount,omitempty"` - LineItems []InvoiceLineItem `json:"line_items,omitempty"` - Discounts []ProformaInvoiceDiscount `json:"discounts,omitempty"` - Taxes []ProformaInvoiceTax `json:"taxes,omitempty"` - Credits []ProformaInvoiceCredit `json:"credits,omitempty"` - Payments []ProformaInvoicePayment `json:"payments,omitempty"` - CustomFields []InvoiceCustomField `json:"custom_fields,omitempty"` - PublicUrl Optional[string] `json:"public_url"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Uid = temp.Uid - p.SiteId = temp.SiteId - p.CustomerId = temp.CustomerId - p.SubscriptionId = temp.SubscriptionId - p.Number = temp.Number - p.SequenceNumber = temp.SequenceNumber - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - p.CreatedAt = &CreatedAtVal - } - if temp.DeliveryDate != nil { - DeliveryDateVal, err := time.Parse(DEFAULT_DATE, *temp.DeliveryDate) - if err != nil { - log.Fatalf("Cannot Parse delivery_date as % s format.", DEFAULT_DATE) - } - p.DeliveryDate = &DeliveryDateVal - } - p.Status = temp.Status - p.CollectionMethod = temp.CollectionMethod - p.PaymentInstructions = temp.PaymentInstructions - p.Currency = temp.Currency - p.ConsolidationLevel = temp.ConsolidationLevel - p.ProductName = temp.ProductName - p.ProductFamilyName = temp.ProductFamilyName - p.Role = temp.Role - p.Seller = temp.Seller - p.Customer = temp.Customer - p.Memo = temp.Memo - p.BillingAddress = temp.BillingAddress - p.ShippingAddress = temp.ShippingAddress - p.SubtotalAmount = temp.SubtotalAmount - p.DiscountAmount = temp.DiscountAmount - p.TaxAmount = temp.TaxAmount - p.TotalAmount = temp.TotalAmount - p.CreditAmount = temp.CreditAmount - p.PaidAmount = temp.PaidAmount - p.RefundAmount = temp.RefundAmount - p.DueAmount = temp.DueAmount - p.LineItems = temp.LineItems - p.Discounts = temp.Discounts - p.Taxes = temp.Taxes - p.Credits = temp.Credits - p.Payments = temp.Payments - p.CustomFields = temp.CustomFields - p.PublicUrl = temp.PublicUrl - return nil + var temp proformaInvoice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Uid = temp.Uid + p.SiteId = temp.SiteId + p.CustomerId = temp.CustomerId + p.SubscriptionId = temp.SubscriptionId + p.Number = temp.Number + p.SequenceNumber = temp.SequenceNumber + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + p.CreatedAt = &CreatedAtVal + } + if temp.DeliveryDate != nil { + DeliveryDateVal, err := time.Parse(DEFAULT_DATE, *temp.DeliveryDate) + if err != nil { + log.Fatalf("Cannot Parse delivery_date as % s format.", DEFAULT_DATE) + } + p.DeliveryDate = &DeliveryDateVal + } + p.Status = temp.Status + p.CollectionMethod = temp.CollectionMethod + p.PaymentInstructions = temp.PaymentInstructions + p.Currency = temp.Currency + p.ConsolidationLevel = temp.ConsolidationLevel + p.ProductName = temp.ProductName + p.ProductFamilyName = temp.ProductFamilyName + p.Role = temp.Role + p.Seller = temp.Seller + p.Customer = temp.Customer + p.Memo = temp.Memo + p.BillingAddress = temp.BillingAddress + p.ShippingAddress = temp.ShippingAddress + p.SubtotalAmount = temp.SubtotalAmount + p.DiscountAmount = temp.DiscountAmount + p.TaxAmount = temp.TaxAmount + p.TotalAmount = temp.TotalAmount + p.CreditAmount = temp.CreditAmount + p.PaidAmount = temp.PaidAmount + p.RefundAmount = temp.RefundAmount + p.DueAmount = temp.DueAmount + p.LineItems = temp.LineItems + p.Discounts = temp.Discounts + p.Taxes = temp.Taxes + p.Credits = temp.Credits + p.Payments = temp.Payments + p.CustomFields = temp.CustomFields + p.PublicUrl = temp.PublicUrl + return nil +} + +// TODO +type proformaInvoice struct { + Uid *string `json:"uid,omitempty"` + SiteId *int `json:"site_id,omitempty"` + CustomerId Optional[int] `json:"customer_id"` + SubscriptionId Optional[int] `json:"subscription_id"` + Number Optional[int] `json:"number"` + SequenceNumber Optional[int] `json:"sequence_number"` + CreatedAt *string `json:"created_at,omitempty"` + DeliveryDate *string `json:"delivery_date,omitempty"` + Status *ProformaInvoiceStatus `json:"status,omitempty"` + CollectionMethod *CollectionMethod `json:"collection_method,omitempty"` + PaymentInstructions *string `json:"payment_instructions,omitempty"` + Currency *string `json:"currency,omitempty"` + ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` + ProductName *string `json:"product_name,omitempty"` + ProductFamilyName *string `json:"product_family_name,omitempty"` + Role *ProformaInvoiceRole `json:"role,omitempty"` + Seller *InvoiceSeller `json:"seller,omitempty"` + Customer *InvoiceCustomer `json:"customer,omitempty"` + Memo *string `json:"memo,omitempty"` + BillingAddress *InvoiceAddress `json:"billing_address,omitempty"` + ShippingAddress *InvoiceAddress `json:"shipping_address,omitempty"` + SubtotalAmount *string `json:"subtotal_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + TotalAmount *string `json:"total_amount,omitempty"` + CreditAmount *string `json:"credit_amount,omitempty"` + PaidAmount *string `json:"paid_amount,omitempty"` + RefundAmount *string `json:"refund_amount,omitempty"` + DueAmount *string `json:"due_amount,omitempty"` + LineItems []InvoiceLineItem `json:"line_items,omitempty"` + Discounts []ProformaInvoiceDiscount `json:"discounts,omitempty"` + Taxes []ProformaInvoiceTax `json:"taxes,omitempty"` + Credits []ProformaInvoiceCredit `json:"credits,omitempty"` + Payments []ProformaInvoicePayment `json:"payments,omitempty"` + CustomFields []InvoiceCustomField `json:"custom_fields,omitempty"` + PublicUrl Optional[string] `json:"public_url"` } diff --git a/models/proforma_invoice_credit.go b/models/proforma_invoice_credit.go index 8cff0bff..512ca16b 100644 --- a/models/proforma_invoice_credit.go +++ b/models/proforma_invoice_credit.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // ProformaInvoiceCredit represents a ProformaInvoiceCredit struct. type ProformaInvoiceCredit struct { - Uid *string `json:"uid,omitempty"` - Memo *string `json:"memo,omitempty"` - OriginalAmount *string `json:"original_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` + Uid *string `json:"uid,omitempty"` + Memo *string `json:"memo,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ProformaInvoiceCredit. +// MarshalJSON implements the json.Marshaler interface for ProformaInvoiceCredit. // It customizes the JSON marshaling process for ProformaInvoiceCredit objects. func (p *ProformaInvoiceCredit) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProformaInvoiceCredit object to a map representation for JSON marshaling. func (p *ProformaInvoiceCredit) toMap() map[string]any { - structMap := make(map[string]any) - if p.Uid != nil { - structMap["uid"] = p.Uid - } - if p.Memo != nil { - structMap["memo"] = p.Memo - } - if p.OriginalAmount != nil { - structMap["original_amount"] = p.OriginalAmount - } - if p.AppliedAmount != nil { - structMap["applied_amount"] = p.AppliedAmount - } - return structMap + structMap := make(map[string]any) + if p.Uid != nil { + structMap["uid"] = p.Uid + } + if p.Memo != nil { + structMap["memo"] = p.Memo + } + if p.OriginalAmount != nil { + structMap["original_amount"] = p.OriginalAmount + } + if p.AppliedAmount != nil { + structMap["applied_amount"] = p.AppliedAmount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProformaInvoiceCredit. +// UnmarshalJSON implements the json.Unmarshaler interface for ProformaInvoiceCredit. // It customizes the JSON unmarshaling process for ProformaInvoiceCredit objects. func (p *ProformaInvoiceCredit) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Memo *string `json:"memo,omitempty"` - OriginalAmount *string `json:"original_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Uid = temp.Uid - p.Memo = temp.Memo - p.OriginalAmount = temp.OriginalAmount - p.AppliedAmount = temp.AppliedAmount - return nil + var temp proformaInvoiceCredit + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Uid = temp.Uid + p.Memo = temp.Memo + p.OriginalAmount = temp.OriginalAmount + p.AppliedAmount = temp.AppliedAmount + return nil +} + +// TODO +type proformaInvoiceCredit struct { + Uid *string `json:"uid,omitempty"` + Memo *string `json:"memo,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` } diff --git a/models/proforma_invoice_discount.go b/models/proforma_invoice_discount.go index f8c756bc..9b4ad64b 100644 --- a/models/proforma_invoice_discount.go +++ b/models/proforma_invoice_discount.go @@ -1,84 +1,86 @@ package models import ( - "encoding/json" + "encoding/json" ) // ProformaInvoiceDiscount represents a ProformaInvoiceDiscount struct. type ProformaInvoiceDiscount struct { - Uid *string `json:"uid,omitempty"` - Title *string `json:"title,omitempty"` - Code *string `json:"code,omitempty"` - SourceType *ProformaInvoiceDiscountSourceType `json:"source_type,omitempty"` - DiscountType *InvoiceDiscountType `json:"discount_type,omitempty"` - EligibleAmount *string `json:"eligible_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - LineItemBreakouts []InvoiceDiscountBreakout `json:"line_item_breakouts,omitempty"` + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + Code *string `json:"code,omitempty"` + SourceType *ProformaInvoiceDiscountSourceType `json:"source_type,omitempty"` + DiscountType *InvoiceDiscountType `json:"discount_type,omitempty"` + EligibleAmount *string `json:"eligible_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` + LineItemBreakouts []InvoiceDiscountBreakout `json:"line_item_breakouts,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ProformaInvoiceDiscount. +// MarshalJSON implements the json.Marshaler interface for ProformaInvoiceDiscount. // It customizes the JSON marshaling process for ProformaInvoiceDiscount objects. func (p *ProformaInvoiceDiscount) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProformaInvoiceDiscount object to a map representation for JSON marshaling. func (p *ProformaInvoiceDiscount) toMap() map[string]any { - structMap := make(map[string]any) - if p.Uid != nil { - structMap["uid"] = p.Uid - } - if p.Title != nil { - structMap["title"] = p.Title - } - if p.Code != nil { - structMap["code"] = p.Code - } - if p.SourceType != nil { - structMap["source_type"] = p.SourceType - } - if p.DiscountType != nil { - structMap["discount_type"] = p.DiscountType - } - if p.EligibleAmount != nil { - structMap["eligible_amount"] = p.EligibleAmount - } - if p.DiscountAmount != nil { - structMap["discount_amount"] = p.DiscountAmount - } - if p.LineItemBreakouts != nil { - structMap["line_item_breakouts"] = p.LineItemBreakouts - } - return structMap + structMap := make(map[string]any) + if p.Uid != nil { + structMap["uid"] = p.Uid + } + if p.Title != nil { + structMap["title"] = p.Title + } + if p.Code != nil { + structMap["code"] = p.Code + } + if p.SourceType != nil { + structMap["source_type"] = p.SourceType + } + if p.DiscountType != nil { + structMap["discount_type"] = p.DiscountType + } + if p.EligibleAmount != nil { + structMap["eligible_amount"] = p.EligibleAmount + } + if p.DiscountAmount != nil { + structMap["discount_amount"] = p.DiscountAmount + } + if p.LineItemBreakouts != nil { + structMap["line_item_breakouts"] = p.LineItemBreakouts + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProformaInvoiceDiscount. +// UnmarshalJSON implements the json.Unmarshaler interface for ProformaInvoiceDiscount. // It customizes the JSON unmarshaling process for ProformaInvoiceDiscount objects. func (p *ProformaInvoiceDiscount) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Title *string `json:"title,omitempty"` - Code *string `json:"code,omitempty"` - SourceType *ProformaInvoiceDiscountSourceType `json:"source_type,omitempty"` - DiscountType *InvoiceDiscountType `json:"discount_type,omitempty"` - EligibleAmount *string `json:"eligible_amount,omitempty"` - DiscountAmount *string `json:"discount_amount,omitempty"` - LineItemBreakouts []InvoiceDiscountBreakout `json:"line_item_breakouts,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Uid = temp.Uid - p.Title = temp.Title - p.Code = temp.Code - p.SourceType = temp.SourceType - p.DiscountType = temp.DiscountType - p.EligibleAmount = temp.EligibleAmount - p.DiscountAmount = temp.DiscountAmount - p.LineItemBreakouts = temp.LineItemBreakouts - return nil + var temp proformaInvoiceDiscount + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Uid = temp.Uid + p.Title = temp.Title + p.Code = temp.Code + p.SourceType = temp.SourceType + p.DiscountType = temp.DiscountType + p.EligibleAmount = temp.EligibleAmount + p.DiscountAmount = temp.DiscountAmount + p.LineItemBreakouts = temp.LineItemBreakouts + return nil +} + +// TODO +type proformaInvoiceDiscount struct { + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + Code *string `json:"code,omitempty"` + SourceType *ProformaInvoiceDiscountSourceType `json:"source_type,omitempty"` + DiscountType *InvoiceDiscountType `json:"discount_type,omitempty"` + EligibleAmount *string `json:"eligible_amount,omitempty"` + DiscountAmount *string `json:"discount_amount,omitempty"` + LineItemBreakouts []InvoiceDiscountBreakout `json:"line_item_breakouts,omitempty"` } diff --git a/models/proforma_invoice_issued.go b/models/proforma_invoice_issued.go new file mode 100644 index 00000000..b61785e3 --- /dev/null +++ b/models/proforma_invoice_issued.go @@ -0,0 +1,140 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// ProformaInvoiceIssued represents a ProformaInvoiceIssued struct. +type ProformaInvoiceIssued struct { + Uid string `json:"uid"` + Number string `json:"number"` + Role string `json:"role"` + DeliveryDate time.Time `json:"delivery_date"` + CreatedAt time.Time `json:"created_at"` + DueAmount string `json:"due_amount"` + PaidAmount string `json:"paid_amount"` + TaxAmount string `json:"tax_amount"` + TotalAmount string `json:"total_amount"` + ProductName string `json:"product_name"` + LineItems []InvoiceLineItemEventData `json:"line_items"` +} + +// MarshalJSON implements the json.Marshaler interface for ProformaInvoiceIssued. +// It customizes the JSON marshaling process for ProformaInvoiceIssued objects. +func (p *ProformaInvoiceIssued) MarshalJSON() ( + []byte, + error) { + return json.Marshal(p.toMap()) +} + +// toMap converts the ProformaInvoiceIssued object to a map representation for JSON marshaling. +func (p *ProformaInvoiceIssued) toMap() map[string]any { + structMap := make(map[string]any) + structMap["uid"] = p.Uid + structMap["number"] = p.Number + structMap["role"] = p.Role + structMap["delivery_date"] = p.DeliveryDate.Format(DEFAULT_DATE) + structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) + structMap["due_amount"] = p.DueAmount + structMap["paid_amount"] = p.PaidAmount + structMap["tax_amount"] = p.TaxAmount + structMap["total_amount"] = p.TotalAmount + structMap["product_name"] = p.ProductName + structMap["line_items"] = p.LineItems + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ProformaInvoiceIssued. +// It customizes the JSON unmarshaling process for ProformaInvoiceIssued objects. +func (p *ProformaInvoiceIssued) UnmarshalJSON(input []byte) error { + var temp proformaInvoiceIssued + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + p.Uid = *temp.Uid + p.Number = *temp.Number + p.Role = *temp.Role + DeliveryDateVal, err := time.Parse(DEFAULT_DATE, *temp.DeliveryDate) + if err != nil { + log.Fatalf("Cannot Parse delivery_date as % s format.", DEFAULT_DATE) + } + p.DeliveryDate = DeliveryDateVal + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + p.CreatedAt = CreatedAtVal + p.DueAmount = *temp.DueAmount + p.PaidAmount = *temp.PaidAmount + p.TaxAmount = *temp.TaxAmount + p.TotalAmount = *temp.TotalAmount + p.ProductName = *temp.ProductName + p.LineItems = *temp.LineItems + return nil +} + +// TODO +type proformaInvoiceIssued struct { + Uid *string `json:"uid"` + Number *string `json:"number"` + Role *string `json:"role"` + DeliveryDate *string `json:"delivery_date"` + CreatedAt *string `json:"created_at"` + DueAmount *string `json:"due_amount"` + PaidAmount *string `json:"paid_amount"` + TaxAmount *string `json:"tax_amount"` + TotalAmount *string `json:"total_amount"` + ProductName *string `json:"product_name"` + LineItems *[]InvoiceLineItemEventData `json:"line_items"` +} + +func (p *proformaInvoiceIssued) validate() error { + var errs []string + if p.Uid == nil { + errs = append(errs, "required field `uid` is missing for type `Proforma Invoice Issued`") + } + if p.Number == nil { + errs = append(errs, "required field `number` is missing for type `Proforma Invoice Issued`") + } + if p.Role == nil { + errs = append(errs, "required field `role` is missing for type `Proforma Invoice Issued`") + } + if p.DeliveryDate == nil { + errs = append(errs, "required field `delivery_date` is missing for type `Proforma Invoice Issued`") + } + if p.CreatedAt == nil { + errs = append(errs, "required field `created_at` is missing for type `Proforma Invoice Issued`") + } + if p.DueAmount == nil { + errs = append(errs, "required field `due_amount` is missing for type `Proforma Invoice Issued`") + } + if p.PaidAmount == nil { + errs = append(errs, "required field `paid_amount` is missing for type `Proforma Invoice Issued`") + } + if p.TaxAmount == nil { + errs = append(errs, "required field `tax_amount` is missing for type `Proforma Invoice Issued`") + } + if p.TotalAmount == nil { + errs = append(errs, "required field `total_amount` is missing for type `Proforma Invoice Issued`") + } + if p.ProductName == nil { + errs = append(errs, "required field `product_name` is missing for type `Proforma Invoice Issued`") + } + if p.LineItems == nil { + errs = append(errs, "required field `line_items` is missing for type `Proforma Invoice Issued`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/proforma_invoice_payment.go b/models/proforma_invoice_payment.go index 654a2145..87406e60 100644 --- a/models/proforma_invoice_payment.go +++ b/models/proforma_invoice_payment.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // ProformaInvoicePayment represents a ProformaInvoicePayment struct. type ProformaInvoicePayment struct { - Memo *string `json:"memo,omitempty"` - OriginalAmount *string `json:"original_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - Prepayment *bool `json:"prepayment,omitempty"` + Memo *string `json:"memo,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` + Prepayment *bool `json:"prepayment,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ProformaInvoicePayment. +// MarshalJSON implements the json.Marshaler interface for ProformaInvoicePayment. // It customizes the JSON marshaling process for ProformaInvoicePayment objects. func (p *ProformaInvoicePayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProformaInvoicePayment object to a map representation for JSON marshaling. func (p *ProformaInvoicePayment) toMap() map[string]any { - structMap := make(map[string]any) - if p.Memo != nil { - structMap["memo"] = p.Memo - } - if p.OriginalAmount != nil { - structMap["original_amount"] = p.OriginalAmount - } - if p.AppliedAmount != nil { - structMap["applied_amount"] = p.AppliedAmount - } - if p.Prepayment != nil { - structMap["prepayment"] = p.Prepayment - } - return structMap + structMap := make(map[string]any) + if p.Memo != nil { + structMap["memo"] = p.Memo + } + if p.OriginalAmount != nil { + structMap["original_amount"] = p.OriginalAmount + } + if p.AppliedAmount != nil { + structMap["applied_amount"] = p.AppliedAmount + } + if p.Prepayment != nil { + structMap["prepayment"] = p.Prepayment + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProformaInvoicePayment. +// UnmarshalJSON implements the json.Unmarshaler interface for ProformaInvoicePayment. // It customizes the JSON unmarshaling process for ProformaInvoicePayment objects. func (p *ProformaInvoicePayment) UnmarshalJSON(input []byte) error { - temp := &struct { - Memo *string `json:"memo,omitempty"` - OriginalAmount *string `json:"original_amount,omitempty"` - AppliedAmount *string `json:"applied_amount,omitempty"` - Prepayment *bool `json:"prepayment,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Memo = temp.Memo - p.OriginalAmount = temp.OriginalAmount - p.AppliedAmount = temp.AppliedAmount - p.Prepayment = temp.Prepayment - return nil + var temp proformaInvoicePayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Memo = temp.Memo + p.OriginalAmount = temp.OriginalAmount + p.AppliedAmount = temp.AppliedAmount + p.Prepayment = temp.Prepayment + return nil +} + +// TODO +type proformaInvoicePayment struct { + Memo *string `json:"memo,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount,omitempty"` + Prepayment *bool `json:"prepayment,omitempty"` } diff --git a/models/proforma_invoice_tax.go b/models/proforma_invoice_tax.go index a4ab0730..8683ed04 100644 --- a/models/proforma_invoice_tax.go +++ b/models/proforma_invoice_tax.go @@ -1,78 +1,80 @@ package models import ( - "encoding/json" + "encoding/json" ) // ProformaInvoiceTax represents a ProformaInvoiceTax struct. type ProformaInvoiceTax struct { - Uid *string `json:"uid,omitempty"` - Title *string `json:"title,omitempty"` - SourceType *ProformaInvoiceTaxSourceType `json:"source_type,omitempty"` - Percentage *string `json:"percentage,omitempty"` - TaxableAmount *string `json:"taxable_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - LineItemBreakouts []InvoiceTaxBreakout `json:"line_item_breakouts,omitempty"` + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + SourceType *ProformaInvoiceTaxSourceType `json:"source_type,omitempty"` + Percentage *string `json:"percentage,omitempty"` + TaxableAmount *string `json:"taxable_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + LineItemBreakouts []InvoiceTaxBreakout `json:"line_item_breakouts,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ProformaInvoiceTax. +// MarshalJSON implements the json.Marshaler interface for ProformaInvoiceTax. // It customizes the JSON marshaling process for ProformaInvoiceTax objects. func (p *ProformaInvoiceTax) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the ProformaInvoiceTax object to a map representation for JSON marshaling. func (p *ProformaInvoiceTax) toMap() map[string]any { - structMap := make(map[string]any) - if p.Uid != nil { - structMap["uid"] = p.Uid - } - if p.Title != nil { - structMap["title"] = p.Title - } - if p.SourceType != nil { - structMap["source_type"] = p.SourceType - } - if p.Percentage != nil { - structMap["percentage"] = p.Percentage - } - if p.TaxableAmount != nil { - structMap["taxable_amount"] = p.TaxableAmount - } - if p.TaxAmount != nil { - structMap["tax_amount"] = p.TaxAmount - } - if p.LineItemBreakouts != nil { - structMap["line_item_breakouts"] = p.LineItemBreakouts - } - return structMap + structMap := make(map[string]any) + if p.Uid != nil { + structMap["uid"] = p.Uid + } + if p.Title != nil { + structMap["title"] = p.Title + } + if p.SourceType != nil { + structMap["source_type"] = p.SourceType + } + if p.Percentage != nil { + structMap["percentage"] = p.Percentage + } + if p.TaxableAmount != nil { + structMap["taxable_amount"] = p.TaxableAmount + } + if p.TaxAmount != nil { + structMap["tax_amount"] = p.TaxAmount + } + if p.LineItemBreakouts != nil { + structMap["line_item_breakouts"] = p.LineItemBreakouts + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ProformaInvoiceTax. +// UnmarshalJSON implements the json.Unmarshaler interface for ProformaInvoiceTax. // It customizes the JSON unmarshaling process for ProformaInvoiceTax objects. func (p *ProformaInvoiceTax) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Title *string `json:"title,omitempty"` - SourceType *ProformaInvoiceTaxSourceType `json:"source_type,omitempty"` - Percentage *string `json:"percentage,omitempty"` - TaxableAmount *string `json:"taxable_amount,omitempty"` - TaxAmount *string `json:"tax_amount,omitempty"` - LineItemBreakouts []InvoiceTaxBreakout `json:"line_item_breakouts,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Uid = temp.Uid - p.Title = temp.Title - p.SourceType = temp.SourceType - p.Percentage = temp.Percentage - p.TaxableAmount = temp.TaxableAmount - p.TaxAmount = temp.TaxAmount - p.LineItemBreakouts = temp.LineItemBreakouts - return nil + var temp proformaInvoiceTax + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Uid = temp.Uid + p.Title = temp.Title + p.SourceType = temp.SourceType + p.Percentage = temp.Percentage + p.TaxableAmount = temp.TaxableAmount + p.TaxAmount = temp.TaxAmount + p.LineItemBreakouts = temp.LineItemBreakouts + return nil +} + +// TODO +type proformaInvoiceTax struct { + Uid *string `json:"uid,omitempty"` + Title *string `json:"title,omitempty"` + SourceType *ProformaInvoiceTaxSourceType `json:"source_type,omitempty"` + Percentage *string `json:"percentage,omitempty"` + TaxableAmount *string `json:"taxable_amount,omitempty"` + TaxAmount *string `json:"tax_amount,omitempty"` + LineItemBreakouts []InvoiceTaxBreakout `json:"line_item_breakouts,omitempty"` } diff --git a/models/proration.go b/models/proration.go index 65ef5474..5aa2d783 100644 --- a/models/proration.go +++ b/models/proration.go @@ -1,43 +1,45 @@ package models import ( - "encoding/json" + "encoding/json" ) // Proration represents a Proration struct. type Proration struct { - // The alternative to sending preserve_period as a direct attribute to migration - PreservePeriod *bool `json:"preserve_period,omitempty"` + // The alternative to sending preserve_period as a direct attribute to migration + PreservePeriod *bool `json:"preserve_period,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Proration. +// MarshalJSON implements the json.Marshaler interface for Proration. // It customizes the JSON marshaling process for Proration objects. func (p *Proration) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the Proration object to a map representation for JSON marshaling. func (p *Proration) toMap() map[string]any { - structMap := make(map[string]any) - if p.PreservePeriod != nil { - structMap["preserve_period"] = p.PreservePeriod - } - return structMap + structMap := make(map[string]any) + if p.PreservePeriod != nil { + structMap["preserve_period"] = p.PreservePeriod + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Proration. +// UnmarshalJSON implements the json.Unmarshaler interface for Proration. // It customizes the JSON unmarshaling process for Proration objects. func (p *Proration) UnmarshalJSON(input []byte) error { - temp := &struct { - PreservePeriod *bool `json:"preserve_period,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.PreservePeriod = temp.PreservePeriod - return nil + var temp proration + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.PreservePeriod = temp.PreservePeriod + return nil +} + +// TODO +type proration struct { + PreservePeriod *bool `json:"preserve_period,omitempty"` } diff --git a/models/public_key.go b/models/public_key.go index 4cf8a67a..65402d2c 100644 --- a/models/public_key.go +++ b/models/public_key.go @@ -1,62 +1,64 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // PublicKey represents a PublicKey struct. type PublicKey struct { - PublicKey *string `json:"public_key,omitempty"` - RequiresSecurityToken *bool `json:"requires_security_token,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` + PublicKey *string `json:"public_key,omitempty"` + RequiresSecurityToken *bool `json:"requires_security_token,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PublicKey. +// MarshalJSON implements the json.Marshaler interface for PublicKey. // It customizes the JSON marshaling process for PublicKey objects. func (p *PublicKey) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PublicKey object to a map representation for JSON marshaling. func (p *PublicKey) toMap() map[string]any { - structMap := make(map[string]any) - if p.PublicKey != nil { - structMap["public_key"] = p.PublicKey - } - if p.RequiresSecurityToken != nil { - structMap["requires_security_token"] = p.RequiresSecurityToken - } - if p.CreatedAt != nil { - structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) - } - return structMap + structMap := make(map[string]any) + if p.PublicKey != nil { + structMap["public_key"] = p.PublicKey + } + if p.RequiresSecurityToken != nil { + structMap["requires_security_token"] = p.RequiresSecurityToken + } + if p.CreatedAt != nil { + structMap["created_at"] = p.CreatedAt.Format(time.RFC3339) + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PublicKey. +// UnmarshalJSON implements the json.Unmarshaler interface for PublicKey. // It customizes the JSON unmarshaling process for PublicKey objects. func (p *PublicKey) UnmarshalJSON(input []byte) error { - temp := &struct { - PublicKey *string `json:"public_key,omitempty"` - RequiresSecurityToken *bool `json:"requires_security_token,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.PublicKey = temp.PublicKey - p.RequiresSecurityToken = temp.RequiresSecurityToken - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - p.CreatedAt = &CreatedAtVal - } - return nil + var temp publicKey + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.PublicKey = temp.PublicKey + p.RequiresSecurityToken = temp.RequiresSecurityToken + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + p.CreatedAt = &CreatedAtVal + } + return nil +} + +// TODO +type publicKey struct { + PublicKey *string `json:"public_key,omitempty"` + RequiresSecurityToken *bool `json:"requires_security_token,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` } diff --git a/models/public_signup_page.go b/models/public_signup_page.go index 551e1c8a..19bd681c 100644 --- a/models/public_signup_page.go +++ b/models/public_signup_page.go @@ -1,64 +1,74 @@ package models import ( - "encoding/json" + "encoding/json" ) // PublicSignupPage represents a PublicSignupPage struct. type PublicSignupPage struct { - // The id of the signup page (public_signup_pages only) - Id *int `json:"id,omitempty"` - // The url to which a customer will be returned after a successful signup (public_signup_pages only) - ReturnUrl Optional[string] `json:"return_url"` - // The params to be appended to the return_url (public_signup_pages only) - ReturnParams Optional[string] `json:"return_params"` - // The url where the signup page can be viewed (public_signup_pages only) - Url *string `json:"url,omitempty"` + // The id of the signup page (public_signup_pages only) + Id *int `json:"id,omitempty"` + // The url to which a customer will be returned after a successful signup (public_signup_pages only) + ReturnUrl Optional[string] `json:"return_url"` + // The params to be appended to the return_url (public_signup_pages only) + ReturnParams Optional[string] `json:"return_params"` + // The url where the signup page can be viewed (public_signup_pages only) + Url *string `json:"url,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for PublicSignupPage. +// MarshalJSON implements the json.Marshaler interface for PublicSignupPage. // It customizes the JSON marshaling process for PublicSignupPage objects. func (p *PublicSignupPage) MarshalJSON() ( - []byte, - error) { - return json.Marshal(p.toMap()) + []byte, + error) { + return json.Marshal(p.toMap()) } // toMap converts the PublicSignupPage object to a map representation for JSON marshaling. func (p *PublicSignupPage) toMap() map[string]any { - structMap := make(map[string]any) - if p.Id != nil { - structMap["id"] = p.Id - } - if p.ReturnUrl.IsValueSet() { - structMap["return_url"] = p.ReturnUrl.Value() - } - if p.ReturnParams.IsValueSet() { - structMap["return_params"] = p.ReturnParams.Value() - } - if p.Url != nil { - structMap["url"] = p.Url - } - return structMap + structMap := make(map[string]any) + if p.Id != nil { + structMap["id"] = p.Id + } + if p.ReturnUrl.IsValueSet() { + if p.ReturnUrl.Value() != nil { + structMap["return_url"] = p.ReturnUrl.Value() + } else { + structMap["return_url"] = nil + } + } + if p.ReturnParams.IsValueSet() { + if p.ReturnParams.Value() != nil { + structMap["return_params"] = p.ReturnParams.Value() + } else { + structMap["return_params"] = nil + } + } + if p.Url != nil { + structMap["url"] = p.Url + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for PublicSignupPage. +// UnmarshalJSON implements the json.Unmarshaler interface for PublicSignupPage. // It customizes the JSON unmarshaling process for PublicSignupPage objects. func (p *PublicSignupPage) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - ReturnUrl Optional[string] `json:"return_url"` - ReturnParams Optional[string] `json:"return_params"` - Url *string `json:"url,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - p.Id = temp.Id - p.ReturnUrl = temp.ReturnUrl - p.ReturnParams = temp.ReturnParams - p.Url = temp.Url - return nil + var temp publicSignupPage + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + p.Id = temp.Id + p.ReturnUrl = temp.ReturnUrl + p.ReturnParams = temp.ReturnParams + p.Url = temp.Url + return nil +} + +// TODO +type publicSignupPage struct { + Id *int `json:"id,omitempty"` + ReturnUrl Optional[string] `json:"return_url"` + ReturnParams Optional[string] `json:"return_params"` + Url *string `json:"url,omitempty"` } diff --git a/models/quantity_based_component.go b/models/quantity_based_component.go index 979e6b64..17fd6cb4 100644 --- a/models/quantity_based_component.go +++ b/models/quantity_based_component.go @@ -1,167 +1,201 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // QuantityBasedComponent represents a QuantityBasedComponent struct. type QuantityBasedComponent struct { - // A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". - Name string `json:"name"` - // The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item - UnitName string `json:"unit_name"` - // A description for the component that will be displayed to the user on the hosted signup page. - Description *string `json:"description,omitempty"` - // A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'. - Handle *string `json:"handle,omitempty"` - // Boolean flag describing whether a component is taxable or not. - Taxable *bool `json:"taxable,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme PricingScheme `json:"pricing_scheme"` - // (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. - Prices []Price `json:"prices,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` - // The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 - UnitPrice *interface{} `json:"unit_price,omitempty"` - // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. - TaxCode *string `json:"tax_code,omitempty"` - // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - // deprecated May 2011 - use unit_price instead - PriceInCents *string `json:"price_in_cents,omitempty"` - Recurring *bool `json:"recurring,omitempty"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + // A name for this component that is suitable for showing customers and displaying on billing statements, ie. "Minutes". + Name string `json:"name"` + // The name of the unit of measurement for the component. It should be singular since it will be automatically pluralized when necessary. i.e. “message”, which may then be shown as “5 messages” on a subscription’s component line-item + UnitName string `json:"unit_name"` + // A description for the component that will be displayed to the user on the hosted signup page. + Description *string `json:"description,omitempty"` + // A unique identifier for your use that can be used to retrieve this component is subsequent requests. Must start with a letter or number and may only contain lowercase letters, numbers, or the characters '.', ':', '-', or '_'. + Handle *string `json:"handle,omitempty"` + // Boolean flag describing whether a component is taxable or not. + Taxable *bool `json:"taxable,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme PricingScheme `json:"pricing_scheme"` + // (Not required for ‘per_unit’ pricing schemes) One or more price brackets. See [Price Bracket Rules](https://chargify.zendesk.com/hc/en-us/articles/4407755865883#price-bracket-rules) for an overview of how price brackets work for different pricing schemes. + Prices []Price `json:"prices,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` + // The amount the customer will be charged per unit when the pricing scheme is “per_unit”. For On/Off Components, this is the amount that the customer will be charged when they turn the component on for the subscription. The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 + UnitPrice *QuantityBasedComponentUnitPrice `json:"unit_price,omitempty"` + // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. + TaxCode *string `json:"tax_code,omitempty"` + // (Only available on Relationship Invoicing sites) Boolean flag describing if the service date range should show for the component on generated invoices. + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + // deprecated May 2011 - use unit_price instead + PriceInCents *string `json:"price_in_cents,omitempty"` + Recurring *bool `json:"recurring,omitempty"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component's default price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component's default price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for QuantityBasedComponent. +// MarshalJSON implements the json.Marshaler interface for QuantityBasedComponent. // It customizes the JSON marshaling process for QuantityBasedComponent objects. func (q *QuantityBasedComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(q.toMap()) + []byte, + error) { + return json.Marshal(q.toMap()) } // toMap converts the QuantityBasedComponent object to a map representation for JSON marshaling. func (q *QuantityBasedComponent) toMap() map[string]any { - structMap := make(map[string]any) - structMap["name"] = q.Name - structMap["unit_name"] = q.UnitName - if q.Description != nil { - structMap["description"] = q.Description - } - if q.Handle != nil { - structMap["handle"] = q.Handle - } - if q.Taxable != nil { - structMap["taxable"] = q.Taxable - } - structMap["pricing_scheme"] = q.PricingScheme - if q.Prices != nil { - structMap["prices"] = q.Prices - } - if q.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = q.UpgradeCharge.Value() - } - if q.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = q.DowngradeCredit.Value() - } - if q.PricePoints != nil { - structMap["price_points"] = q.PricePoints - } - if q.UnitPrice != nil { - structMap["unit_price"] = q.UnitPrice - } - if q.TaxCode != nil { - structMap["tax_code"] = q.TaxCode - } - if q.HideDateRangeOnInvoice != nil { - structMap["hide_date_range_on_invoice"] = q.HideDateRangeOnInvoice - } - if q.PriceInCents != nil { - structMap["price_in_cents"] = q.PriceInCents - } - if q.Recurring != nil { - structMap["recurring"] = q.Recurring - } - if q.DisplayOnHostedPage != nil { - structMap["display_on_hosted_page"] = q.DisplayOnHostedPage - } - if q.AllowFractionalQuantities != nil { - structMap["allow_fractional_quantities"] = q.AllowFractionalQuantities - } - if q.PublicSignupPageIds != nil { - structMap["public_signup_page_ids"] = q.PublicSignupPageIds - } - if q.Interval != nil { - structMap["interval"] = q.Interval - } - if q.IntervalUnit != nil { - structMap["interval_unit"] = q.IntervalUnit - } - return structMap + structMap := make(map[string]any) + structMap["name"] = q.Name + structMap["unit_name"] = q.UnitName + if q.Description != nil { + structMap["description"] = q.Description + } + if q.Handle != nil { + structMap["handle"] = q.Handle + } + if q.Taxable != nil { + structMap["taxable"] = q.Taxable + } + structMap["pricing_scheme"] = q.PricingScheme + if q.Prices != nil { + structMap["prices"] = q.Prices + } + if q.UpgradeCharge.IsValueSet() { + if q.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = q.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if q.DowngradeCredit.IsValueSet() { + if q.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = q.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if q.PricePoints != nil { + structMap["price_points"] = q.PricePoints + } + if q.UnitPrice != nil { + structMap["unit_price"] = q.UnitPrice.toMap() + } + if q.TaxCode != nil { + structMap["tax_code"] = q.TaxCode + } + if q.HideDateRangeOnInvoice != nil { + structMap["hide_date_range_on_invoice"] = q.HideDateRangeOnInvoice + } + if q.PriceInCents != nil { + structMap["price_in_cents"] = q.PriceInCents + } + if q.Recurring != nil { + structMap["recurring"] = q.Recurring + } + if q.DisplayOnHostedPage != nil { + structMap["display_on_hosted_page"] = q.DisplayOnHostedPage + } + if q.AllowFractionalQuantities != nil { + structMap["allow_fractional_quantities"] = q.AllowFractionalQuantities + } + if q.PublicSignupPageIds != nil { + structMap["public_signup_page_ids"] = q.PublicSignupPageIds + } + if q.Interval != nil { + structMap["interval"] = q.Interval + } + if q.IntervalUnit != nil { + structMap["interval_unit"] = q.IntervalUnit + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for QuantityBasedComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for QuantityBasedComponent. // It customizes the JSON unmarshaling process for QuantityBasedComponent objects. func (q *QuantityBasedComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - Name string `json:"name"` - UnitName string `json:"unit_name"` - Description *string `json:"description,omitempty"` - Handle *string `json:"handle,omitempty"` - Taxable *bool `json:"taxable,omitempty"` - PricingScheme PricingScheme `json:"pricing_scheme"` - Prices []Price `json:"prices,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` - UnitPrice *interface{} `json:"unit_price,omitempty"` - TaxCode *string `json:"tax_code,omitempty"` - HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` - PriceInCents *string `json:"price_in_cents,omitempty"` - Recurring *bool `json:"recurring,omitempty"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - q.Name = temp.Name - q.UnitName = temp.UnitName - q.Description = temp.Description - q.Handle = temp.Handle - q.Taxable = temp.Taxable - q.PricingScheme = temp.PricingScheme - q.Prices = temp.Prices - q.UpgradeCharge = temp.UpgradeCharge - q.DowngradeCredit = temp.DowngradeCredit - q.PricePoints = temp.PricePoints - q.UnitPrice = temp.UnitPrice - q.TaxCode = temp.TaxCode - q.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice - q.PriceInCents = temp.PriceInCents - q.Recurring = temp.Recurring - q.DisplayOnHostedPage = temp.DisplayOnHostedPage - q.AllowFractionalQuantities = temp.AllowFractionalQuantities - q.PublicSignupPageIds = temp.PublicSignupPageIds - q.Interval = temp.Interval - q.IntervalUnit = temp.IntervalUnit - return nil + var temp quantityBasedComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + q.Name = *temp.Name + q.UnitName = *temp.UnitName + q.Description = temp.Description + q.Handle = temp.Handle + q.Taxable = temp.Taxable + q.PricingScheme = *temp.PricingScheme + q.Prices = temp.Prices + q.UpgradeCharge = temp.UpgradeCharge + q.DowngradeCredit = temp.DowngradeCredit + q.PricePoints = temp.PricePoints + q.UnitPrice = temp.UnitPrice + q.TaxCode = temp.TaxCode + q.HideDateRangeOnInvoice = temp.HideDateRangeOnInvoice + q.PriceInCents = temp.PriceInCents + q.Recurring = temp.Recurring + q.DisplayOnHostedPage = temp.DisplayOnHostedPage + q.AllowFractionalQuantities = temp.AllowFractionalQuantities + q.PublicSignupPageIds = temp.PublicSignupPageIds + q.Interval = temp.Interval + q.IntervalUnit = temp.IntervalUnit + return nil +} + +// TODO +type quantityBasedComponent struct { + Name *string `json:"name"` + UnitName *string `json:"unit_name"` + Description *string `json:"description,omitempty"` + Handle *string `json:"handle,omitempty"` + Taxable *bool `json:"taxable,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme"` + Prices []Price `json:"prices,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + PricePoints []ComponentPricePointItem `json:"price_points,omitempty"` + UnitPrice *QuantityBasedComponentUnitPrice `json:"unit_price,omitempty"` + TaxCode *string `json:"tax_code,omitempty"` + HideDateRangeOnInvoice *bool `json:"hide_date_range_on_invoice,omitempty"` + PriceInCents *string `json:"price_in_cents,omitempty"` + Recurring *bool `json:"recurring,omitempty"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + PublicSignupPageIds []int `json:"public_signup_page_ids,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` +} + +func (q *quantityBasedComponent) validate() error { + var errs []string + if q.Name == nil { + errs = append(errs, "required field `name` is missing for type `Quantity Based Component`") + } + if q.UnitName == nil { + errs = append(errs, "required field `unit_name` is missing for type `Quantity Based Component`") + } + if q.PricingScheme == nil { + errs = append(errs, "required field `pricing_scheme` is missing for type `Quantity Based Component`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/quantity_based_component_unit_price.go b/models/quantity_based_component_unit_price.go new file mode 100644 index 00000000..04c440be --- /dev/null +++ b/models/quantity_based_component_unit_price.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// QuantityBasedComponentUnitPrice represents a QuantityBasedComponentUnitPrice struct. +// This is a container for one-of cases. +type QuantityBasedComponentUnitPrice struct { + value any + isString bool + isPrecision bool +} + +// String converts the QuantityBasedComponentUnitPrice object to a string representation. +func (q QuantityBasedComponentUnitPrice) String() string { + if bytes, err := json.Marshal(q.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for QuantityBasedComponentUnitPrice. +// It customizes the JSON marshaling process for QuantityBasedComponentUnitPrice objects. +func (q *QuantityBasedComponentUnitPrice) MarshalJSON() ( + []byte, + error) { + if q.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.QuantityBasedComponentUnitPriceContainer.From*` functions to initialize the QuantityBasedComponentUnitPrice object.") + } + return json.Marshal(q.toMap()) +} + +// toMap converts the QuantityBasedComponentUnitPrice object to a map representation for JSON marshaling. +func (q *QuantityBasedComponentUnitPrice) toMap() any { + switch obj := q.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for QuantityBasedComponentUnitPrice. +// It customizes the JSON unmarshaling process for QuantityBasedComponentUnitPrice objects. +func (q *QuantityBasedComponentUnitPrice) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &q.isString), + NewTypeHolder(new(float64), false, &q.isPrecision), + ) + + q.value = result + return err +} + +func (q *QuantityBasedComponentUnitPrice) AsString() ( + *string, + bool) { + if !q.isString { + return nil, false + } + return q.value.(*string), true +} + +func (q *QuantityBasedComponentUnitPrice) AsPrecision() ( + *float64, + bool) { + if !q.isPrecision { + return nil, false + } + return q.value.(*float64), true +} + +// internalQuantityBasedComponentUnitPrice represents a quantityBasedComponentUnitPrice struct. +// This is a container for one-of cases. +type internalQuantityBasedComponentUnitPrice struct{} + +var QuantityBasedComponentUnitPriceContainer internalQuantityBasedComponentUnitPrice + +func (q *internalQuantityBasedComponentUnitPrice) FromString(val string) QuantityBasedComponentUnitPrice { + return QuantityBasedComponentUnitPrice{value: &val} +} + +func (q *internalQuantityBasedComponentUnitPrice) FromPrecision(val float64) QuantityBasedComponentUnitPrice { + return QuantityBasedComponentUnitPrice{value: &val} +} diff --git a/models/reactivate_subscription_group_request.go b/models/reactivate_subscription_group_request.go index 6851d658..f2e61510 100644 --- a/models/reactivate_subscription_group_request.go +++ b/models/reactivate_subscription_group_request.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // ReactivateSubscriptionGroupRequest represents a ReactivateSubscriptionGroupRequest struct. type ReactivateSubscriptionGroupRequest struct { - Resume *bool `json:"resume,omitempty"` - ResumeMembers *bool `json:"resume_members,omitempty"` + Resume *bool `json:"resume,omitempty"` + ResumeMembers *bool `json:"resume_members,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ReactivateSubscriptionGroupRequest. +// MarshalJSON implements the json.Marshaler interface for ReactivateSubscriptionGroupRequest. // It customizes the JSON marshaling process for ReactivateSubscriptionGroupRequest objects. func (r *ReactivateSubscriptionGroupRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ReactivateSubscriptionGroupRequest object to a map representation for JSON marshaling. func (r *ReactivateSubscriptionGroupRequest) toMap() map[string]any { - structMap := make(map[string]any) - if r.Resume != nil { - structMap["resume"] = r.Resume - } - if r.ResumeMembers != nil { - structMap["resume_members"] = r.ResumeMembers - } - return structMap + structMap := make(map[string]any) + if r.Resume != nil { + structMap["resume"] = r.Resume + } + if r.ResumeMembers != nil { + structMap["resume_members"] = r.ResumeMembers + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ReactivateSubscriptionGroupRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for ReactivateSubscriptionGroupRequest. // It customizes the JSON unmarshaling process for ReactivateSubscriptionGroupRequest objects. func (r *ReactivateSubscriptionGroupRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Resume *bool `json:"resume,omitempty"` - ResumeMembers *bool `json:"resume_members,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Resume = temp.Resume - r.ResumeMembers = temp.ResumeMembers - return nil + var temp reactivateSubscriptionGroupRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.Resume = temp.Resume + r.ResumeMembers = temp.ResumeMembers + return nil +} + +// TODO +type reactivateSubscriptionGroupRequest struct { + Resume *bool `json:"resume,omitempty"` + ResumeMembers *bool `json:"resume_members,omitempty"` } diff --git a/models/reactivate_subscription_group_response.go b/models/reactivate_subscription_group_response.go index 1acc9c8e..88fa5bc3 100644 --- a/models/reactivate_subscription_group_response.go +++ b/models/reactivate_subscription_group_response.go @@ -1,98 +1,100 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // ReactivateSubscriptionGroupResponse represents a ReactivateSubscriptionGroupResponse struct. type ReactivateSubscriptionGroupResponse struct { - Uid *string `json:"uid,omitempty"` - Scheme *int `json:"scheme,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - SubscriptionIds []int `json:"subscription_ids,omitempty"` - PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` - NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` - State *string `json:"state,omitempty"` - CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` + Uid *string `json:"uid,omitempty"` + Scheme *int `json:"scheme,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + SubscriptionIds []int `json:"subscription_ids,omitempty"` + PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` + NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` + State *string `json:"state,omitempty"` + CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ReactivateSubscriptionGroupResponse. +// MarshalJSON implements the json.Marshaler interface for ReactivateSubscriptionGroupResponse. // It customizes the JSON marshaling process for ReactivateSubscriptionGroupResponse objects. func (r *ReactivateSubscriptionGroupResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ReactivateSubscriptionGroupResponse object to a map representation for JSON marshaling. func (r *ReactivateSubscriptionGroupResponse) toMap() map[string]any { - structMap := make(map[string]any) - if r.Uid != nil { - structMap["uid"] = r.Uid - } - if r.Scheme != nil { - structMap["scheme"] = r.Scheme - } - if r.CustomerId != nil { - structMap["customer_id"] = r.CustomerId - } - if r.PaymentProfileId != nil { - structMap["payment_profile_id"] = r.PaymentProfileId - } - if r.SubscriptionIds != nil { - structMap["subscription_ids"] = r.SubscriptionIds - } - if r.PrimarySubscriptionId != nil { - structMap["primary_subscription_id"] = r.PrimarySubscriptionId - } - if r.NextAssessmentAt != nil { - structMap["next_assessment_at"] = r.NextAssessmentAt.Format(time.RFC3339) - } - if r.State != nil { - structMap["state"] = r.State - } - if r.CancelAtEndOfPeriod != nil { - structMap["cancel_at_end_of_period"] = r.CancelAtEndOfPeriod - } - return structMap + structMap := make(map[string]any) + if r.Uid != nil { + structMap["uid"] = r.Uid + } + if r.Scheme != nil { + structMap["scheme"] = r.Scheme + } + if r.CustomerId != nil { + structMap["customer_id"] = r.CustomerId + } + if r.PaymentProfileId != nil { + structMap["payment_profile_id"] = r.PaymentProfileId + } + if r.SubscriptionIds != nil { + structMap["subscription_ids"] = r.SubscriptionIds + } + if r.PrimarySubscriptionId != nil { + structMap["primary_subscription_id"] = r.PrimarySubscriptionId + } + if r.NextAssessmentAt != nil { + structMap["next_assessment_at"] = r.NextAssessmentAt.Format(time.RFC3339) + } + if r.State != nil { + structMap["state"] = r.State + } + if r.CancelAtEndOfPeriod != nil { + structMap["cancel_at_end_of_period"] = r.CancelAtEndOfPeriod + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ReactivateSubscriptionGroupResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ReactivateSubscriptionGroupResponse. // It customizes the JSON unmarshaling process for ReactivateSubscriptionGroupResponse objects. func (r *ReactivateSubscriptionGroupResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Scheme *int `json:"scheme,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - SubscriptionIds []int `json:"subscription_ids,omitempty"` - PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` - NextAssessmentAt *string `json:"next_assessment_at,omitempty"` - State *string `json:"state,omitempty"` - CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Uid = temp.Uid - r.Scheme = temp.Scheme - r.CustomerId = temp.CustomerId - r.PaymentProfileId = temp.PaymentProfileId - r.SubscriptionIds = temp.SubscriptionIds - r.PrimarySubscriptionId = temp.PrimarySubscriptionId - if temp.NextAssessmentAt != nil { - NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) - if err != nil { - log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) - } - r.NextAssessmentAt = &NextAssessmentAtVal - } - r.State = temp.State - r.CancelAtEndOfPeriod = temp.CancelAtEndOfPeriod - return nil + var temp reactivateSubscriptionGroupResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.Uid = temp.Uid + r.Scheme = temp.Scheme + r.CustomerId = temp.CustomerId + r.PaymentProfileId = temp.PaymentProfileId + r.SubscriptionIds = temp.SubscriptionIds + r.PrimarySubscriptionId = temp.PrimarySubscriptionId + if temp.NextAssessmentAt != nil { + NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) + if err != nil { + log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) + } + r.NextAssessmentAt = &NextAssessmentAtVal + } + r.State = temp.State + r.CancelAtEndOfPeriod = temp.CancelAtEndOfPeriod + return nil +} + +// TODO +type reactivateSubscriptionGroupResponse struct { + Uid *string `json:"uid,omitempty"` + Scheme *int `json:"scheme,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + SubscriptionIds []int `json:"subscription_ids,omitempty"` + PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` + NextAssessmentAt *string `json:"next_assessment_at,omitempty"` + State *string `json:"state,omitempty"` + CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` } diff --git a/models/reactivate_subscription_request.go b/models/reactivate_subscription_request.go index 09ffc66c..b6aeff35 100644 --- a/models/reactivate_subscription_request.go +++ b/models/reactivate_subscription_request.go @@ -1,78 +1,80 @@ package models import ( - "encoding/json" + "encoding/json" ) // ReactivateSubscriptionRequest represents a ReactivateSubscriptionRequest struct. type ReactivateSubscriptionRequest struct { - // These values are only applicable to subscriptions using calendar billing - CalendarBilling *ReactivationBilling `json:"calendar_billing,omitempty"` - // If `true` is sent, the reactivated Subscription will include a trial if one is available. If `false` is sent, the trial period will be ignored. - IncludeTrial *bool `json:"include_trial,omitempty"` - // If `true` is passed, the existing subscription balance will NOT be cleared/reset before adding the additional reactivation charges. - PreserveBalance *bool `json:"preserve_balance,omitempty"` - // The coupon code to be applied during reactivation. - CouponCode *string `json:"coupon_code,omitempty"` - // If true is sent, Chargify will use service credits and prepayments upon reactivation. If false is sent, the service credits and prepayments will be ignored. - UseCreditsAndPrepayments *bool `json:"use_credits_and_prepayments,omitempty"` - // If `true`, Chargify will attempt to resume the subscription's billing period. if not resumable, the subscription will be reactivated with a new billing period. If `false`: Chargify will only attempt to reactivate the subscription. - Resume *interface{} `json:"resume,omitempty"` + // These values are only applicable to subscriptions using calendar billing + CalendarBilling *ReactivationBilling `json:"calendar_billing,omitempty"` + // If `true` is sent, the reactivated Subscription will include a trial if one is available. If `false` is sent, the trial period will be ignored. + IncludeTrial *bool `json:"include_trial,omitempty"` + // If `true` is passed, the existing subscription balance will NOT be cleared/reset before adding the additional reactivation charges. + PreserveBalance *bool `json:"preserve_balance,omitempty"` + // The coupon code to be applied during reactivation. + CouponCode *string `json:"coupon_code,omitempty"` + // If true is sent, Chargify will use service credits and prepayments upon reactivation. If false is sent, the service credits and prepayments will be ignored. + UseCreditsAndPrepayments *bool `json:"use_credits_and_prepayments,omitempty"` + // If `true`, Chargify will attempt to resume the subscription's billing period. if not resumable, the subscription will be reactivated with a new billing period. If `false`: Chargify will only attempt to reactivate the subscription. + Resume *ReactivateSubscriptionRequestResume `json:"resume,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ReactivateSubscriptionRequest. +// MarshalJSON implements the json.Marshaler interface for ReactivateSubscriptionRequest. // It customizes the JSON marshaling process for ReactivateSubscriptionRequest objects. func (r *ReactivateSubscriptionRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ReactivateSubscriptionRequest object to a map representation for JSON marshaling. func (r *ReactivateSubscriptionRequest) toMap() map[string]any { - structMap := make(map[string]any) - if r.CalendarBilling != nil { - structMap["calendar_billing"] = r.CalendarBilling.toMap() - } - if r.IncludeTrial != nil { - structMap["include_trial"] = r.IncludeTrial - } - if r.PreserveBalance != nil { - structMap["preserve_balance"] = r.PreserveBalance - } - if r.CouponCode != nil { - structMap["coupon_code"] = r.CouponCode - } - if r.UseCreditsAndPrepayments != nil { - structMap["use_credits_and_prepayments"] = r.UseCreditsAndPrepayments - } - if r.Resume != nil { - structMap["resume"] = r.Resume - } - return structMap + structMap := make(map[string]any) + if r.CalendarBilling != nil { + structMap["calendar_billing"] = r.CalendarBilling.toMap() + } + if r.IncludeTrial != nil { + structMap["include_trial"] = r.IncludeTrial + } + if r.PreserveBalance != nil { + structMap["preserve_balance"] = r.PreserveBalance + } + if r.CouponCode != nil { + structMap["coupon_code"] = r.CouponCode + } + if r.UseCreditsAndPrepayments != nil { + structMap["use_credits_and_prepayments"] = r.UseCreditsAndPrepayments + } + if r.Resume != nil { + structMap["resume"] = r.Resume.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ReactivateSubscriptionRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for ReactivateSubscriptionRequest. // It customizes the JSON unmarshaling process for ReactivateSubscriptionRequest objects. func (r *ReactivateSubscriptionRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - CalendarBilling *ReactivationBilling `json:"calendar_billing,omitempty"` - IncludeTrial *bool `json:"include_trial,omitempty"` - PreserveBalance *bool `json:"preserve_balance,omitempty"` - CouponCode *string `json:"coupon_code,omitempty"` - UseCreditsAndPrepayments *bool `json:"use_credits_and_prepayments,omitempty"` - Resume *interface{} `json:"resume,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.CalendarBilling = temp.CalendarBilling - r.IncludeTrial = temp.IncludeTrial - r.PreserveBalance = temp.PreserveBalance - r.CouponCode = temp.CouponCode - r.UseCreditsAndPrepayments = temp.UseCreditsAndPrepayments - r.Resume = temp.Resume - return nil + var temp reactivateSubscriptionRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.CalendarBilling = temp.CalendarBilling + r.IncludeTrial = temp.IncludeTrial + r.PreserveBalance = temp.PreserveBalance + r.CouponCode = temp.CouponCode + r.UseCreditsAndPrepayments = temp.UseCreditsAndPrepayments + r.Resume = temp.Resume + return nil +} + +// TODO +type reactivateSubscriptionRequest struct { + CalendarBilling *ReactivationBilling `json:"calendar_billing,omitempty"` + IncludeTrial *bool `json:"include_trial,omitempty"` + PreserveBalance *bool `json:"preserve_balance,omitempty"` + CouponCode *string `json:"coupon_code,omitempty"` + UseCreditsAndPrepayments *bool `json:"use_credits_and_prepayments,omitempty"` + Resume *ReactivateSubscriptionRequestResume `json:"resume,omitempty"` } diff --git a/models/reactivate_subscription_request_resume.go b/models/reactivate_subscription_request_resume.go new file mode 100644 index 00000000..714161eb --- /dev/null +++ b/models/reactivate_subscription_request_resume.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ReactivateSubscriptionRequestResume represents a ReactivateSubscriptionRequestResume struct. +// This is a container for one-of cases. +type ReactivateSubscriptionRequestResume struct { + value any + isBoolean bool + isResumeOptions bool +} + +// String converts the ReactivateSubscriptionRequestResume object to a string representation. +func (r ReactivateSubscriptionRequestResume) String() string { + if bytes, err := json.Marshal(r.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ReactivateSubscriptionRequestResume. +// It customizes the JSON marshaling process for ReactivateSubscriptionRequestResume objects. +func (r *ReactivateSubscriptionRequestResume) MarshalJSON() ( + []byte, + error) { + if r.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ReactivateSubscriptionRequestResumeContainer.From*` functions to initialize the ReactivateSubscriptionRequestResume object.") + } + return json.Marshal(r.toMap()) +} + +// toMap converts the ReactivateSubscriptionRequestResume object to a map representation for JSON marshaling. +func (r *ReactivateSubscriptionRequestResume) toMap() any { + switch obj := r.value.(type) { + case *bool: + return *obj + case *ResumeOptions: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ReactivateSubscriptionRequestResume. +// It customizes the JSON unmarshaling process for ReactivateSubscriptionRequestResume objects. +func (r *ReactivateSubscriptionRequestResume) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(bool), false, &r.isBoolean), + NewTypeHolder(&ResumeOptions{}, false, &r.isResumeOptions), + ) + + r.value = result + return err +} + +func (r *ReactivateSubscriptionRequestResume) AsBoolean() ( + *bool, + bool) { + if !r.isBoolean { + return nil, false + } + return r.value.(*bool), true +} + +func (r *ReactivateSubscriptionRequestResume) AsResumeOptions() ( + *ResumeOptions, + bool) { + if !r.isResumeOptions { + return nil, false + } + return r.value.(*ResumeOptions), true +} + +// internalReactivateSubscriptionRequestResume represents a reactivateSubscriptionRequestResume struct. +// This is a container for one-of cases. +type internalReactivateSubscriptionRequestResume struct{} + +var ReactivateSubscriptionRequestResumeContainer internalReactivateSubscriptionRequestResume + +func (r *internalReactivateSubscriptionRequestResume) FromBoolean(val bool) ReactivateSubscriptionRequestResume { + return ReactivateSubscriptionRequestResume{value: &val} +} + +func (r *internalReactivateSubscriptionRequestResume) FromResumeOptions(val ResumeOptions) ReactivateSubscriptionRequestResume { + return ReactivateSubscriptionRequestResume{value: &val} +} diff --git a/models/reactivation_billing.go b/models/reactivation_billing.go index 5968db93..e0ced7b4 100644 --- a/models/reactivation_billing.go +++ b/models/reactivation_billing.go @@ -1,44 +1,46 @@ package models import ( - "encoding/json" + "encoding/json" ) -// ReactivationBilling represents a ReactivationBilling struct. +// ReactivationBilling represents a ReactivationBilling struct. // These values are only applicable to subscriptions using calendar billing type ReactivationBilling struct { - // You may choose how to handle the reactivation charge for that subscription: 1) `prorated` A prorated charge for the product price will be attempted for to complete the period 2) `immediate` A full-price charge for the product price will be attempted immediately 3) `delayed` A full-price charge for the product price will be attempted at the next renewal - ReactivationCharge *ReactivationCharge `json:"reactivation_charge,omitempty"` + // You may choose how to handle the reactivation charge for that subscription: 1) `prorated` A prorated charge for the product price will be attempted for to complete the period 2) `immediate` A full-price charge for the product price will be attempted immediately 3) `delayed` A full-price charge for the product price will be attempted at the next renewal + ReactivationCharge *ReactivationCharge `json:"reactivation_charge,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ReactivationBilling. +// MarshalJSON implements the json.Marshaler interface for ReactivationBilling. // It customizes the JSON marshaling process for ReactivationBilling objects. func (r *ReactivationBilling) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ReactivationBilling object to a map representation for JSON marshaling. func (r *ReactivationBilling) toMap() map[string]any { - structMap := make(map[string]any) - if r.ReactivationCharge != nil { - structMap["reactivation_charge"] = r.ReactivationCharge - } - return structMap + structMap := make(map[string]any) + if r.ReactivationCharge != nil { + structMap["reactivation_charge"] = r.ReactivationCharge + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ReactivationBilling. +// UnmarshalJSON implements the json.Unmarshaler interface for ReactivationBilling. // It customizes the JSON unmarshaling process for ReactivationBilling objects. func (r *ReactivationBilling) UnmarshalJSON(input []byte) error { - temp := &struct { - ReactivationCharge *ReactivationCharge `json:"reactivation_charge,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.ReactivationCharge = temp.ReactivationCharge - return nil + var temp reactivationBilling + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.ReactivationCharge = temp.ReactivationCharge + return nil +} + +// TODO +type reactivationBilling struct { + ReactivationCharge *ReactivationCharge `json:"reactivation_charge,omitempty"` } diff --git a/models/read_product_price_point_price_point_id.go b/models/read_product_price_point_price_point_id.go new file mode 100644 index 00000000..d0bead2e --- /dev/null +++ b/models/read_product_price_point_price_point_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ReadProductPricePointPricePointId represents a ReadProductPricePointPricePointId struct. +// This is a container for one-of cases. +type ReadProductPricePointPricePointId struct { + value any + isNumber bool + isString bool +} + +// String converts the ReadProductPricePointPricePointId object to a string representation. +func (r ReadProductPricePointPricePointId) String() string { + if bytes, err := json.Marshal(r.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ReadProductPricePointPricePointId. +// It customizes the JSON marshaling process for ReadProductPricePointPricePointId objects. +func (r *ReadProductPricePointPricePointId) MarshalJSON() ( + []byte, + error) { + if r.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ReadProductPricePointPricePointIdContainer.From*` functions to initialize the ReadProductPricePointPricePointId object.") + } + return json.Marshal(r.toMap()) +} + +// toMap converts the ReadProductPricePointPricePointId object to a map representation for JSON marshaling. +func (r *ReadProductPricePointPricePointId) toMap() any { + switch obj := r.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ReadProductPricePointPricePointId. +// It customizes the JSON unmarshaling process for ReadProductPricePointPricePointId objects. +func (r *ReadProductPricePointPricePointId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &r.isNumber), + NewTypeHolder(new(string), false, &r.isString), + ) + + r.value = result + return err +} + +func (r *ReadProductPricePointPricePointId) AsNumber() ( + *int, + bool) { + if !r.isNumber { + return nil, false + } + return r.value.(*int), true +} + +func (r *ReadProductPricePointPricePointId) AsString() ( + *string, + bool) { + if !r.isString { + return nil, false + } + return r.value.(*string), true +} + +// internalReadProductPricePointPricePointId represents a readProductPricePointPricePointId struct. +// This is a container for one-of cases. +type internalReadProductPricePointPricePointId struct{} + +var ReadProductPricePointPricePointIdContainer internalReadProductPricePointPricePointId + +func (r *internalReadProductPricePointPricePointId) FromNumber(val int) ReadProductPricePointPricePointId { + return ReadProductPricePointPricePointId{value: &val} +} + +func (r *internalReadProductPricePointPricePointId) FromString(val string) ReadProductPricePointPricePointId { + return ReadProductPricePointPricePointId{value: &val} +} diff --git a/models/read_product_price_point_product_id.go b/models/read_product_price_point_product_id.go new file mode 100644 index 00000000..678a8116 --- /dev/null +++ b/models/read_product_price_point_product_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// ReadProductPricePointProductId represents a ReadProductPricePointProductId struct. +// This is a container for one-of cases. +type ReadProductPricePointProductId struct { + value any + isNumber bool + isString bool +} + +// String converts the ReadProductPricePointProductId object to a string representation. +func (r ReadProductPricePointProductId) String() string { + if bytes, err := json.Marshal(r.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for ReadProductPricePointProductId. +// It customizes the JSON marshaling process for ReadProductPricePointProductId objects. +func (r *ReadProductPricePointProductId) MarshalJSON() ( + []byte, + error) { + if r.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.ReadProductPricePointProductIdContainer.From*` functions to initialize the ReadProductPricePointProductId object.") + } + return json.Marshal(r.toMap()) +} + +// toMap converts the ReadProductPricePointProductId object to a map representation for JSON marshaling. +func (r *ReadProductPricePointProductId) toMap() any { + switch obj := r.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ReadProductPricePointProductId. +// It customizes the JSON unmarshaling process for ReadProductPricePointProductId objects. +func (r *ReadProductPricePointProductId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &r.isNumber), + NewTypeHolder(new(string), false, &r.isString), + ) + + r.value = result + return err +} + +func (r *ReadProductPricePointProductId) AsNumber() ( + *int, + bool) { + if !r.isNumber { + return nil, false + } + return r.value.(*int), true +} + +func (r *ReadProductPricePointProductId) AsString() ( + *string, + bool) { + if !r.isString { + return nil, false + } + return r.value.(*string), true +} + +// internalReadProductPricePointProductId represents a readProductPricePointProductId struct. +// This is a container for one-of cases. +type internalReadProductPricePointProductId struct{} + +var ReadProductPricePointProductIdContainer internalReadProductPricePointProductId + +func (r *internalReadProductPricePointProductId) FromNumber(val int) ReadProductPricePointProductId { + return ReadProductPricePointProductId{value: &val} +} + +func (r *internalReadProductPricePointProductId) FromString(val string) ReadProductPricePointProductId { + return ReadProductPricePointProductId{value: &val} +} diff --git a/models/reason_code.go b/models/reason_code.go index 16549355..629039bb 100644 --- a/models/reason_code.go +++ b/models/reason_code.go @@ -1,92 +1,94 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // ReasonCode represents a ReasonCode struct. type ReasonCode struct { - Id *int `json:"id,omitempty"` - SiteId *int `json:"site_id,omitempty"` - Code *string `json:"code,omitempty"` - Description *string `json:"description,omitempty"` - Position *int `json:"position,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` + Id *int `json:"id,omitempty"` + SiteId *int `json:"site_id,omitempty"` + Code *string `json:"code,omitempty"` + Description *string `json:"description,omitempty"` + Position *int `json:"position,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ReasonCode. +// MarshalJSON implements the json.Marshaler interface for ReasonCode. // It customizes the JSON marshaling process for ReasonCode objects. func (r *ReasonCode) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ReasonCode object to a map representation for JSON marshaling. func (r *ReasonCode) toMap() map[string]any { - structMap := make(map[string]any) - if r.Id != nil { - structMap["id"] = r.Id - } - if r.SiteId != nil { - structMap["site_id"] = r.SiteId - } - if r.Code != nil { - structMap["code"] = r.Code - } - if r.Description != nil { - structMap["description"] = r.Description - } - if r.Position != nil { - structMap["position"] = r.Position - } - if r.CreatedAt != nil { - structMap["created_at"] = r.CreatedAt.Format(time.RFC3339) - } - if r.UpdatedAt != nil { - structMap["updated_at"] = r.UpdatedAt.Format(time.RFC3339) - } - return structMap + structMap := make(map[string]any) + if r.Id != nil { + structMap["id"] = r.Id + } + if r.SiteId != nil { + structMap["site_id"] = r.SiteId + } + if r.Code != nil { + structMap["code"] = r.Code + } + if r.Description != nil { + structMap["description"] = r.Description + } + if r.Position != nil { + structMap["position"] = r.Position + } + if r.CreatedAt != nil { + structMap["created_at"] = r.CreatedAt.Format(time.RFC3339) + } + if r.UpdatedAt != nil { + structMap["updated_at"] = r.UpdatedAt.Format(time.RFC3339) + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ReasonCode. +// UnmarshalJSON implements the json.Unmarshaler interface for ReasonCode. // It customizes the JSON unmarshaling process for ReasonCode objects. func (r *ReasonCode) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - SiteId *int `json:"site_id,omitempty"` - Code *string `json:"code,omitempty"` - Description *string `json:"description,omitempty"` - Position *int `json:"position,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Id = temp.Id - r.SiteId = temp.SiteId - r.Code = temp.Code - r.Description = temp.Description - r.Position = temp.Position - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - r.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - r.UpdatedAt = &UpdatedAtVal - } - return nil + var temp reasonCode + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.Id = temp.Id + r.SiteId = temp.SiteId + r.Code = temp.Code + r.Description = temp.Description + r.Position = temp.Position + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + r.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + r.UpdatedAt = &UpdatedAtVal + } + return nil +} + +// TODO +type reasonCode struct { + Id *int `json:"id,omitempty"` + SiteId *int `json:"site_id,omitempty"` + Code *string `json:"code,omitempty"` + Description *string `json:"description,omitempty"` + Position *int `json:"position,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` } diff --git a/models/reason_code_response.go b/models/reason_code_response.go index cf5d985d..a09b024b 100644 --- a/models/reason_code_response.go +++ b/models/reason_code_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ReasonCodeResponse represents a ReasonCodeResponse struct. type ReasonCodeResponse struct { - ReasonCode ReasonCode `json:"reason_code"` + ReasonCode ReasonCode `json:"reason_code"` } -// MarshalJSON implements the json.Marshaler interface for ReasonCodeResponse. +// MarshalJSON implements the json.Marshaler interface for ReasonCodeResponse. // It customizes the JSON marshaling process for ReasonCodeResponse objects. func (r *ReasonCodeResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ReasonCodeResponse object to a map representation for JSON marshaling. func (r *ReasonCodeResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["reason_code"] = r.ReasonCode.toMap() - return structMap + structMap := make(map[string]any) + structMap["reason_code"] = r.ReasonCode.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ReasonCodeResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ReasonCodeResponse. // It customizes the JSON unmarshaling process for ReasonCodeResponse objects. func (r *ReasonCodeResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - ReasonCode ReasonCode `json:"reason_code"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.ReasonCode = temp.ReasonCode - return nil + var temp reasonCodeResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.ReasonCode = *temp.ReasonCode + return nil +} + +// TODO +type reasonCodeResponse struct { + ReasonCode *ReasonCode `json:"reason_code"` +} + +func (r *reasonCodeResponse) validate() error { + var errs []string + if r.ReasonCode == nil { + errs = append(errs, "required field `reason_code` is missing for type `Reason Code Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/reason_codes_json_response.go b/models/reason_codes_json_response.go index bdea2465..52e509dd 100644 --- a/models/reason_codes_json_response.go +++ b/models/reason_codes_json_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // ReasonCodesJsonResponse represents a ReasonCodesJsonResponse struct. type ReasonCodesJsonResponse struct { - Ok *string `json:"ok,omitempty"` + Ok *string `json:"ok,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ReasonCodesJsonResponse. +// MarshalJSON implements the json.Marshaler interface for ReasonCodesJsonResponse. // It customizes the JSON marshaling process for ReasonCodesJsonResponse objects. func (r *ReasonCodesJsonResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ReasonCodesJsonResponse object to a map representation for JSON marshaling. func (r *ReasonCodesJsonResponse) toMap() map[string]any { - structMap := make(map[string]any) - if r.Ok != nil { - structMap["ok"] = r.Ok - } - return structMap + structMap := make(map[string]any) + if r.Ok != nil { + structMap["ok"] = r.Ok + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ReasonCodesJsonResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ReasonCodesJsonResponse. // It customizes the JSON unmarshaling process for ReasonCodesJsonResponse objects. func (r *ReasonCodesJsonResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Ok *string `json:"ok,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Ok = temp.Ok - return nil + var temp reasonCodesJsonResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.Ok = temp.Ok + return nil +} + +// TODO +type reasonCodesJsonResponse struct { + Ok *string `json:"ok,omitempty"` } diff --git a/models/record_payment_request.go b/models/record_payment_request.go index 9dd3b7bd..3f75309f 100644 --- a/models/record_payment_request.go +++ b/models/record_payment_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // RecordPaymentRequest represents a RecordPaymentRequest struct. type RecordPaymentRequest struct { - Payment CreatePayment `json:"payment"` + Payment CreatePayment `json:"payment"` } -// MarshalJSON implements the json.Marshaler interface for RecordPaymentRequest. +// MarshalJSON implements the json.Marshaler interface for RecordPaymentRequest. // It customizes the JSON marshaling process for RecordPaymentRequest objects. func (r *RecordPaymentRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RecordPaymentRequest object to a map representation for JSON marshaling. func (r *RecordPaymentRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["payment"] = r.Payment.toMap() - return structMap + structMap := make(map[string]any) + structMap["payment"] = r.Payment.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RecordPaymentRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for RecordPaymentRequest. // It customizes the JSON unmarshaling process for RecordPaymentRequest objects. func (r *RecordPaymentRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Payment CreatePayment `json:"payment"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Payment = temp.Payment - return nil + var temp recordPaymentRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.Payment = *temp.Payment + return nil +} + +// TODO +type recordPaymentRequest struct { + Payment *CreatePayment `json:"payment"` +} + +func (r *recordPaymentRequest) validate() error { + var errs []string + if r.Payment == nil { + errs = append(errs, "required field `payment` is missing for type `Record Payment Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/record_payment_response.go b/models/record_payment_response.go index 523a4361..e482487e 100644 --- a/models/record_payment_response.go +++ b/models/record_payment_response.go @@ -1,48 +1,54 @@ package models import ( - "encoding/json" + "encoding/json" ) // RecordPaymentResponse represents a RecordPaymentResponse struct. type RecordPaymentResponse struct { - PaidInvoices []PaidInvoice `json:"paid_invoices,omitempty"` - Prepayment Optional[InvoicePrePayment] `json:"prepayment"` + PaidInvoices []PaidInvoice `json:"paid_invoices,omitempty"` + Prepayment Optional[RecordPaymentResponsePrepayment] `json:"prepayment"` } -// MarshalJSON implements the json.Marshaler interface for RecordPaymentResponse. +// MarshalJSON implements the json.Marshaler interface for RecordPaymentResponse. // It customizes the JSON marshaling process for RecordPaymentResponse objects. func (r *RecordPaymentResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RecordPaymentResponse object to a map representation for JSON marshaling. func (r *RecordPaymentResponse) toMap() map[string]any { - structMap := make(map[string]any) - if r.PaidInvoices != nil { - structMap["paid_invoices"] = r.PaidInvoices - } - if r.Prepayment.IsValueSet() { - structMap["prepayment"] = r.Prepayment.Value() - } - return structMap + structMap := make(map[string]any) + if r.PaidInvoices != nil { + structMap["paid_invoices"] = r.PaidInvoices + } + if r.Prepayment.IsValueSet() { + if r.Prepayment.Value() != nil { + structMap["prepayment"] = r.Prepayment.Value().toMap() + } else { + structMap["prepayment"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RecordPaymentResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for RecordPaymentResponse. // It customizes the JSON unmarshaling process for RecordPaymentResponse objects. func (r *RecordPaymentResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - PaidInvoices []PaidInvoice `json:"paid_invoices,omitempty"` - Prepayment Optional[InvoicePrePayment] `json:"prepayment"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.PaidInvoices = temp.PaidInvoices - r.Prepayment = temp.Prepayment - return nil + var temp recordPaymentResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.PaidInvoices = temp.PaidInvoices + r.Prepayment = temp.Prepayment + return nil +} + +// TODO +type recordPaymentResponse struct { + PaidInvoices []PaidInvoice `json:"paid_invoices,omitempty"` + Prepayment Optional[RecordPaymentResponsePrepayment] `json:"prepayment"` } diff --git a/models/record_payment_response_prepayment.go b/models/record_payment_response_prepayment.go new file mode 100644 index 00000000..5ef57664 --- /dev/null +++ b/models/record_payment_response_prepayment.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// RecordPaymentResponsePrepayment represents a RecordPaymentResponsePrepayment struct. +// This is a container for one-of cases. +type RecordPaymentResponsePrepayment struct { + value any + isInvoicePrePayment bool +} + +// String converts the RecordPaymentResponsePrepayment object to a string representation. +func (r RecordPaymentResponsePrepayment) String() string { + if bytes, err := json.Marshal(r.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for RecordPaymentResponsePrepayment. +// It customizes the JSON marshaling process for RecordPaymentResponsePrepayment objects. +func (r *RecordPaymentResponsePrepayment) MarshalJSON() ( + []byte, + error) { + if r.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.RecordPaymentResponsePrepaymentContainer.From*` functions to initialize the RecordPaymentResponsePrepayment object.") + } + return json.Marshal(r.toMap()) +} + +// toMap converts the RecordPaymentResponsePrepayment object to a map representation for JSON marshaling. +func (r *RecordPaymentResponsePrepayment) toMap() any { + switch obj := r.value.(type) { + case *InvoicePrePayment: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RecordPaymentResponsePrepayment. +// It customizes the JSON unmarshaling process for RecordPaymentResponsePrepayment objects. +func (r *RecordPaymentResponsePrepayment) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&InvoicePrePayment{}, false, &r.isInvoicePrePayment), + ) + + r.value = result + return err +} + +func (r *RecordPaymentResponsePrepayment) AsInvoicePrePayment() ( + *InvoicePrePayment, + bool) { + if !r.isInvoicePrePayment { + return nil, false + } + return r.value.(*InvoicePrePayment), true +} + +// internalRecordPaymentResponsePrepayment represents a recordPaymentResponsePrepayment struct. +// This is a container for one-of cases. +type internalRecordPaymentResponsePrepayment struct{} + +var RecordPaymentResponsePrepaymentContainer internalRecordPaymentResponsePrepayment + +func (r *internalRecordPaymentResponsePrepayment) FromInvoicePrePayment(val InvoicePrePayment) RecordPaymentResponsePrepayment { + return RecordPaymentResponsePrepayment{value: &val} +} diff --git a/models/referral_code.go b/models/referral_code.go index 2c29c843..5e1f006b 100644 --- a/models/referral_code.go +++ b/models/referral_code.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // ReferralCode represents a ReferralCode struct. type ReferralCode struct { - Id *int `json:"id,omitempty"` - SiteId *int `json:"site_id,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - Code *string `json:"code,omitempty"` + Id *int `json:"id,omitempty"` + SiteId *int `json:"site_id,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + Code *string `json:"code,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ReferralCode. +// MarshalJSON implements the json.Marshaler interface for ReferralCode. // It customizes the JSON marshaling process for ReferralCode objects. func (r *ReferralCode) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ReferralCode object to a map representation for JSON marshaling. func (r *ReferralCode) toMap() map[string]any { - structMap := make(map[string]any) - if r.Id != nil { - structMap["id"] = r.Id - } - if r.SiteId != nil { - structMap["site_id"] = r.SiteId - } - if r.SubscriptionId != nil { - structMap["subscription_id"] = r.SubscriptionId - } - if r.Code != nil { - structMap["code"] = r.Code - } - return structMap + structMap := make(map[string]any) + if r.Id != nil { + structMap["id"] = r.Id + } + if r.SiteId != nil { + structMap["site_id"] = r.SiteId + } + if r.SubscriptionId != nil { + structMap["subscription_id"] = r.SubscriptionId + } + if r.Code != nil { + structMap["code"] = r.Code + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ReferralCode. +// UnmarshalJSON implements the json.Unmarshaler interface for ReferralCode. // It customizes the JSON unmarshaling process for ReferralCode objects. func (r *ReferralCode) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - SiteId *int `json:"site_id,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - Code *string `json:"code,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Id = temp.Id - r.SiteId = temp.SiteId - r.SubscriptionId = temp.SubscriptionId - r.Code = temp.Code - return nil + var temp referralCode + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.Id = temp.Id + r.SiteId = temp.SiteId + r.SubscriptionId = temp.SubscriptionId + r.Code = temp.Code + return nil +} + +// TODO +type referralCode struct { + Id *int `json:"id,omitempty"` + SiteId *int `json:"site_id,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + Code *string `json:"code,omitempty"` } diff --git a/models/referral_validation_response.go b/models/referral_validation_response.go index 34b0172b..346b1dfb 100644 --- a/models/referral_validation_response.go +++ b/models/referral_validation_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // ReferralValidationResponse represents a ReferralValidationResponse struct. type ReferralValidationResponse struct { - ReferralCode *ReferralCode `json:"referral_code,omitempty"` + ReferralCode *ReferralCode `json:"referral_code,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ReferralValidationResponse. +// MarshalJSON implements the json.Marshaler interface for ReferralValidationResponse. // It customizes the JSON marshaling process for ReferralValidationResponse objects. func (r *ReferralValidationResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ReferralValidationResponse object to a map representation for JSON marshaling. func (r *ReferralValidationResponse) toMap() map[string]any { - structMap := make(map[string]any) - if r.ReferralCode != nil { - structMap["referral_code"] = r.ReferralCode.toMap() - } - return structMap + structMap := make(map[string]any) + if r.ReferralCode != nil { + structMap["referral_code"] = r.ReferralCode.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ReferralValidationResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ReferralValidationResponse. // It customizes the JSON unmarshaling process for ReferralValidationResponse objects. func (r *ReferralValidationResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - ReferralCode *ReferralCode `json:"referral_code,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.ReferralCode = temp.ReferralCode - return nil + var temp referralValidationResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.ReferralCode = temp.ReferralCode + return nil +} + +// TODO +type referralValidationResponse struct { + ReferralCode *ReferralCode `json:"referral_code,omitempty"` } diff --git a/models/refund.go b/models/refund.go index 242718cb..a34b18ea 100644 --- a/models/refund.go +++ b/models/refund.go @@ -1,85 +1,87 @@ package models import ( - "encoding/json" + "encoding/json" ) // Refund represents a Refund struct. type Refund struct { - // The amount to be refunded in decimal format as a string. Example: "10.50". Must not exceed the remaining refundable balance of the payment. - Amount *string `json:"amount,omitempty"` - // A description that will be attached to the refund - Memo *string `json:"memo,omitempty"` - // The ID of the payment to be refunded - PaymentId *int `json:"payment_id,omitempty"` - // Flag that marks refund as external (no money is returned to the customer). Defaults to `false`. - External *bool `json:"external,omitempty"` - // If set to true, creates credit and applies it to an invoice. Defaults to `false`. - ApplyCredit *bool `json:"apply_credit,omitempty"` - // If `apply_credit` set to false and refunding full amount, if `void_invoice` set to true, invoice will be voided after refund. Defaults to `false`. - VoidInvoice *bool `json:"void_invoice,omitempty"` - // An array of segment uids to refund or the string 'all' to indicate that all segments should be refunded - SegmentUids *interface{} `json:"segment_uids,omitempty"` + // The amount to be refunded in decimal format as a string. Example: "10.50". Must not exceed the remaining refundable balance of the payment. + Amount *string `json:"amount,omitempty"` + // A description that will be attached to the refund + Memo *string `json:"memo,omitempty"` + // The ID of the payment to be refunded + PaymentId *int `json:"payment_id,omitempty"` + // Flag that marks refund as external (no money is returned to the customer). Defaults to `false`. + External *bool `json:"external,omitempty"` + // If set to true, creates credit and applies it to an invoice. Defaults to `false`. + ApplyCredit *bool `json:"apply_credit,omitempty"` + // If `apply_credit` set to false and refunding full amount, if `void_invoice` set to true, invoice will be voided after refund. Defaults to `false`. + VoidInvoice *bool `json:"void_invoice,omitempty"` + // An array of segment uids to refund or the string 'all' to indicate that all segments should be refunded + SegmentUids *RefundSegmentUids `json:"segment_uids,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Refund. +// MarshalJSON implements the json.Marshaler interface for Refund. // It customizes the JSON marshaling process for Refund objects. func (r *Refund) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the Refund object to a map representation for JSON marshaling. func (r *Refund) toMap() map[string]any { - structMap := make(map[string]any) - if r.Amount != nil { - structMap["amount"] = r.Amount - } - if r.Memo != nil { - structMap["memo"] = r.Memo - } - if r.PaymentId != nil { - structMap["payment_id"] = r.PaymentId - } - if r.External != nil { - structMap["external"] = r.External - } - if r.ApplyCredit != nil { - structMap["apply_credit"] = r.ApplyCredit - } - if r.VoidInvoice != nil { - structMap["void_invoice"] = r.VoidInvoice - } - if r.SegmentUids != nil { - structMap["segment_uids"] = r.SegmentUids - } - return structMap + structMap := make(map[string]any) + if r.Amount != nil { + structMap["amount"] = r.Amount + } + if r.Memo != nil { + structMap["memo"] = r.Memo + } + if r.PaymentId != nil { + structMap["payment_id"] = r.PaymentId + } + if r.External != nil { + structMap["external"] = r.External + } + if r.ApplyCredit != nil { + structMap["apply_credit"] = r.ApplyCredit + } + if r.VoidInvoice != nil { + structMap["void_invoice"] = r.VoidInvoice + } + if r.SegmentUids != nil { + structMap["segment_uids"] = r.SegmentUids.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Refund. +// UnmarshalJSON implements the json.Unmarshaler interface for Refund. // It customizes the JSON unmarshaling process for Refund objects. func (r *Refund) UnmarshalJSON(input []byte) error { - temp := &struct { - Amount *string `json:"amount,omitempty"` - Memo *string `json:"memo,omitempty"` - PaymentId *int `json:"payment_id,omitempty"` - External *bool `json:"external,omitempty"` - ApplyCredit *bool `json:"apply_credit,omitempty"` - VoidInvoice *bool `json:"void_invoice,omitempty"` - SegmentUids *interface{} `json:"segment_uids,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Amount = temp.Amount - r.Memo = temp.Memo - r.PaymentId = temp.PaymentId - r.External = temp.External - r.ApplyCredit = temp.ApplyCredit - r.VoidInvoice = temp.VoidInvoice - r.SegmentUids = temp.SegmentUids - return nil + var temp refund + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.Amount = temp.Amount + r.Memo = temp.Memo + r.PaymentId = temp.PaymentId + r.External = temp.External + r.ApplyCredit = temp.ApplyCredit + r.VoidInvoice = temp.VoidInvoice + r.SegmentUids = temp.SegmentUids + return nil +} + +// TODO +type refund struct { + Amount *string `json:"amount,omitempty"` + Memo *string `json:"memo,omitempty"` + PaymentId *int `json:"payment_id,omitempty"` + External *bool `json:"external,omitempty"` + ApplyCredit *bool `json:"apply_credit,omitempty"` + VoidInvoice *bool `json:"void_invoice,omitempty"` + SegmentUids *RefundSegmentUids `json:"segment_uids,omitempty"` } diff --git a/models/refund_consolidated_invoice.go b/models/refund_consolidated_invoice.go new file mode 100644 index 00000000..ddbd97d7 --- /dev/null +++ b/models/refund_consolidated_invoice.go @@ -0,0 +1,99 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// RefundConsolidatedInvoice represents a RefundConsolidatedInvoice struct. +// Refund consolidated invoice +type RefundConsolidatedInvoice struct { + // A description for the refund + Memo string `json:"memo"` + // The ID of the payment to be refunded + PaymentId int `json:"payment_id"` + // An array of segment uids to refund or the string 'all' to indicate that all segments should be refunded + SegmentUids RefundConsolidatedInvoiceSegmentUids `json:"segment_uids"` + // Flag that marks refund as external (no money is returned to the customer). Defaults to `false`. + External *bool `json:"external,omitempty"` + // If set to true, creates credit and applies it to an invoice. Defaults to `false`. + ApplyCredit *bool `json:"apply_credit,omitempty"` + // The amount of payment to be refunded in decimal format. Example: "10.50". This will default to the full amount of the payment if not provided. + Amount *string `json:"amount,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for RefundConsolidatedInvoice. +// It customizes the JSON marshaling process for RefundConsolidatedInvoice objects. +func (r *RefundConsolidatedInvoice) MarshalJSON() ( + []byte, + error) { + return json.Marshal(r.toMap()) +} + +// toMap converts the RefundConsolidatedInvoice object to a map representation for JSON marshaling. +func (r *RefundConsolidatedInvoice) toMap() map[string]any { + structMap := make(map[string]any) + structMap["memo"] = r.Memo + structMap["payment_id"] = r.PaymentId + structMap["segment_uids"] = r.SegmentUids.toMap() + if r.External != nil { + structMap["external"] = r.External + } + if r.ApplyCredit != nil { + structMap["apply_credit"] = r.ApplyCredit + } + if r.Amount != nil { + structMap["amount"] = r.Amount + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RefundConsolidatedInvoice. +// It customizes the JSON unmarshaling process for RefundConsolidatedInvoice objects. +func (r *RefundConsolidatedInvoice) UnmarshalJSON(input []byte) error { + var temp refundConsolidatedInvoice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.Memo = *temp.Memo + r.PaymentId = *temp.PaymentId + r.SegmentUids = *temp.SegmentUids + r.External = temp.External + r.ApplyCredit = temp.ApplyCredit + r.Amount = temp.Amount + return nil +} + +// TODO +type refundConsolidatedInvoice struct { + Memo *string `json:"memo"` + PaymentId *int `json:"payment_id"` + SegmentUids *RefundConsolidatedInvoiceSegmentUids `json:"segment_uids"` + External *bool `json:"external,omitempty"` + ApplyCredit *bool `json:"apply_credit,omitempty"` + Amount *string `json:"amount,omitempty"` +} + +func (r *refundConsolidatedInvoice) validate() error { + var errs []string + if r.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Refund Consolidated Invoice`") + } + if r.PaymentId == nil { + errs = append(errs, "required field `payment_id` is missing for type `Refund Consolidated Invoice`") + } + if r.SegmentUids == nil { + errs = append(errs, "required field `segment_uids` is missing for type `Refund Consolidated Invoice`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/refund_consolidated_invoice_segment_uids.go b/models/refund_consolidated_invoice_segment_uids.go new file mode 100644 index 00000000..b6bbdb13 --- /dev/null +++ b/models/refund_consolidated_invoice_segment_uids.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// RefundConsolidatedInvoiceSegmentUids represents a RefundConsolidatedInvoiceSegmentUids struct. +// This is a container for one-of cases. +type RefundConsolidatedInvoiceSegmentUids struct { + value any + isArrayOfString bool + isString bool +} + +// String converts the RefundConsolidatedInvoiceSegmentUids object to a string representation. +func (r RefundConsolidatedInvoiceSegmentUids) String() string { + if bytes, err := json.Marshal(r.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for RefundConsolidatedInvoiceSegmentUids. +// It customizes the JSON marshaling process for RefundConsolidatedInvoiceSegmentUids objects. +func (r *RefundConsolidatedInvoiceSegmentUids) MarshalJSON() ( + []byte, + error) { + if r.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.RefundConsolidatedInvoiceSegmentUidsContainer.From*` functions to initialize the RefundConsolidatedInvoiceSegmentUids object.") + } + return json.Marshal(r.toMap()) +} + +// toMap converts the RefundConsolidatedInvoiceSegmentUids object to a map representation for JSON marshaling. +func (r *RefundConsolidatedInvoiceSegmentUids) toMap() any { + switch obj := r.value.(type) { + case *[]string: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RefundConsolidatedInvoiceSegmentUids. +// It customizes the JSON unmarshaling process for RefundConsolidatedInvoiceSegmentUids objects. +func (r *RefundConsolidatedInvoiceSegmentUids) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new([]string), false, &r.isArrayOfString), + NewTypeHolder(new(string), false, &r.isString), + ) + + r.value = result + return err +} + +func (r *RefundConsolidatedInvoiceSegmentUids) AsArrayOfString() ( + *[]string, + bool) { + if !r.isArrayOfString { + return nil, false + } + return r.value.(*[]string), true +} + +func (r *RefundConsolidatedInvoiceSegmentUids) AsString() ( + *string, + bool) { + if !r.isString { + return nil, false + } + return r.value.(*string), true +} + +// internalRefundConsolidatedInvoiceSegmentUids represents a refundConsolidatedInvoiceSegmentUids struct. +// This is a container for one-of cases. +type internalRefundConsolidatedInvoiceSegmentUids struct{} + +var RefundConsolidatedInvoiceSegmentUidsContainer internalRefundConsolidatedInvoiceSegmentUids + +func (r *internalRefundConsolidatedInvoiceSegmentUids) FromArrayOfString(val []string) RefundConsolidatedInvoiceSegmentUids { + return RefundConsolidatedInvoiceSegmentUids{value: &val} +} + +func (r *internalRefundConsolidatedInvoiceSegmentUids) FromString(val string) RefundConsolidatedInvoiceSegmentUids { + return RefundConsolidatedInvoiceSegmentUids{value: &val} +} diff --git a/models/refund_invoice.go b/models/refund_invoice.go new file mode 100644 index 00000000..3d5ebf89 --- /dev/null +++ b/models/refund_invoice.go @@ -0,0 +1,99 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// RefundInvoice represents a RefundInvoice struct. +// Refund an invoice or a segment of a consolidated invoice. +type RefundInvoice struct { + // The amount to be refunded in decimal format as a string. Example: "10.50". Must not exceed the remaining refundable balance of the payment. + Amount string `json:"amount"` + // A description that will be attached to the refund + Memo string `json:"memo"` + // The ID of the payment to be refunded + PaymentId int `json:"payment_id"` + // Flag that marks refund as external (no money is returned to the customer). Defaults to `false`. + External *bool `json:"external,omitempty"` + // If set to true, creates credit and applies it to an invoice. Defaults to `false`. + ApplyCredit *bool `json:"apply_credit,omitempty"` + // If `apply_credit` set to false and refunding full amount, if `void_invoice` set to true, invoice will be voided after refund. Defaults to `false`. + VoidInvoice *bool `json:"void_invoice,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for RefundInvoice. +// It customizes the JSON marshaling process for RefundInvoice objects. +func (r *RefundInvoice) MarshalJSON() ( + []byte, + error) { + return json.Marshal(r.toMap()) +} + +// toMap converts the RefundInvoice object to a map representation for JSON marshaling. +func (r *RefundInvoice) toMap() map[string]any { + structMap := make(map[string]any) + structMap["amount"] = r.Amount + structMap["memo"] = r.Memo + structMap["payment_id"] = r.PaymentId + if r.External != nil { + structMap["external"] = r.External + } + if r.ApplyCredit != nil { + structMap["apply_credit"] = r.ApplyCredit + } + if r.VoidInvoice != nil { + structMap["void_invoice"] = r.VoidInvoice + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RefundInvoice. +// It customizes the JSON unmarshaling process for RefundInvoice objects. +func (r *RefundInvoice) UnmarshalJSON(input []byte) error { + var temp refundInvoice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.Amount = *temp.Amount + r.Memo = *temp.Memo + r.PaymentId = *temp.PaymentId + r.External = temp.External + r.ApplyCredit = temp.ApplyCredit + r.VoidInvoice = temp.VoidInvoice + return nil +} + +// TODO +type refundInvoice struct { + Amount *string `json:"amount"` + Memo *string `json:"memo"` + PaymentId *int `json:"payment_id"` + External *bool `json:"external,omitempty"` + ApplyCredit *bool `json:"apply_credit,omitempty"` + VoidInvoice *bool `json:"void_invoice,omitempty"` +} + +func (r *refundInvoice) validate() error { + var errs []string + if r.Amount == nil { + errs = append(errs, "required field `amount` is missing for type `Refund Invoice`") + } + if r.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Refund Invoice`") + } + if r.PaymentId == nil { + errs = append(errs, "required field `payment_id` is missing for type `Refund Invoice`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/refund_invoice_event_data.go b/models/refund_invoice_event_data.go new file mode 100644 index 00000000..b5757688 --- /dev/null +++ b/models/refund_invoice_event_data.go @@ -0,0 +1,133 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// RefundInvoiceEventData represents a RefundInvoiceEventData struct. +// Example schema for an `refund_invoice` event +type RefundInvoiceEventData struct { + // If true, credit was created and applied it to the invoice. + ApplyCredit bool `json:"apply_credit"` + // Consolidation level of the invoice, which is applicable to invoice consolidation. It will hold one of the following values: + // * "none": A normal invoice with no consolidation. + // * "child": An invoice segment which has been combined into a consolidated invoice. + // * "parent": A consolidated invoice, whose contents are composed of invoice segments. + // "Parent" invoices do not have lines of their own, but they have subtotals and totals which aggregate the member invoice segments. + // See also the [invoice consolidation documentation](https://chargify.zendesk.com/hc/en-us/articles/4407746391835). + ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` + CreditNoteAttributes CreditNote `json:"credit_note_attributes"` + // The refund memo. + Memo *string `json:"memo,omitempty"` + // The full, original amount of the refund. + OriginalAmount *string `json:"original_amount,omitempty"` + // The ID of the payment transaction to be refunded. + PaymentId int `json:"payment_id"` + // The amount of the refund. + RefundAmount string `json:"refund_amount"` + // The ID of the refund transaction. + RefundId int `json:"refund_id"` + // The time the refund was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" + TransactionTime time.Time `json:"transaction_time"` +} + +// MarshalJSON implements the json.Marshaler interface for RefundInvoiceEventData. +// It customizes the JSON marshaling process for RefundInvoiceEventData objects. +func (r *RefundInvoiceEventData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(r.toMap()) +} + +// toMap converts the RefundInvoiceEventData object to a map representation for JSON marshaling. +func (r *RefundInvoiceEventData) toMap() map[string]any { + structMap := make(map[string]any) + structMap["apply_credit"] = r.ApplyCredit + if r.ConsolidationLevel != nil { + structMap["consolidation_level"] = r.ConsolidationLevel + } + structMap["credit_note_attributes"] = r.CreditNoteAttributes.toMap() + if r.Memo != nil { + structMap["memo"] = r.Memo + } + if r.OriginalAmount != nil { + structMap["original_amount"] = r.OriginalAmount + } + structMap["payment_id"] = r.PaymentId + structMap["refund_amount"] = r.RefundAmount + structMap["refund_id"] = r.RefundId + structMap["transaction_time"] = r.TransactionTime.Format(time.RFC3339) + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RefundInvoiceEventData. +// It customizes the JSON unmarshaling process for RefundInvoiceEventData objects. +func (r *RefundInvoiceEventData) UnmarshalJSON(input []byte) error { + var temp refundInvoiceEventData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.ApplyCredit = *temp.ApplyCredit + r.ConsolidationLevel = temp.ConsolidationLevel + r.CreditNoteAttributes = *temp.CreditNoteAttributes + r.Memo = temp.Memo + r.OriginalAmount = temp.OriginalAmount + r.PaymentId = *temp.PaymentId + r.RefundAmount = *temp.RefundAmount + r.RefundId = *temp.RefundId + TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) + if err != nil { + log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) + } + r.TransactionTime = TransactionTimeVal + return nil +} + +// TODO +type refundInvoiceEventData struct { + ApplyCredit *bool `json:"apply_credit"` + ConsolidationLevel *InvoiceConsolidationLevel `json:"consolidation_level,omitempty"` + CreditNoteAttributes *CreditNote `json:"credit_note_attributes"` + Memo *string `json:"memo,omitempty"` + OriginalAmount *string `json:"original_amount,omitempty"` + PaymentId *int `json:"payment_id"` + RefundAmount *string `json:"refund_amount"` + RefundId *int `json:"refund_id"` + TransactionTime *string `json:"transaction_time"` +} + +func (r *refundInvoiceEventData) validate() error { + var errs []string + if r.ApplyCredit == nil { + errs = append(errs, "required field `apply_credit` is missing for type `Refund Invoice Event Data`") + } + if r.CreditNoteAttributes == nil { + errs = append(errs, "required field `credit_note_attributes` is missing for type `Refund Invoice Event Data`") + } + if r.PaymentId == nil { + errs = append(errs, "required field `payment_id` is missing for type `Refund Invoice Event Data`") + } + if r.RefundAmount == nil { + errs = append(errs, "required field `refund_amount` is missing for type `Refund Invoice Event Data`") + } + if r.RefundId == nil { + errs = append(errs, "required field `refund_id` is missing for type `Refund Invoice Event Data`") + } + if r.TransactionTime == nil { + errs = append(errs, "required field `transaction_time` is missing for type `Refund Invoice Event Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/refund_invoice_request.go b/models/refund_invoice_request.go index 2bdec40d..cf62a51b 100644 --- a/models/refund_invoice_request.go +++ b/models/refund_invoice_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // RefundInvoiceRequest represents a RefundInvoiceRequest struct. type RefundInvoiceRequest struct { - Refund Refund `json:"refund"` + Refund RefundInvoiceRequestRefund `json:"refund"` } -// MarshalJSON implements the json.Marshaler interface for RefundInvoiceRequest. +// MarshalJSON implements the json.Marshaler interface for RefundInvoiceRequest. // It customizes the JSON marshaling process for RefundInvoiceRequest objects. func (r *RefundInvoiceRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RefundInvoiceRequest object to a map representation for JSON marshaling. func (r *RefundInvoiceRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["refund"] = r.Refund.toMap() - return structMap + structMap := make(map[string]any) + structMap["refund"] = r.Refund.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RefundInvoiceRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for RefundInvoiceRequest. // It customizes the JSON unmarshaling process for RefundInvoiceRequest objects. func (r *RefundInvoiceRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Refund Refund `json:"refund"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Refund = temp.Refund - return nil + var temp refundInvoiceRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.Refund = *temp.Refund + return nil +} + +// TODO +type refundInvoiceRequest struct { + Refund *RefundInvoiceRequestRefund `json:"refund"` +} + +func (r *refundInvoiceRequest) validate() error { + var errs []string + if r.Refund == nil { + errs = append(errs, "required field `refund` is missing for type `Refund Invoice Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/refund_invoice_request_refund.go b/models/refund_invoice_request_refund.go new file mode 100644 index 00000000..986041ba --- /dev/null +++ b/models/refund_invoice_request_refund.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// RefundInvoiceRequestRefund represents a RefundInvoiceRequestRefund struct. +// This is a container for any-of cases. +type RefundInvoiceRequestRefund struct { + value any + isRefundInvoice bool + isRefundConsolidatedInvoice bool +} + +// String converts the RefundInvoiceRequestRefund object to a string representation. +func (r RefundInvoiceRequestRefund) String() string { + if bytes, err := json.Marshal(r.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for RefundInvoiceRequestRefund. +// It customizes the JSON marshaling process for RefundInvoiceRequestRefund objects. +func (r *RefundInvoiceRequestRefund) MarshalJSON() ( + []byte, + error) { + if r.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.RefundInvoiceRequestRefundContainer.From*` functions to initialize the RefundInvoiceRequestRefund object.") + } + return json.Marshal(r.toMap()) +} + +// toMap converts the RefundInvoiceRequestRefund object to a map representation for JSON marshaling. +func (r *RefundInvoiceRequestRefund) toMap() any { + switch obj := r.value.(type) { + case *RefundInvoice: + return obj.toMap() + case *RefundConsolidatedInvoice: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RefundInvoiceRequestRefund. +// It customizes the JSON unmarshaling process for RefundInvoiceRequestRefund objects. +func (r *RefundInvoiceRequestRefund) UnmarshalJSON(input []byte) error { + result, err := UnmarshallAnyOf(input, + NewTypeHolder(&RefundInvoice{}, false, &r.isRefundInvoice), + NewTypeHolder(&RefundConsolidatedInvoice{}, false, &r.isRefundConsolidatedInvoice), + ) + + r.value = result + return err +} + +func (r *RefundInvoiceRequestRefund) AsRefundInvoice() ( + *RefundInvoice, + bool) { + if !r.isRefundInvoice { + return nil, false + } + return r.value.(*RefundInvoice), true +} + +func (r *RefundInvoiceRequestRefund) AsRefundConsolidatedInvoice() ( + *RefundConsolidatedInvoice, + bool) { + if !r.isRefundConsolidatedInvoice { + return nil, false + } + return r.value.(*RefundConsolidatedInvoice), true +} + +// internalRefundInvoiceRequestRefund represents a refundInvoiceRequestRefund struct. +// This is a container for any-of cases. +type internalRefundInvoiceRequestRefund struct{} + +var RefundInvoiceRequestRefundContainer internalRefundInvoiceRequestRefund + +func (r *internalRefundInvoiceRequestRefund) FromRefundInvoice(val RefundInvoice) RefundInvoiceRequestRefund { + return RefundInvoiceRequestRefund{value: &val} +} + +func (r *internalRefundInvoiceRequestRefund) FromRefundConsolidatedInvoice(val RefundConsolidatedInvoice) RefundInvoiceRequestRefund { + return RefundInvoiceRequestRefund{value: &val} +} diff --git a/models/refund_prepayment.go b/models/refund_prepayment.go index cd4e62a6..8265c2c0 100644 --- a/models/refund_prepayment.go +++ b/models/refund_prepayment.go @@ -1,57 +1,83 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // RefundPrepayment represents a RefundPrepayment struct. type RefundPrepayment struct { - // `amount` is not required if you pass `amount_in_cents`. - AmountInCents int64 `json:"amount_in_cents"` - // `amount_in_cents` is not required if you pass `amount`. - Amount interface{} `json:"amount"` - Memo string `json:"memo"` - // Specify the type of refund you wish to initiate. When the prepayment is external, the `external` flag is optional. But if the prepayment was made through a payment profile, the `external` flag is required. - External *bool `json:"external,omitempty"` + // `amount` is not required if you pass `amount_in_cents`. + AmountInCents int64 `json:"amount_in_cents"` + // `amount_in_cents` is not required if you pass `amount`. + Amount RefundPrepaymentAmount `json:"amount"` + Memo string `json:"memo"` + // Specify the type of refund you wish to initiate. When the prepayment is external, the `external` flag is optional. But if the prepayment was made through a payment profile, the `external` flag is required. + External *bool `json:"external,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for RefundPrepayment. +// MarshalJSON implements the json.Marshaler interface for RefundPrepayment. // It customizes the JSON marshaling process for RefundPrepayment objects. func (r *RefundPrepayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RefundPrepayment object to a map representation for JSON marshaling. func (r *RefundPrepayment) toMap() map[string]any { - structMap := make(map[string]any) - structMap["amount_in_cents"] = r.AmountInCents - structMap["amount"] = r.Amount - structMap["memo"] = r.Memo - if r.External != nil { - structMap["external"] = r.External - } - return structMap + structMap := make(map[string]any) + structMap["amount_in_cents"] = r.AmountInCents + structMap["amount"] = r.Amount.toMap() + structMap["memo"] = r.Memo + if r.External != nil { + structMap["external"] = r.External + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RefundPrepayment. +// UnmarshalJSON implements the json.Unmarshaler interface for RefundPrepayment. // It customizes the JSON unmarshaling process for RefundPrepayment objects. func (r *RefundPrepayment) UnmarshalJSON(input []byte) error { - temp := &struct { - AmountInCents int64 `json:"amount_in_cents"` - Amount interface{} `json:"amount"` - Memo string `json:"memo"` - External *bool `json:"external,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.AmountInCents = temp.AmountInCents - r.Amount = temp.Amount - r.Memo = temp.Memo - r.External = temp.External - return nil + var temp refundPrepayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.AmountInCents = *temp.AmountInCents + r.Amount = *temp.Amount + r.Memo = *temp.Memo + r.External = temp.External + return nil +} + +// TODO +type refundPrepayment struct { + AmountInCents *int64 `json:"amount_in_cents"` + Amount *RefundPrepaymentAmount `json:"amount"` + Memo *string `json:"memo"` + External *bool `json:"external,omitempty"` +} + +func (r *refundPrepayment) validate() error { + var errs []string + if r.AmountInCents == nil { + errs = append(errs, "required field `amount_in_cents` is missing for type `Refund Prepayment`") + } + if r.Amount == nil { + errs = append(errs, "required field `amount` is missing for type `Refund Prepayment`") + } + if r.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Refund Prepayment`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/refund_prepayment_aggregated_error.go b/models/refund_prepayment_aggregated_error.go index a362b0c0..caae2ed1 100644 --- a/models/refund_prepayment_aggregated_error.go +++ b/models/refund_prepayment_aggregated_error.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // RefundPrepaymentAggregatedError represents a RefundPrepaymentAggregatedError struct. type RefundPrepaymentAggregatedError struct { - Refund *PrepaymentAggregatedError `json:"refund,omitempty"` + Refund *PrepaymentAggregatedError `json:"refund,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for RefundPrepaymentAggregatedError. +// MarshalJSON implements the json.Marshaler interface for RefundPrepaymentAggregatedError. // It customizes the JSON marshaling process for RefundPrepaymentAggregatedError objects. func (r *RefundPrepaymentAggregatedError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RefundPrepaymentAggregatedError object to a map representation for JSON marshaling. func (r *RefundPrepaymentAggregatedError) toMap() map[string]any { - structMap := make(map[string]any) - if r.Refund != nil { - structMap["refund"] = r.Refund.toMap() - } - return structMap + structMap := make(map[string]any) + if r.Refund != nil { + structMap["refund"] = r.Refund.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RefundPrepaymentAggregatedError. +// UnmarshalJSON implements the json.Unmarshaler interface for RefundPrepaymentAggregatedError. // It customizes the JSON unmarshaling process for RefundPrepaymentAggregatedError objects. func (r *RefundPrepaymentAggregatedError) UnmarshalJSON(input []byte) error { - temp := &struct { - Refund *PrepaymentAggregatedError `json:"refund,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Refund = temp.Refund - return nil + var temp refundPrepaymentAggregatedError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.Refund = temp.Refund + return nil +} + +// TODO +type refundPrepaymentAggregatedError struct { + Refund *PrepaymentAggregatedError `json:"refund,omitempty"` } diff --git a/models/refund_prepayment_amount.go b/models/refund_prepayment_amount.go new file mode 100644 index 00000000..09f9f561 --- /dev/null +++ b/models/refund_prepayment_amount.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// RefundPrepaymentAmount represents a RefundPrepaymentAmount struct. +// This is a container for one-of cases. +type RefundPrepaymentAmount struct { + value any + isString bool + isPrecision bool +} + +// String converts the RefundPrepaymentAmount object to a string representation. +func (r RefundPrepaymentAmount) String() string { + if bytes, err := json.Marshal(r.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for RefundPrepaymentAmount. +// It customizes the JSON marshaling process for RefundPrepaymentAmount objects. +func (r *RefundPrepaymentAmount) MarshalJSON() ( + []byte, + error) { + if r.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.RefundPrepaymentAmountContainer.From*` functions to initialize the RefundPrepaymentAmount object.") + } + return json.Marshal(r.toMap()) +} + +// toMap converts the RefundPrepaymentAmount object to a map representation for JSON marshaling. +func (r *RefundPrepaymentAmount) toMap() any { + switch obj := r.value.(type) { + case *string: + return *obj + case *float64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RefundPrepaymentAmount. +// It customizes the JSON unmarshaling process for RefundPrepaymentAmount objects. +func (r *RefundPrepaymentAmount) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &r.isString), + NewTypeHolder(new(float64), false, &r.isPrecision), + ) + + r.value = result + return err +} + +func (r *RefundPrepaymentAmount) AsString() ( + *string, + bool) { + if !r.isString { + return nil, false + } + return r.value.(*string), true +} + +func (r *RefundPrepaymentAmount) AsPrecision() ( + *float64, + bool) { + if !r.isPrecision { + return nil, false + } + return r.value.(*float64), true +} + +// internalRefundPrepaymentAmount represents a refundPrepaymentAmount struct. +// This is a container for one-of cases. +type internalRefundPrepaymentAmount struct{} + +var RefundPrepaymentAmountContainer internalRefundPrepaymentAmount + +func (r *internalRefundPrepaymentAmount) FromString(val string) RefundPrepaymentAmount { + return RefundPrepaymentAmount{value: &val} +} + +func (r *internalRefundPrepaymentAmount) FromPrecision(val float64) RefundPrepaymentAmount { + return RefundPrepaymentAmount{value: &val} +} diff --git a/models/refund_prepayment_base_refund_error.go b/models/refund_prepayment_base_refund_error.go index 4689622f..8a7ebbda 100644 --- a/models/refund_prepayment_base_refund_error.go +++ b/models/refund_prepayment_base_refund_error.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // RefundPrepaymentBaseRefundError represents a RefundPrepaymentBaseRefundError struct. type RefundPrepaymentBaseRefundError struct { - Refund *BaseRefundError `json:"refund,omitempty"` + Refund *BaseRefundError `json:"refund,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for RefundPrepaymentBaseRefundError. +// MarshalJSON implements the json.Marshaler interface for RefundPrepaymentBaseRefundError. // It customizes the JSON marshaling process for RefundPrepaymentBaseRefundError objects. func (r *RefundPrepaymentBaseRefundError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RefundPrepaymentBaseRefundError object to a map representation for JSON marshaling. func (r *RefundPrepaymentBaseRefundError) toMap() map[string]any { - structMap := make(map[string]any) - if r.Refund != nil { - structMap["refund"] = r.Refund.toMap() - } - return structMap + structMap := make(map[string]any) + if r.Refund != nil { + structMap["refund"] = r.Refund.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RefundPrepaymentBaseRefundError. +// UnmarshalJSON implements the json.Unmarshaler interface for RefundPrepaymentBaseRefundError. // It customizes the JSON unmarshaling process for RefundPrepaymentBaseRefundError objects. func (r *RefundPrepaymentBaseRefundError) UnmarshalJSON(input []byte) error { - temp := &struct { - Refund *BaseRefundError `json:"refund,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Refund = temp.Refund - return nil + var temp refundPrepaymentBaseRefundError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.Refund = temp.Refund + return nil +} + +// TODO +type refundPrepaymentBaseRefundError struct { + Refund *BaseRefundError `json:"refund,omitempty"` } diff --git a/models/refund_prepayment_request.go b/models/refund_prepayment_request.go index 589be4e4..0ac6e37d 100644 --- a/models/refund_prepayment_request.go +++ b/models/refund_prepayment_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // RefundPrepaymentRequest represents a RefundPrepaymentRequest struct. type RefundPrepaymentRequest struct { - Refund RefundPrepayment `json:"refund"` + Refund RefundPrepayment `json:"refund"` } -// MarshalJSON implements the json.Marshaler interface for RefundPrepaymentRequest. +// MarshalJSON implements the json.Marshaler interface for RefundPrepaymentRequest. // It customizes the JSON marshaling process for RefundPrepaymentRequest objects. func (r *RefundPrepaymentRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RefundPrepaymentRequest object to a map representation for JSON marshaling. func (r *RefundPrepaymentRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["refund"] = r.Refund.toMap() - return structMap + structMap := make(map[string]any) + structMap["refund"] = r.Refund.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RefundPrepaymentRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for RefundPrepaymentRequest. // It customizes the JSON unmarshaling process for RefundPrepaymentRequest objects. func (r *RefundPrepaymentRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Refund RefundPrepayment `json:"refund"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Refund = temp.Refund - return nil + var temp refundPrepaymentRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.Refund = *temp.Refund + return nil +} + +// TODO +type refundPrepaymentRequest struct { + Refund *RefundPrepayment `json:"refund"` +} + +func (r *refundPrepaymentRequest) validate() error { + var errs []string + if r.Refund == nil { + errs = append(errs, "required field `refund` is missing for type `Refund Prepayment Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/refund_segment_uids.go b/models/refund_segment_uids.go new file mode 100644 index 00000000..d9c23006 --- /dev/null +++ b/models/refund_segment_uids.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// RefundSegmentUids represents a RefundSegmentUids struct. +// This is a container for one-of cases. +type RefundSegmentUids struct { + value any + isArrayOfString bool + isString bool +} + +// String converts the RefundSegmentUids object to a string representation. +func (r RefundSegmentUids) String() string { + if bytes, err := json.Marshal(r.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for RefundSegmentUids. +// It customizes the JSON marshaling process for RefundSegmentUids objects. +func (r *RefundSegmentUids) MarshalJSON() ( + []byte, + error) { + if r.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.RefundSegmentUidsContainer.From*` functions to initialize the RefundSegmentUids object.") + } + return json.Marshal(r.toMap()) +} + +// toMap converts the RefundSegmentUids object to a map representation for JSON marshaling. +func (r *RefundSegmentUids) toMap() any { + switch obj := r.value.(type) { + case *[]string: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RefundSegmentUids. +// It customizes the JSON unmarshaling process for RefundSegmentUids objects. +func (r *RefundSegmentUids) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new([]string), false, &r.isArrayOfString), + NewTypeHolder(new(string), false, &r.isString), + ) + + r.value = result + return err +} + +func (r *RefundSegmentUids) AsArrayOfString() ( + *[]string, + bool) { + if !r.isArrayOfString { + return nil, false + } + return r.value.(*[]string), true +} + +func (r *RefundSegmentUids) AsString() ( + *string, + bool) { + if !r.isString { + return nil, false + } + return r.value.(*string), true +} + +// internalRefundSegmentUids represents a refundSegmentUids struct. +// This is a container for one-of cases. +type internalRefundSegmentUids struct{} + +var RefundSegmentUidsContainer internalRefundSegmentUids + +func (r *internalRefundSegmentUids) FromArrayOfString(val []string) RefundSegmentUids { + return RefundSegmentUids{value: &val} +} + +func (r *internalRefundSegmentUids) FromString(val string) RefundSegmentUids { + return RefundSegmentUids{value: &val} +} diff --git a/models/refund_success.go b/models/refund_success.go new file mode 100644 index 00000000..05e84c61 --- /dev/null +++ b/models/refund_success.go @@ -0,0 +1,74 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// RefundSuccess represents a RefundSuccess struct. +type RefundSuccess struct { + RefundId int `json:"refund_id"` + GatewayTransactionId int `json:"gateway_transaction_id"` + ProductId int `json:"product_id"` +} + +// MarshalJSON implements the json.Marshaler interface for RefundSuccess. +// It customizes the JSON marshaling process for RefundSuccess objects. +func (r *RefundSuccess) MarshalJSON() ( + []byte, + error) { + return json.Marshal(r.toMap()) +} + +// toMap converts the RefundSuccess object to a map representation for JSON marshaling. +func (r *RefundSuccess) toMap() map[string]any { + structMap := make(map[string]any) + structMap["refund_id"] = r.RefundId + structMap["gateway_transaction_id"] = r.GatewayTransactionId + structMap["product_id"] = r.ProductId + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RefundSuccess. +// It customizes the JSON unmarshaling process for RefundSuccess objects. +func (r *RefundSuccess) UnmarshalJSON(input []byte) error { + var temp refundSuccess + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.RefundId = *temp.RefundId + r.GatewayTransactionId = *temp.GatewayTransactionId + r.ProductId = *temp.ProductId + return nil +} + +// TODO +type refundSuccess struct { + RefundId *int `json:"refund_id"` + GatewayTransactionId *int `json:"gateway_transaction_id"` + ProductId *int `json:"product_id"` +} + +func (r *refundSuccess) validate() error { + var errs []string + if r.RefundId == nil { + errs = append(errs, "required field `refund_id` is missing for type `Refund Success`") + } + if r.GatewayTransactionId == nil { + errs = append(errs, "required field `gateway_transaction_id` is missing for type `Refund Success`") + } + if r.ProductId == nil { + errs = append(errs, "required field `product_id` is missing for type `Refund Success`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/remove_payment_event_data.go b/models/remove_payment_event_data.go new file mode 100644 index 00000000..9f1f035a --- /dev/null +++ b/models/remove_payment_event_data.go @@ -0,0 +1,115 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// RemovePaymentEventData represents a RemovePaymentEventData struct. +// Example schema for an `remove_payment` event +type RemovePaymentEventData struct { + // Transaction ID of the original payment that was removed + TransactionId int `json:"transaction_id"` + // Memo of the original payment + Memo string `json:"memo"` + // Full amount of the original payment + OriginalAmount *string `json:"original_amount,omitempty"` + // Applied amount of the original payment + AppliedAmount string `json:"applied_amount"` + // Transaction time of the original payment, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" + TransactionTime time.Time `json:"transaction_time"` + // A nested data structure detailing the method of payment + PaymentMethod InvoiceEventPayment2 `json:"payment_method"` + // The flag that shows whether the original payment was a prepayment or not + Prepayment bool `json:"prepayment"` +} + +// MarshalJSON implements the json.Marshaler interface for RemovePaymentEventData. +// It customizes the JSON marshaling process for RemovePaymentEventData objects. +func (r *RemovePaymentEventData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(r.toMap()) +} + +// toMap converts the RemovePaymentEventData object to a map representation for JSON marshaling. +func (r *RemovePaymentEventData) toMap() map[string]any { + structMap := make(map[string]any) + structMap["transaction_id"] = r.TransactionId + structMap["memo"] = r.Memo + if r.OriginalAmount != nil { + structMap["original_amount"] = r.OriginalAmount + } + structMap["applied_amount"] = r.AppliedAmount + structMap["transaction_time"] = r.TransactionTime.Format(time.RFC3339) + structMap["payment_method"] = r.PaymentMethod.toMap() + structMap["prepayment"] = r.Prepayment + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RemovePaymentEventData. +// It customizes the JSON unmarshaling process for RemovePaymentEventData objects. +func (r *RemovePaymentEventData) UnmarshalJSON(input []byte) error { + var temp removePaymentEventData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.TransactionId = *temp.TransactionId + r.Memo = *temp.Memo + r.OriginalAmount = temp.OriginalAmount + r.AppliedAmount = *temp.AppliedAmount + TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) + if err != nil { + log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) + } + r.TransactionTime = TransactionTimeVal + r.PaymentMethod = *temp.PaymentMethod + r.Prepayment = *temp.Prepayment + return nil +} + +// TODO +type removePaymentEventData struct { + TransactionId *int `json:"transaction_id"` + Memo *string `json:"memo"` + OriginalAmount *string `json:"original_amount,omitempty"` + AppliedAmount *string `json:"applied_amount"` + TransactionTime *string `json:"transaction_time"` + PaymentMethod *InvoiceEventPayment2 `json:"payment_method"` + Prepayment *bool `json:"prepayment"` +} + +func (r *removePaymentEventData) validate() error { + var errs []string + if r.TransactionId == nil { + errs = append(errs, "required field `transaction_id` is missing for type `Remove Payment Event Data`") + } + if r.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Remove Payment Event Data`") + } + if r.AppliedAmount == nil { + errs = append(errs, "required field `applied_amount` is missing for type `Remove Payment Event Data`") + } + if r.TransactionTime == nil { + errs = append(errs, "required field `transaction_time` is missing for type `Remove Payment Event Data`") + } + if r.PaymentMethod == nil { + errs = append(errs, "required field `payment_method` is missing for type `Remove Payment Event Data`") + } + if r.Prepayment == nil { + errs = append(errs, "required field `prepayment` is missing for type `Remove Payment Event Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/renewal_preview.go b/models/renewal_preview.go index eac527fd..498444fb 100644 --- a/models/renewal_preview.go +++ b/models/renewal_preview.go @@ -1,107 +1,109 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // RenewalPreview represents a RenewalPreview struct. type RenewalPreview struct { - // The timestamp for the subscription’s next renewal - NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` - // An integer representing the amount of the total pre-tax, pre-discount charges that will be assessed at the next renewal - SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` - // An integer representing the total tax charges that will be assessed at the next renewal - TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` - // An integer representing the amount of the coupon discounts that will be applied to the next renewal - TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` - // An integer representing the total amount owed, less any discounts, that will be assessed at the next renewal - TotalInCents *int64 `json:"total_in_cents,omitempty"` - // An integer representing the amount of the subscription’s current balance - ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` - // An integer representing the existing_balance_in_cents plus the total_in_cents - TotalAmountDueInCents *int64 `json:"total_amount_due_in_cents,omitempty"` - // A boolean indicating whether or not additional taxes will be calculated at the time of renewal. This will be true if you are using Avalara and the address of the subscription is in one of your defined taxable regions. - UncalculatedTaxes *bool `json:"uncalculated_taxes,omitempty"` - // An array of objects representing the individual transactions that will be created at the next renewal - LineItems []RenewalPreviewLineItem `json:"line_items,omitempty"` + // The timestamp for the subscription’s next renewal + NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` + // An integer representing the amount of the total pre-tax, pre-discount charges that will be assessed at the next renewal + SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` + // An integer representing the total tax charges that will be assessed at the next renewal + TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` + // An integer representing the amount of the coupon discounts that will be applied to the next renewal + TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` + // An integer representing the total amount owed, less any discounts, that will be assessed at the next renewal + TotalInCents *int64 `json:"total_in_cents,omitempty"` + // An integer representing the amount of the subscription’s current balance + ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` + // An integer representing the existing_balance_in_cents plus the total_in_cents + TotalAmountDueInCents *int64 `json:"total_amount_due_in_cents,omitempty"` + // A boolean indicating whether or not additional taxes will be calculated at the time of renewal. This will be true if you are using Avalara and the address of the subscription is in one of your defined taxable regions. + UncalculatedTaxes *bool `json:"uncalculated_taxes,omitempty"` + // An array of objects representing the individual transactions that will be created at the next renewal + LineItems []RenewalPreviewLineItem `json:"line_items,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for RenewalPreview. +// MarshalJSON implements the json.Marshaler interface for RenewalPreview. // It customizes the JSON marshaling process for RenewalPreview objects. func (r *RenewalPreview) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RenewalPreview object to a map representation for JSON marshaling. func (r *RenewalPreview) toMap() map[string]any { - structMap := make(map[string]any) - if r.NextAssessmentAt != nil { - structMap["next_assessment_at"] = r.NextAssessmentAt.Format(time.RFC3339) - } - if r.SubtotalInCents != nil { - structMap["subtotal_in_cents"] = r.SubtotalInCents - } - if r.TotalTaxInCents != nil { - structMap["total_tax_in_cents"] = r.TotalTaxInCents - } - if r.TotalDiscountInCents != nil { - structMap["total_discount_in_cents"] = r.TotalDiscountInCents - } - if r.TotalInCents != nil { - structMap["total_in_cents"] = r.TotalInCents - } - if r.ExistingBalanceInCents != nil { - structMap["existing_balance_in_cents"] = r.ExistingBalanceInCents - } - if r.TotalAmountDueInCents != nil { - structMap["total_amount_due_in_cents"] = r.TotalAmountDueInCents - } - if r.UncalculatedTaxes != nil { - structMap["uncalculated_taxes"] = r.UncalculatedTaxes - } - if r.LineItems != nil { - structMap["line_items"] = r.LineItems - } - return structMap + structMap := make(map[string]any) + if r.NextAssessmentAt != nil { + structMap["next_assessment_at"] = r.NextAssessmentAt.Format(time.RFC3339) + } + if r.SubtotalInCents != nil { + structMap["subtotal_in_cents"] = r.SubtotalInCents + } + if r.TotalTaxInCents != nil { + structMap["total_tax_in_cents"] = r.TotalTaxInCents + } + if r.TotalDiscountInCents != nil { + structMap["total_discount_in_cents"] = r.TotalDiscountInCents + } + if r.TotalInCents != nil { + structMap["total_in_cents"] = r.TotalInCents + } + if r.ExistingBalanceInCents != nil { + structMap["existing_balance_in_cents"] = r.ExistingBalanceInCents + } + if r.TotalAmountDueInCents != nil { + structMap["total_amount_due_in_cents"] = r.TotalAmountDueInCents + } + if r.UncalculatedTaxes != nil { + structMap["uncalculated_taxes"] = r.UncalculatedTaxes + } + if r.LineItems != nil { + structMap["line_items"] = r.LineItems + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreview. +// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreview. // It customizes the JSON unmarshaling process for RenewalPreview objects. func (r *RenewalPreview) UnmarshalJSON(input []byte) error { - temp := &struct { - NextAssessmentAt *string `json:"next_assessment_at,omitempty"` - SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` - TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` - TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` - TotalInCents *int64 `json:"total_in_cents,omitempty"` - ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` - TotalAmountDueInCents *int64 `json:"total_amount_due_in_cents,omitempty"` - UncalculatedTaxes *bool `json:"uncalculated_taxes,omitempty"` - LineItems []RenewalPreviewLineItem `json:"line_items,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - if temp.NextAssessmentAt != nil { - NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) - if err != nil { - log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) - } - r.NextAssessmentAt = &NextAssessmentAtVal - } - r.SubtotalInCents = temp.SubtotalInCents - r.TotalTaxInCents = temp.TotalTaxInCents - r.TotalDiscountInCents = temp.TotalDiscountInCents - r.TotalInCents = temp.TotalInCents - r.ExistingBalanceInCents = temp.ExistingBalanceInCents - r.TotalAmountDueInCents = temp.TotalAmountDueInCents - r.UncalculatedTaxes = temp.UncalculatedTaxes - r.LineItems = temp.LineItems - return nil + var temp renewalPreview + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + if temp.NextAssessmentAt != nil { + NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) + if err != nil { + log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) + } + r.NextAssessmentAt = &NextAssessmentAtVal + } + r.SubtotalInCents = temp.SubtotalInCents + r.TotalTaxInCents = temp.TotalTaxInCents + r.TotalDiscountInCents = temp.TotalDiscountInCents + r.TotalInCents = temp.TotalInCents + r.ExistingBalanceInCents = temp.ExistingBalanceInCents + r.TotalAmountDueInCents = temp.TotalAmountDueInCents + r.UncalculatedTaxes = temp.UncalculatedTaxes + r.LineItems = temp.LineItems + return nil +} + +// TODO +type renewalPreview struct { + NextAssessmentAt *string `json:"next_assessment_at,omitempty"` + SubtotalInCents *int64 `json:"subtotal_in_cents,omitempty"` + TotalTaxInCents *int64 `json:"total_tax_in_cents,omitempty"` + TotalDiscountInCents *int64 `json:"total_discount_in_cents,omitempty"` + TotalInCents *int64 `json:"total_in_cents,omitempty"` + ExistingBalanceInCents *int64 `json:"existing_balance_in_cents,omitempty"` + TotalAmountDueInCents *int64 `json:"total_amount_due_in_cents,omitempty"` + UncalculatedTaxes *bool `json:"uncalculated_taxes,omitempty"` + LineItems []RenewalPreviewLineItem `json:"line_items,omitempty"` } diff --git a/models/renewal_preview_component.go b/models/renewal_preview_component.go index 0f19c16d..0d00db8b 100644 --- a/models/renewal_preview_component.go +++ b/models/renewal_preview_component.go @@ -1,62 +1,64 @@ package models import ( - "encoding/json" + "encoding/json" ) // RenewalPreviewComponent represents a RenewalPreviewComponent struct. type RenewalPreviewComponent struct { - // Either the component's Chargify id or its handle prefixed with `handle:` - ComponentId *interface{} `json:"component_id,omitempty"` - // The quantity for which you wish to preview billing. This is useful if you want to preview a predicted, higher usage value than is currently present on the subscription. - // This quantity represents: - // - Whether or not an on/off component is enabled - use 0 for disabled or 1 for enabled - // - The desired allocated_quantity for a quantity-based component - // - The desired unit_balance for a metered component - // - The desired metric quantity for an events-based component - Quantity *int `json:"quantity,omitempty"` - // Either the component price point's Chargify id or its handle prefixed with `handle:` - PricePointId *interface{} `json:"price_point_id,omitempty"` + // Either the component's Chargify id or its handle prefixed with `handle:` + ComponentId *RenewalPreviewComponentComponentId `json:"component_id,omitempty"` + // The quantity for which you wish to preview billing. This is useful if you want to preview a predicted, higher usage value than is currently present on the subscription. + // This quantity represents: + // - Whether or not an on/off component is enabled - use 0 for disabled or 1 for enabled + // - The desired allocated_quantity for a quantity-based component + // - The desired unit_balance for a metered component + // - The desired metric quantity for an events-based component + Quantity *int `json:"quantity,omitempty"` + // Either the component price point's Chargify id or its handle prefixed with `handle:` + PricePointId *RenewalPreviewComponentPricePointId `json:"price_point_id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for RenewalPreviewComponent. +// MarshalJSON implements the json.Marshaler interface for RenewalPreviewComponent. // It customizes the JSON marshaling process for RenewalPreviewComponent objects. func (r *RenewalPreviewComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RenewalPreviewComponent object to a map representation for JSON marshaling. func (r *RenewalPreviewComponent) toMap() map[string]any { - structMap := make(map[string]any) - if r.ComponentId != nil { - structMap["component_id"] = r.ComponentId - } - if r.Quantity != nil { - structMap["quantity"] = r.Quantity - } - if r.PricePointId != nil { - structMap["price_point_id"] = r.PricePointId - } - return structMap + structMap := make(map[string]any) + if r.ComponentId != nil { + structMap["component_id"] = r.ComponentId.toMap() + } + if r.Quantity != nil { + structMap["quantity"] = r.Quantity + } + if r.PricePointId != nil { + structMap["price_point_id"] = r.PricePointId.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreviewComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreviewComponent. // It customizes the JSON unmarshaling process for RenewalPreviewComponent objects. func (r *RenewalPreviewComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - ComponentId *interface{} `json:"component_id,omitempty"` - Quantity *int `json:"quantity,omitempty"` - PricePointId *interface{} `json:"price_point_id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.ComponentId = temp.ComponentId - r.Quantity = temp.Quantity - r.PricePointId = temp.PricePointId - return nil + var temp renewalPreviewComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.ComponentId = temp.ComponentId + r.Quantity = temp.Quantity + r.PricePointId = temp.PricePointId + return nil +} + +// TODO +type renewalPreviewComponent struct { + ComponentId *RenewalPreviewComponentComponentId `json:"component_id,omitempty"` + Quantity *int `json:"quantity,omitempty"` + PricePointId *RenewalPreviewComponentPricePointId `json:"price_point_id,omitempty"` } diff --git a/models/renewal_preview_component_component_id.go b/models/renewal_preview_component_component_id.go new file mode 100644 index 00000000..d6ca281d --- /dev/null +++ b/models/renewal_preview_component_component_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// RenewalPreviewComponentComponentId represents a RenewalPreviewComponentComponentId struct. +// This is a container for one-of cases. +type RenewalPreviewComponentComponentId struct { + value any + isString bool + isNumber bool +} + +// String converts the RenewalPreviewComponentComponentId object to a string representation. +func (r RenewalPreviewComponentComponentId) String() string { + if bytes, err := json.Marshal(r.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for RenewalPreviewComponentComponentId. +// It customizes the JSON marshaling process for RenewalPreviewComponentComponentId objects. +func (r *RenewalPreviewComponentComponentId) MarshalJSON() ( + []byte, + error) { + if r.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.RenewalPreviewComponentComponentIdContainer.From*` functions to initialize the RenewalPreviewComponentComponentId object.") + } + return json.Marshal(r.toMap()) +} + +// toMap converts the RenewalPreviewComponentComponentId object to a map representation for JSON marshaling. +func (r *RenewalPreviewComponentComponentId) toMap() any { + switch obj := r.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreviewComponentComponentId. +// It customizes the JSON unmarshaling process for RenewalPreviewComponentComponentId objects. +func (r *RenewalPreviewComponentComponentId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &r.isString), + NewTypeHolder(new(int), false, &r.isNumber), + ) + + r.value = result + return err +} + +func (r *RenewalPreviewComponentComponentId) AsString() ( + *string, + bool) { + if !r.isString { + return nil, false + } + return r.value.(*string), true +} + +func (r *RenewalPreviewComponentComponentId) AsNumber() ( + *int, + bool) { + if !r.isNumber { + return nil, false + } + return r.value.(*int), true +} + +// internalRenewalPreviewComponentComponentId represents a renewalPreviewComponentComponentId struct. +// This is a container for one-of cases. +type internalRenewalPreviewComponentComponentId struct{} + +var RenewalPreviewComponentComponentIdContainer internalRenewalPreviewComponentComponentId + +func (r *internalRenewalPreviewComponentComponentId) FromString(val string) RenewalPreviewComponentComponentId { + return RenewalPreviewComponentComponentId{value: &val} +} + +func (r *internalRenewalPreviewComponentComponentId) FromNumber(val int) RenewalPreviewComponentComponentId { + return RenewalPreviewComponentComponentId{value: &val} +} diff --git a/models/renewal_preview_component_price_point_id.go b/models/renewal_preview_component_price_point_id.go new file mode 100644 index 00000000..552726c0 --- /dev/null +++ b/models/renewal_preview_component_price_point_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// RenewalPreviewComponentPricePointId represents a RenewalPreviewComponentPricePointId struct. +// This is a container for one-of cases. +type RenewalPreviewComponentPricePointId struct { + value any + isString bool + isNumber bool +} + +// String converts the RenewalPreviewComponentPricePointId object to a string representation. +func (r RenewalPreviewComponentPricePointId) String() string { + if bytes, err := json.Marshal(r.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for RenewalPreviewComponentPricePointId. +// It customizes the JSON marshaling process for RenewalPreviewComponentPricePointId objects. +func (r *RenewalPreviewComponentPricePointId) MarshalJSON() ( + []byte, + error) { + if r.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.RenewalPreviewComponentPricePointIdContainer.From*` functions to initialize the RenewalPreviewComponentPricePointId object.") + } + return json.Marshal(r.toMap()) +} + +// toMap converts the RenewalPreviewComponentPricePointId object to a map representation for JSON marshaling. +func (r *RenewalPreviewComponentPricePointId) toMap() any { + switch obj := r.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreviewComponentPricePointId. +// It customizes the JSON unmarshaling process for RenewalPreviewComponentPricePointId objects. +func (r *RenewalPreviewComponentPricePointId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &r.isString), + NewTypeHolder(new(int), false, &r.isNumber), + ) + + r.value = result + return err +} + +func (r *RenewalPreviewComponentPricePointId) AsString() ( + *string, + bool) { + if !r.isString { + return nil, false + } + return r.value.(*string), true +} + +func (r *RenewalPreviewComponentPricePointId) AsNumber() ( + *int, + bool) { + if !r.isNumber { + return nil, false + } + return r.value.(*int), true +} + +// internalRenewalPreviewComponentPricePointId represents a renewalPreviewComponentPricePointId struct. +// This is a container for one-of cases. +type internalRenewalPreviewComponentPricePointId struct{} + +var RenewalPreviewComponentPricePointIdContainer internalRenewalPreviewComponentPricePointId + +func (r *internalRenewalPreviewComponentPricePointId) FromString(val string) RenewalPreviewComponentPricePointId { + return RenewalPreviewComponentPricePointId{value: &val} +} + +func (r *internalRenewalPreviewComponentPricePointId) FromNumber(val int) RenewalPreviewComponentPricePointId { + return RenewalPreviewComponentPricePointId{value: &val} +} diff --git a/models/renewal_preview_line_item.go b/models/renewal_preview_line_item.go index e7d5b101..1f5ef426 100644 --- a/models/renewal_preview_line_item.go +++ b/models/renewal_preview_line_item.go @@ -1,122 +1,124 @@ package models import ( - "encoding/json" + "encoding/json" ) // RenewalPreviewLineItem represents a RenewalPreviewLineItem struct. type RenewalPreviewLineItem struct { - // A handle for the line item transaction type - TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` - // A handle for the line item kind - Kind *LineItemKind `json:"kind,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - Memo *string `json:"memo,omitempty"` - DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` - TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` - ProductId *int `json:"product_id,omitempty"` - ProductName *string `json:"product_name,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - ComponentHandle *string `json:"component_handle,omitempty"` - ComponentName *string `json:"component_name,omitempty"` - ProductHandle *string `json:"product_handle,omitempty"` - PeriodRangeStart *string `json:"period_range_start,omitempty"` - PeriodRangeEnd *string `json:"period_range_end,omitempty"` + // A handle for the line item transaction type + TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` + // A handle for the line item kind + Kind *LineItemKind `json:"kind,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + Memo *string `json:"memo,omitempty"` + DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` + TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductName *string `json:"product_name,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + ComponentHandle *string `json:"component_handle,omitempty"` + ComponentName *string `json:"component_name,omitempty"` + ProductHandle *string `json:"product_handle,omitempty"` + PeriodRangeStart *string `json:"period_range_start,omitempty"` + PeriodRangeEnd *string `json:"period_range_end,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for RenewalPreviewLineItem. +// MarshalJSON implements the json.Marshaler interface for RenewalPreviewLineItem. // It customizes the JSON marshaling process for RenewalPreviewLineItem objects. func (r *RenewalPreviewLineItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RenewalPreviewLineItem object to a map representation for JSON marshaling. func (r *RenewalPreviewLineItem) toMap() map[string]any { - structMap := make(map[string]any) - if r.TransactionType != nil { - structMap["transaction_type"] = r.TransactionType - } - if r.Kind != nil { - structMap["kind"] = r.Kind - } - if r.AmountInCents != nil { - structMap["amount_in_cents"] = r.AmountInCents - } - if r.Memo != nil { - structMap["memo"] = r.Memo - } - if r.DiscountAmountInCents != nil { - structMap["discount_amount_in_cents"] = r.DiscountAmountInCents - } - if r.TaxableAmountInCents != nil { - structMap["taxable_amount_in_cents"] = r.TaxableAmountInCents - } - if r.ProductId != nil { - structMap["product_id"] = r.ProductId - } - if r.ProductName != nil { - structMap["product_name"] = r.ProductName - } - if r.ComponentId != nil { - structMap["component_id"] = r.ComponentId - } - if r.ComponentHandle != nil { - structMap["component_handle"] = r.ComponentHandle - } - if r.ComponentName != nil { - structMap["component_name"] = r.ComponentName - } - if r.ProductHandle != nil { - structMap["product_handle"] = r.ProductHandle - } - if r.PeriodRangeStart != nil { - structMap["period_range_start"] = r.PeriodRangeStart - } - if r.PeriodRangeEnd != nil { - structMap["period_range_end"] = r.PeriodRangeEnd - } - return structMap + structMap := make(map[string]any) + if r.TransactionType != nil { + structMap["transaction_type"] = r.TransactionType + } + if r.Kind != nil { + structMap["kind"] = r.Kind + } + if r.AmountInCents != nil { + structMap["amount_in_cents"] = r.AmountInCents + } + if r.Memo != nil { + structMap["memo"] = r.Memo + } + if r.DiscountAmountInCents != nil { + structMap["discount_amount_in_cents"] = r.DiscountAmountInCents + } + if r.TaxableAmountInCents != nil { + structMap["taxable_amount_in_cents"] = r.TaxableAmountInCents + } + if r.ProductId != nil { + structMap["product_id"] = r.ProductId + } + if r.ProductName != nil { + structMap["product_name"] = r.ProductName + } + if r.ComponentId != nil { + structMap["component_id"] = r.ComponentId + } + if r.ComponentHandle != nil { + structMap["component_handle"] = r.ComponentHandle + } + if r.ComponentName != nil { + structMap["component_name"] = r.ComponentName + } + if r.ProductHandle != nil { + structMap["product_handle"] = r.ProductHandle + } + if r.PeriodRangeStart != nil { + structMap["period_range_start"] = r.PeriodRangeStart + } + if r.PeriodRangeEnd != nil { + structMap["period_range_end"] = r.PeriodRangeEnd + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreviewLineItem. +// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreviewLineItem. // It customizes the JSON unmarshaling process for RenewalPreviewLineItem objects. func (r *RenewalPreviewLineItem) UnmarshalJSON(input []byte) error { - temp := &struct { - TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` - Kind *LineItemKind `json:"kind,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - Memo *string `json:"memo,omitempty"` - DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` - TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` - ProductId *int `json:"product_id,omitempty"` - ProductName *string `json:"product_name,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - ComponentHandle *string `json:"component_handle,omitempty"` - ComponentName *string `json:"component_name,omitempty"` - ProductHandle *string `json:"product_handle,omitempty"` - PeriodRangeStart *string `json:"period_range_start,omitempty"` - PeriodRangeEnd *string `json:"period_range_end,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.TransactionType = temp.TransactionType - r.Kind = temp.Kind - r.AmountInCents = temp.AmountInCents - r.Memo = temp.Memo - r.DiscountAmountInCents = temp.DiscountAmountInCents - r.TaxableAmountInCents = temp.TaxableAmountInCents - r.ProductId = temp.ProductId - r.ProductName = temp.ProductName - r.ComponentId = temp.ComponentId - r.ComponentHandle = temp.ComponentHandle - r.ComponentName = temp.ComponentName - r.ProductHandle = temp.ProductHandle - r.PeriodRangeStart = temp.PeriodRangeStart - r.PeriodRangeEnd = temp.PeriodRangeEnd - return nil + var temp renewalPreviewLineItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.TransactionType = temp.TransactionType + r.Kind = temp.Kind + r.AmountInCents = temp.AmountInCents + r.Memo = temp.Memo + r.DiscountAmountInCents = temp.DiscountAmountInCents + r.TaxableAmountInCents = temp.TaxableAmountInCents + r.ProductId = temp.ProductId + r.ProductName = temp.ProductName + r.ComponentId = temp.ComponentId + r.ComponentHandle = temp.ComponentHandle + r.ComponentName = temp.ComponentName + r.ProductHandle = temp.ProductHandle + r.PeriodRangeStart = temp.PeriodRangeStart + r.PeriodRangeEnd = temp.PeriodRangeEnd + return nil +} + +// TODO +type renewalPreviewLineItem struct { + TransactionType *LineItemTransactionType `json:"transaction_type,omitempty"` + Kind *LineItemKind `json:"kind,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + Memo *string `json:"memo,omitempty"` + DiscountAmountInCents *int64 `json:"discount_amount_in_cents,omitempty"` + TaxableAmountInCents *int64 `json:"taxable_amount_in_cents,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductName *string `json:"product_name,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + ComponentHandle *string `json:"component_handle,omitempty"` + ComponentName *string `json:"component_name,omitempty"` + ProductHandle *string `json:"product_handle,omitempty"` + PeriodRangeStart *string `json:"period_range_start,omitempty"` + PeriodRangeEnd *string `json:"period_range_end,omitempty"` } diff --git a/models/renewal_preview_request.go b/models/renewal_preview_request.go index 95c6b923..18672788 100644 --- a/models/renewal_preview_request.go +++ b/models/renewal_preview_request.go @@ -1,43 +1,45 @@ package models import ( - "encoding/json" + "encoding/json" ) // RenewalPreviewRequest represents a RenewalPreviewRequest struct. type RenewalPreviewRequest struct { - // An optional array of component definitions to preview. Providing any component definitions here will override the actual components on the subscription (and their quantities), and the billing preview will contain only these components (in addition to any product base fees). - Components []RenewalPreviewComponent `json:"components,omitempty"` + // An optional array of component definitions to preview. Providing any component definitions here will override the actual components on the subscription (and their quantities), and the billing preview will contain only these components (in addition to any product base fees). + Components []RenewalPreviewComponent `json:"components,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for RenewalPreviewRequest. +// MarshalJSON implements the json.Marshaler interface for RenewalPreviewRequest. // It customizes the JSON marshaling process for RenewalPreviewRequest objects. func (r *RenewalPreviewRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RenewalPreviewRequest object to a map representation for JSON marshaling. func (r *RenewalPreviewRequest) toMap() map[string]any { - structMap := make(map[string]any) - if r.Components != nil { - structMap["components"] = r.Components - } - return structMap + structMap := make(map[string]any) + if r.Components != nil { + structMap["components"] = r.Components + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreviewRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreviewRequest. // It customizes the JSON unmarshaling process for RenewalPreviewRequest objects. func (r *RenewalPreviewRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Components []RenewalPreviewComponent `json:"components,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Components = temp.Components - return nil + var temp renewalPreviewRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.Components = temp.Components + return nil +} + +// TODO +type renewalPreviewRequest struct { + Components []RenewalPreviewComponent `json:"components,omitempty"` } diff --git a/models/renewal_preview_response.go b/models/renewal_preview_response.go index 30d5b4b0..133708ea 100644 --- a/models/renewal_preview_response.go +++ b/models/renewal_preview_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // RenewalPreviewResponse represents a RenewalPreviewResponse struct. type RenewalPreviewResponse struct { - RenewalPreview RenewalPreview `json:"renewal_preview"` + RenewalPreview RenewalPreview `json:"renewal_preview"` } -// MarshalJSON implements the json.Marshaler interface for RenewalPreviewResponse. +// MarshalJSON implements the json.Marshaler interface for RenewalPreviewResponse. // It customizes the JSON marshaling process for RenewalPreviewResponse objects. func (r *RenewalPreviewResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RenewalPreviewResponse object to a map representation for JSON marshaling. func (r *RenewalPreviewResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["renewal_preview"] = r.RenewalPreview.toMap() - return structMap + structMap := make(map[string]any) + structMap["renewal_preview"] = r.RenewalPreview.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreviewResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for RenewalPreviewResponse. // It customizes the JSON unmarshaling process for RenewalPreviewResponse objects. func (r *RenewalPreviewResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - RenewalPreview RenewalPreview `json:"renewal_preview"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.RenewalPreview = temp.RenewalPreview - return nil + var temp renewalPreviewResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.RenewalPreview = *temp.RenewalPreview + return nil +} + +// TODO +type renewalPreviewResponse struct { + RenewalPreview *RenewalPreview `json:"renewal_preview"` +} + +func (r *renewalPreviewResponse) validate() error { + var errs []string + if r.RenewalPreview == nil { + errs = append(errs, "required field `renewal_preview` is missing for type `Renewal Preview Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/replay_webhooks_request.go b/models/replay_webhooks_request.go index 8c48b99d..fc4f7d69 100644 --- a/models/replay_webhooks_request.go +++ b/models/replay_webhooks_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ReplayWebhooksRequest represents a ReplayWebhooksRequest struct. type ReplayWebhooksRequest struct { - Ids []int64 `json:"ids"` + Ids []int64 `json:"ids"` } -// MarshalJSON implements the json.Marshaler interface for ReplayWebhooksRequest. +// MarshalJSON implements the json.Marshaler interface for ReplayWebhooksRequest. // It customizes the JSON marshaling process for ReplayWebhooksRequest objects. func (r *ReplayWebhooksRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ReplayWebhooksRequest object to a map representation for JSON marshaling. func (r *ReplayWebhooksRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["ids"] = r.Ids - return structMap + structMap := make(map[string]any) + structMap["ids"] = r.Ids + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ReplayWebhooksRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for ReplayWebhooksRequest. // It customizes the JSON unmarshaling process for ReplayWebhooksRequest objects. func (r *ReplayWebhooksRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Ids []int64 `json:"ids"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Ids = temp.Ids - return nil + var temp replayWebhooksRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + r.Ids = *temp.Ids + return nil +} + +// TODO +type replayWebhooksRequest struct { + Ids *[]int64 `json:"ids"` +} + +func (r *replayWebhooksRequest) validate() error { + var errs []string + if r.Ids == nil { + errs = append(errs, "required field `ids` is missing for type `Replay Webhooks Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/replay_webhooks_response.go b/models/replay_webhooks_response.go index f77f3934..e7269234 100644 --- a/models/replay_webhooks_response.go +++ b/models/replay_webhooks_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // ReplayWebhooksResponse represents a ReplayWebhooksResponse struct. type ReplayWebhooksResponse struct { - Status *string `json:"status,omitempty"` + Status *string `json:"status,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ReplayWebhooksResponse. +// MarshalJSON implements the json.Marshaler interface for ReplayWebhooksResponse. // It customizes the JSON marshaling process for ReplayWebhooksResponse objects. func (r *ReplayWebhooksResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ReplayWebhooksResponse object to a map representation for JSON marshaling. func (r *ReplayWebhooksResponse) toMap() map[string]any { - structMap := make(map[string]any) - if r.Status != nil { - structMap["status"] = r.Status - } - return structMap + structMap := make(map[string]any) + if r.Status != nil { + structMap["status"] = r.Status + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ReplayWebhooksResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ReplayWebhooksResponse. // It customizes the JSON unmarshaling process for ReplayWebhooksResponse objects. func (r *ReplayWebhooksResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Status *string `json:"status,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.Status = temp.Status - return nil + var temp replayWebhooksResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.Status = temp.Status + return nil +} + +// TODO +type replayWebhooksResponse struct { + Status *string `json:"status,omitempty"` } diff --git a/models/resent_invitation.go b/models/resent_invitation.go index 16f12980..12673fcf 100644 --- a/models/resent_invitation.go +++ b/models/resent_invitation.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // ResentInvitation represents a ResentInvitation struct. type ResentInvitation struct { - LastSentAt *string `json:"last_sent_at,omitempty"` - LastAcceptedAt *string `json:"last_accepted_at,omitempty"` - SendInviteLinkText *string `json:"send_invite_link_text,omitempty"` - UninvitedCount *int `json:"uninvited_count,omitempty"` + LastSentAt *string `json:"last_sent_at,omitempty"` + LastAcceptedAt *string `json:"last_accepted_at,omitempty"` + SendInviteLinkText *string `json:"send_invite_link_text,omitempty"` + UninvitedCount *int `json:"uninvited_count,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ResentInvitation. +// MarshalJSON implements the json.Marshaler interface for ResentInvitation. // It customizes the JSON marshaling process for ResentInvitation objects. func (r *ResentInvitation) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the ResentInvitation object to a map representation for JSON marshaling. func (r *ResentInvitation) toMap() map[string]any { - structMap := make(map[string]any) - if r.LastSentAt != nil { - structMap["last_sent_at"] = r.LastSentAt - } - if r.LastAcceptedAt != nil { - structMap["last_accepted_at"] = r.LastAcceptedAt - } - if r.SendInviteLinkText != nil { - structMap["send_invite_link_text"] = r.SendInviteLinkText - } - if r.UninvitedCount != nil { - structMap["uninvited_count"] = r.UninvitedCount - } - return structMap + structMap := make(map[string]any) + if r.LastSentAt != nil { + structMap["last_sent_at"] = r.LastSentAt + } + if r.LastAcceptedAt != nil { + structMap["last_accepted_at"] = r.LastAcceptedAt + } + if r.SendInviteLinkText != nil { + structMap["send_invite_link_text"] = r.SendInviteLinkText + } + if r.UninvitedCount != nil { + structMap["uninvited_count"] = r.UninvitedCount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ResentInvitation. +// UnmarshalJSON implements the json.Unmarshaler interface for ResentInvitation. // It customizes the JSON unmarshaling process for ResentInvitation objects. func (r *ResentInvitation) UnmarshalJSON(input []byte) error { - temp := &struct { - LastSentAt *string `json:"last_sent_at,omitempty"` - LastAcceptedAt *string `json:"last_accepted_at,omitempty"` - SendInviteLinkText *string `json:"send_invite_link_text,omitempty"` - UninvitedCount *int `json:"uninvited_count,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.LastSentAt = temp.LastSentAt - r.LastAcceptedAt = temp.LastAcceptedAt - r.SendInviteLinkText = temp.SendInviteLinkText - r.UninvitedCount = temp.UninvitedCount - return nil + var temp resentInvitation + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.LastSentAt = temp.LastSentAt + r.LastAcceptedAt = temp.LastAcceptedAt + r.SendInviteLinkText = temp.SendInviteLinkText + r.UninvitedCount = temp.UninvitedCount + return nil +} + +// TODO +type resentInvitation struct { + LastSentAt *string `json:"last_sent_at,omitempty"` + LastAcceptedAt *string `json:"last_accepted_at,omitempty"` + SendInviteLinkText *string `json:"send_invite_link_text,omitempty"` + UninvitedCount *int `json:"uninvited_count,omitempty"` } diff --git a/models/resume_options.go b/models/resume_options.go new file mode 100644 index 00000000..5075163d --- /dev/null +++ b/models/resume_options.go @@ -0,0 +1,52 @@ +package models + +import ( + "encoding/json" +) + +// ResumeOptions represents a ResumeOptions struct. +type ResumeOptions struct { + // Chargify will only attempt to resume the subscription's billing period. If not resumable, the subscription will be left in it's current state. + RequireResume *bool `json:"require_resume,omitempty"` + // Indicates whether or not Chargify should clear the subscription's existing balance before attempting to resume the subscription. If subscription cannot be resumed, the balance will remain as it was before the attempt to resume was made. + ForgiveBalance *bool `json:"forgive_balance,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for ResumeOptions. +// It customizes the JSON marshaling process for ResumeOptions objects. +func (r *ResumeOptions) MarshalJSON() ( + []byte, + error) { + return json.Marshal(r.toMap()) +} + +// toMap converts the ResumeOptions object to a map representation for JSON marshaling. +func (r *ResumeOptions) toMap() map[string]any { + structMap := make(map[string]any) + if r.RequireResume != nil { + structMap["require_resume"] = r.RequireResume + } + if r.ForgiveBalance != nil { + structMap["forgive_balance"] = r.ForgiveBalance + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for ResumeOptions. +// It customizes the JSON unmarshaling process for ResumeOptions objects. +func (r *ResumeOptions) UnmarshalJSON(input []byte) error { + var temp resumeOptions + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.RequireResume = temp.RequireResume + r.ForgiveBalance = temp.ForgiveBalance + return nil +} + +// TODO +type resumeOptions struct { + RequireResume *bool `json:"require_resume,omitempty"` + ForgiveBalance *bool `json:"forgive_balance,omitempty"` +} diff --git a/models/revoked_invitation.go b/models/revoked_invitation.go index 6d8b64aa..9db235c9 100644 --- a/models/revoked_invitation.go +++ b/models/revoked_invitation.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // RevokedInvitation represents a RevokedInvitation struct. type RevokedInvitation struct { - LastSentAt *string `json:"last_sent_at,omitempty"` - LastAcceptedAt *string `json:"last_accepted_at,omitempty"` - UninvitedCount *int `json:"uninvited_count,omitempty"` + LastSentAt *string `json:"last_sent_at,omitempty"` + LastAcceptedAt *string `json:"last_accepted_at,omitempty"` + UninvitedCount *int `json:"uninvited_count,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for RevokedInvitation. +// MarshalJSON implements the json.Marshaler interface for RevokedInvitation. // It customizes the JSON marshaling process for RevokedInvitation objects. func (r *RevokedInvitation) MarshalJSON() ( - []byte, - error) { - return json.Marshal(r.toMap()) + []byte, + error) { + return json.Marshal(r.toMap()) } // toMap converts the RevokedInvitation object to a map representation for JSON marshaling. func (r *RevokedInvitation) toMap() map[string]any { - structMap := make(map[string]any) - if r.LastSentAt != nil { - structMap["last_sent_at"] = r.LastSentAt - } - if r.LastAcceptedAt != nil { - structMap["last_accepted_at"] = r.LastAcceptedAt - } - if r.UninvitedCount != nil { - structMap["uninvited_count"] = r.UninvitedCount - } - return structMap + structMap := make(map[string]any) + if r.LastSentAt != nil { + structMap["last_sent_at"] = r.LastSentAt + } + if r.LastAcceptedAt != nil { + structMap["last_accepted_at"] = r.LastAcceptedAt + } + if r.UninvitedCount != nil { + structMap["uninvited_count"] = r.UninvitedCount + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for RevokedInvitation. +// UnmarshalJSON implements the json.Unmarshaler interface for RevokedInvitation. // It customizes the JSON unmarshaling process for RevokedInvitation objects. func (r *RevokedInvitation) UnmarshalJSON(input []byte) error { - temp := &struct { - LastSentAt *string `json:"last_sent_at,omitempty"` - LastAcceptedAt *string `json:"last_accepted_at,omitempty"` - UninvitedCount *int `json:"uninvited_count,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - r.LastSentAt = temp.LastSentAt - r.LastAcceptedAt = temp.LastAcceptedAt - r.UninvitedCount = temp.UninvitedCount - return nil + var temp revokedInvitation + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + r.LastSentAt = temp.LastSentAt + r.LastAcceptedAt = temp.LastAcceptedAt + r.UninvitedCount = temp.UninvitedCount + return nil +} + +// TODO +type revokedInvitation struct { + LastSentAt *string `json:"last_sent_at,omitempty"` + LastAcceptedAt *string `json:"last_accepted_at,omitempty"` + UninvitedCount *int `json:"uninvited_count,omitempty"` } diff --git a/models/sale_rep.go b/models/sale_rep.go index 00f75a00..ec69a0ea 100644 --- a/models/sale_rep.go +++ b/models/sale_rep.go @@ -1,66 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" ) // SaleRep represents a SaleRep struct. type SaleRep struct { - Id *int `json:"id,omitempty"` - FullName *string `json:"full_name,omitempty"` - SubscriptionsCount *int `json:"subscriptions_count,omitempty"` - TestMode *bool `json:"test_mode,omitempty"` - Subscriptions []SaleRepSubscription `json:"subscriptions,omitempty"` + Id *int `json:"id,omitempty"` + FullName *string `json:"full_name,omitempty"` + SubscriptionsCount *int `json:"subscriptions_count,omitempty"` + TestMode *bool `json:"test_mode,omitempty"` + Subscriptions []SaleRepSubscription `json:"subscriptions,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SaleRep. +// MarshalJSON implements the json.Marshaler interface for SaleRep. // It customizes the JSON marshaling process for SaleRep objects. func (s *SaleRep) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SaleRep object to a map representation for JSON marshaling. func (s *SaleRep) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.FullName != nil { - structMap["full_name"] = s.FullName - } - if s.SubscriptionsCount != nil { - structMap["subscriptions_count"] = s.SubscriptionsCount - } - if s.TestMode != nil { - structMap["test_mode"] = s.TestMode - } - if s.Subscriptions != nil { - structMap["subscriptions"] = s.Subscriptions - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.FullName != nil { + structMap["full_name"] = s.FullName + } + if s.SubscriptionsCount != nil { + structMap["subscriptions_count"] = s.SubscriptionsCount + } + if s.TestMode != nil { + structMap["test_mode"] = s.TestMode + } + if s.Subscriptions != nil { + structMap["subscriptions"] = s.Subscriptions + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SaleRep. +// UnmarshalJSON implements the json.Unmarshaler interface for SaleRep. // It customizes the JSON unmarshaling process for SaleRep objects. func (s *SaleRep) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - FullName *string `json:"full_name,omitempty"` - SubscriptionsCount *int `json:"subscriptions_count,omitempty"` - TestMode *bool `json:"test_mode,omitempty"` - Subscriptions []SaleRepSubscription `json:"subscriptions,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.FullName = temp.FullName - s.SubscriptionsCount = temp.SubscriptionsCount - s.TestMode = temp.TestMode - s.Subscriptions = temp.Subscriptions - return nil + var temp saleRep + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.FullName = temp.FullName + s.SubscriptionsCount = temp.SubscriptionsCount + s.TestMode = temp.TestMode + s.Subscriptions = temp.Subscriptions + return nil +} + +// TODO +type saleRep struct { + Id *int `json:"id,omitempty"` + FullName *string `json:"full_name,omitempty"` + SubscriptionsCount *int `json:"subscriptions_count,omitempty"` + TestMode *bool `json:"test_mode,omitempty"` + Subscriptions []SaleRepSubscription `json:"subscriptions,omitempty"` } diff --git a/models/sale_rep_item_mrr.go b/models/sale_rep_item_mrr.go index acbb75a8..af31a808 100644 --- a/models/sale_rep_item_mrr.go +++ b/models/sale_rep_item_mrr.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // SaleRepItemMrr represents a SaleRepItemMrr struct. type SaleRepItemMrr struct { - Mrr *string `json:"mrr,omitempty"` - Usage *string `json:"usage,omitempty"` - Recurring *string `json:"recurring,omitempty"` + Mrr *string `json:"mrr,omitempty"` + Usage *string `json:"usage,omitempty"` + Recurring *string `json:"recurring,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SaleRepItemMrr. +// MarshalJSON implements the json.Marshaler interface for SaleRepItemMrr. // It customizes the JSON marshaling process for SaleRepItemMrr objects. func (s *SaleRepItemMrr) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SaleRepItemMrr object to a map representation for JSON marshaling. func (s *SaleRepItemMrr) toMap() map[string]any { - structMap := make(map[string]any) - if s.Mrr != nil { - structMap["mrr"] = s.Mrr - } - if s.Usage != nil { - structMap["usage"] = s.Usage - } - if s.Recurring != nil { - structMap["recurring"] = s.Recurring - } - return structMap + structMap := make(map[string]any) + if s.Mrr != nil { + structMap["mrr"] = s.Mrr + } + if s.Usage != nil { + structMap["usage"] = s.Usage + } + if s.Recurring != nil { + structMap["recurring"] = s.Recurring + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SaleRepItemMrr. +// UnmarshalJSON implements the json.Unmarshaler interface for SaleRepItemMrr. // It customizes the JSON unmarshaling process for SaleRepItemMrr objects. func (s *SaleRepItemMrr) UnmarshalJSON(input []byte) error { - temp := &struct { - Mrr *string `json:"mrr,omitempty"` - Usage *string `json:"usage,omitempty"` - Recurring *string `json:"recurring,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Mrr = temp.Mrr - s.Usage = temp.Usage - s.Recurring = temp.Recurring - return nil + var temp saleRepItemMrr + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Mrr = temp.Mrr + s.Usage = temp.Usage + s.Recurring = temp.Recurring + return nil +} + +// TODO +type saleRepItemMrr struct { + Mrr *string `json:"mrr,omitempty"` + Usage *string `json:"usage,omitempty"` + Recurring *string `json:"recurring,omitempty"` } diff --git a/models/sale_rep_settings.go b/models/sale_rep_settings.go index 69e92c04..a3f61810 100644 --- a/models/sale_rep_settings.go +++ b/models/sale_rep_settings.go @@ -1,78 +1,80 @@ package models import ( - "encoding/json" + "encoding/json" ) // SaleRepSettings represents a SaleRepSettings struct. type SaleRepSettings struct { - CustomerName *string `json:"customer_name,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - SiteLink *string `json:"site_link,omitempty"` - SiteName *string `json:"site_name,omitempty"` - SubscriptionMrr *string `json:"subscription_mrr,omitempty"` - SalesRepId *int `json:"sales_rep_id,omitempty"` - SalesRepName *string `json:"sales_rep_name,omitempty"` + CustomerName *string `json:"customer_name,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + SiteLink *string `json:"site_link,omitempty"` + SiteName *string `json:"site_name,omitempty"` + SubscriptionMrr *string `json:"subscription_mrr,omitempty"` + SalesRepId *int `json:"sales_rep_id,omitempty"` + SalesRepName *string `json:"sales_rep_name,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SaleRepSettings. +// MarshalJSON implements the json.Marshaler interface for SaleRepSettings. // It customizes the JSON marshaling process for SaleRepSettings objects. func (s *SaleRepSettings) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SaleRepSettings object to a map representation for JSON marshaling. func (s *SaleRepSettings) toMap() map[string]any { - structMap := make(map[string]any) - if s.CustomerName != nil { - structMap["customer_name"] = s.CustomerName - } - if s.SubscriptionId != nil { - structMap["subscription_id"] = s.SubscriptionId - } - if s.SiteLink != nil { - structMap["site_link"] = s.SiteLink - } - if s.SiteName != nil { - structMap["site_name"] = s.SiteName - } - if s.SubscriptionMrr != nil { - structMap["subscription_mrr"] = s.SubscriptionMrr - } - if s.SalesRepId != nil { - structMap["sales_rep_id"] = s.SalesRepId - } - if s.SalesRepName != nil { - structMap["sales_rep_name"] = s.SalesRepName - } - return structMap + structMap := make(map[string]any) + if s.CustomerName != nil { + structMap["customer_name"] = s.CustomerName + } + if s.SubscriptionId != nil { + structMap["subscription_id"] = s.SubscriptionId + } + if s.SiteLink != nil { + structMap["site_link"] = s.SiteLink + } + if s.SiteName != nil { + structMap["site_name"] = s.SiteName + } + if s.SubscriptionMrr != nil { + structMap["subscription_mrr"] = s.SubscriptionMrr + } + if s.SalesRepId != nil { + structMap["sales_rep_id"] = s.SalesRepId + } + if s.SalesRepName != nil { + structMap["sales_rep_name"] = s.SalesRepName + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SaleRepSettings. +// UnmarshalJSON implements the json.Unmarshaler interface for SaleRepSettings. // It customizes the JSON unmarshaling process for SaleRepSettings objects. func (s *SaleRepSettings) UnmarshalJSON(input []byte) error { - temp := &struct { - CustomerName *string `json:"customer_name,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - SiteLink *string `json:"site_link,omitempty"` - SiteName *string `json:"site_name,omitempty"` - SubscriptionMrr *string `json:"subscription_mrr,omitempty"` - SalesRepId *int `json:"sales_rep_id,omitempty"` - SalesRepName *string `json:"sales_rep_name,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.CustomerName = temp.CustomerName - s.SubscriptionId = temp.SubscriptionId - s.SiteLink = temp.SiteLink - s.SiteName = temp.SiteName - s.SubscriptionMrr = temp.SubscriptionMrr - s.SalesRepId = temp.SalesRepId - s.SalesRepName = temp.SalesRepName - return nil + var temp saleRepSettings + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.CustomerName = temp.CustomerName + s.SubscriptionId = temp.SubscriptionId + s.SiteLink = temp.SiteLink + s.SiteName = temp.SiteName + s.SubscriptionMrr = temp.SubscriptionMrr + s.SalesRepId = temp.SalesRepId + s.SalesRepName = temp.SalesRepName + return nil +} + +// TODO +type saleRepSettings struct { + CustomerName *string `json:"customer_name,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + SiteLink *string `json:"site_link,omitempty"` + SiteName *string `json:"site_name,omitempty"` + SubscriptionMrr *string `json:"subscription_mrr,omitempty"` + SalesRepId *int `json:"sales_rep_id,omitempty"` + SalesRepName *string `json:"sales_rep_name,omitempty"` } diff --git a/models/sale_rep_subscription.go b/models/sale_rep_subscription.go index b9c5c031..ed2ba5c3 100644 --- a/models/sale_rep_subscription.go +++ b/models/sale_rep_subscription.go @@ -1,96 +1,102 @@ package models import ( - "encoding/json" + "encoding/json" ) // SaleRepSubscription represents a SaleRepSubscription struct. type SaleRepSubscription struct { - Id *int `json:"id,omitempty"` - SiteName *string `json:"site_name,omitempty"` - SubscriptionUrl *string `json:"subscription_url,omitempty"` - CustomerName *string `json:"customer_name,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - Mrr *string `json:"mrr,omitempty"` - Usage *string `json:"usage,omitempty"` - Recurring *string `json:"recurring,omitempty"` - LastPayment *string `json:"last_payment,omitempty"` - ChurnDate Optional[string] `json:"churn_date"` + Id *int `json:"id,omitempty"` + SiteName *string `json:"site_name,omitempty"` + SubscriptionUrl *string `json:"subscription_url,omitempty"` + CustomerName *string `json:"customer_name,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + Mrr *string `json:"mrr,omitempty"` + Usage *string `json:"usage,omitempty"` + Recurring *string `json:"recurring,omitempty"` + LastPayment *string `json:"last_payment,omitempty"` + ChurnDate Optional[string] `json:"churn_date"` } -// MarshalJSON implements the json.Marshaler interface for SaleRepSubscription. +// MarshalJSON implements the json.Marshaler interface for SaleRepSubscription. // It customizes the JSON marshaling process for SaleRepSubscription objects. func (s *SaleRepSubscription) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SaleRepSubscription object to a map representation for JSON marshaling. func (s *SaleRepSubscription) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.SiteName != nil { - structMap["site_name"] = s.SiteName - } - if s.SubscriptionUrl != nil { - structMap["subscription_url"] = s.SubscriptionUrl - } - if s.CustomerName != nil { - structMap["customer_name"] = s.CustomerName - } - if s.CreatedAt != nil { - structMap["created_at"] = s.CreatedAt - } - if s.Mrr != nil { - structMap["mrr"] = s.Mrr - } - if s.Usage != nil { - structMap["usage"] = s.Usage - } - if s.Recurring != nil { - structMap["recurring"] = s.Recurring - } - if s.LastPayment != nil { - structMap["last_payment"] = s.LastPayment - } - if s.ChurnDate.IsValueSet() { - structMap["churn_date"] = s.ChurnDate.Value() - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.SiteName != nil { + structMap["site_name"] = s.SiteName + } + if s.SubscriptionUrl != nil { + structMap["subscription_url"] = s.SubscriptionUrl + } + if s.CustomerName != nil { + structMap["customer_name"] = s.CustomerName + } + if s.CreatedAt != nil { + structMap["created_at"] = s.CreatedAt + } + if s.Mrr != nil { + structMap["mrr"] = s.Mrr + } + if s.Usage != nil { + structMap["usage"] = s.Usage + } + if s.Recurring != nil { + structMap["recurring"] = s.Recurring + } + if s.LastPayment != nil { + structMap["last_payment"] = s.LastPayment + } + if s.ChurnDate.IsValueSet() { + if s.ChurnDate.Value() != nil { + structMap["churn_date"] = s.ChurnDate.Value() + } else { + structMap["churn_date"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SaleRepSubscription. +// UnmarshalJSON implements the json.Unmarshaler interface for SaleRepSubscription. // It customizes the JSON unmarshaling process for SaleRepSubscription objects. func (s *SaleRepSubscription) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - SiteName *string `json:"site_name,omitempty"` - SubscriptionUrl *string `json:"subscription_url,omitempty"` - CustomerName *string `json:"customer_name,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - Mrr *string `json:"mrr,omitempty"` - Usage *string `json:"usage,omitempty"` - Recurring *string `json:"recurring,omitempty"` - LastPayment *string `json:"last_payment,omitempty"` - ChurnDate Optional[string] `json:"churn_date"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.SiteName = temp.SiteName - s.SubscriptionUrl = temp.SubscriptionUrl - s.CustomerName = temp.CustomerName - s.CreatedAt = temp.CreatedAt - s.Mrr = temp.Mrr - s.Usage = temp.Usage - s.Recurring = temp.Recurring - s.LastPayment = temp.LastPayment - s.ChurnDate = temp.ChurnDate - return nil + var temp saleRepSubscription + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.SiteName = temp.SiteName + s.SubscriptionUrl = temp.SubscriptionUrl + s.CustomerName = temp.CustomerName + s.CreatedAt = temp.CreatedAt + s.Mrr = temp.Mrr + s.Usage = temp.Usage + s.Recurring = temp.Recurring + s.LastPayment = temp.LastPayment + s.ChurnDate = temp.ChurnDate + return nil +} + +// TODO +type saleRepSubscription struct { + Id *int `json:"id,omitempty"` + SiteName *string `json:"site_name,omitempty"` + SubscriptionUrl *string `json:"subscription_url,omitempty"` + CustomerName *string `json:"customer_name,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + Mrr *string `json:"mrr,omitempty"` + Usage *string `json:"usage,omitempty"` + Recurring *string `json:"recurring,omitempty"` + LastPayment *string `json:"last_payment,omitempty"` + ChurnDate Optional[string] `json:"churn_date"` } diff --git a/models/segment.go b/models/segment.go index 8a1deae9..98185afd 100644 --- a/models/segment.go +++ b/models/segment.go @@ -1,123 +1,125 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Segment represents a Segment struct. type Segment struct { - Id *int `json:"id,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - EventBasedBillingMetricId *int `json:"event_based_billing_metric_id,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - SegmentProperty1Value *interface{} `json:"segment_property_1_value,omitempty"` - SegmentProperty2Value *interface{} `json:"segment_property_2_value,omitempty"` - SegmentProperty3Value *interface{} `json:"segment_property_3_value,omitempty"` - SegmentProperty4Value *interface{} `json:"segment_property_4_value,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - Prices []SegmentPrice `json:"prices,omitempty"` + Id *int `json:"id,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + EventBasedBillingMetricId *int `json:"event_based_billing_metric_id,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + SegmentProperty1Value *SegmentSegmentProperty1Value `json:"segment_property_1_value,omitempty"` + SegmentProperty2Value *SegmentSegmentProperty2Value `json:"segment_property_2_value,omitempty"` + SegmentProperty3Value *SegmentSegmentProperty3Value `json:"segment_property_3_value,omitempty"` + SegmentProperty4Value *SegmentSegmentProperty4Value `json:"segment_property_4_value,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + Prices []SegmentPrice `json:"prices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Segment. +// MarshalJSON implements the json.Marshaler interface for Segment. // It customizes the JSON marshaling process for Segment objects. func (s *Segment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the Segment object to a map representation for JSON marshaling. func (s *Segment) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.ComponentId != nil { - structMap["component_id"] = s.ComponentId - } - if s.PricePointId != nil { - structMap["price_point_id"] = s.PricePointId - } - if s.EventBasedBillingMetricId != nil { - structMap["event_based_billing_metric_id"] = s.EventBasedBillingMetricId - } - if s.PricingScheme != nil { - structMap["pricing_scheme"] = s.PricingScheme - } - if s.SegmentProperty1Value != nil { - structMap["segment_property_1_value"] = s.SegmentProperty1Value - } - if s.SegmentProperty2Value != nil { - structMap["segment_property_2_value"] = s.SegmentProperty2Value - } - if s.SegmentProperty3Value != nil { - structMap["segment_property_3_value"] = s.SegmentProperty3Value - } - if s.SegmentProperty4Value != nil { - structMap["segment_property_4_value"] = s.SegmentProperty4Value - } - if s.CreatedAt != nil { - structMap["created_at"] = s.CreatedAt.Format(time.RFC3339) - } - if s.UpdatedAt != nil { - structMap["updated_at"] = s.UpdatedAt.Format(time.RFC3339) - } - if s.Prices != nil { - structMap["prices"] = s.Prices - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.ComponentId != nil { + structMap["component_id"] = s.ComponentId + } + if s.PricePointId != nil { + structMap["price_point_id"] = s.PricePointId + } + if s.EventBasedBillingMetricId != nil { + structMap["event_based_billing_metric_id"] = s.EventBasedBillingMetricId + } + if s.PricingScheme != nil { + structMap["pricing_scheme"] = s.PricingScheme + } + if s.SegmentProperty1Value != nil { + structMap["segment_property_1_value"] = s.SegmentProperty1Value.toMap() + } + if s.SegmentProperty2Value != nil { + structMap["segment_property_2_value"] = s.SegmentProperty2Value.toMap() + } + if s.SegmentProperty3Value != nil { + structMap["segment_property_3_value"] = s.SegmentProperty3Value.toMap() + } + if s.SegmentProperty4Value != nil { + structMap["segment_property_4_value"] = s.SegmentProperty4Value.toMap() + } + if s.CreatedAt != nil { + structMap["created_at"] = s.CreatedAt.Format(time.RFC3339) + } + if s.UpdatedAt != nil { + structMap["updated_at"] = s.UpdatedAt.Format(time.RFC3339) + } + if s.Prices != nil { + structMap["prices"] = s.Prices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Segment. +// UnmarshalJSON implements the json.Unmarshaler interface for Segment. // It customizes the JSON unmarshaling process for Segment objects. func (s *Segment) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - EventBasedBillingMetricId *int `json:"event_based_billing_metric_id,omitempty"` - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - SegmentProperty1Value *interface{} `json:"segment_property_1_value,omitempty"` - SegmentProperty2Value *interface{} `json:"segment_property_2_value,omitempty"` - SegmentProperty3Value *interface{} `json:"segment_property_3_value,omitempty"` - SegmentProperty4Value *interface{} `json:"segment_property_4_value,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - Prices []SegmentPrice `json:"prices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.ComponentId = temp.ComponentId - s.PricePointId = temp.PricePointId - s.EventBasedBillingMetricId = temp.EventBasedBillingMetricId - s.PricingScheme = temp.PricingScheme - s.SegmentProperty1Value = temp.SegmentProperty1Value - s.SegmentProperty2Value = temp.SegmentProperty2Value - s.SegmentProperty3Value = temp.SegmentProperty3Value - s.SegmentProperty4Value = temp.SegmentProperty4Value - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - s.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - s.UpdatedAt = &UpdatedAtVal - } - s.Prices = temp.Prices - return nil + var temp segment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.ComponentId = temp.ComponentId + s.PricePointId = temp.PricePointId + s.EventBasedBillingMetricId = temp.EventBasedBillingMetricId + s.PricingScheme = temp.PricingScheme + s.SegmentProperty1Value = temp.SegmentProperty1Value + s.SegmentProperty2Value = temp.SegmentProperty2Value + s.SegmentProperty3Value = temp.SegmentProperty3Value + s.SegmentProperty4Value = temp.SegmentProperty4Value + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + s.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + s.UpdatedAt = &UpdatedAtVal + } + s.Prices = temp.Prices + return nil +} + +// TODO +type segment struct { + Id *int `json:"id,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + EventBasedBillingMetricId *int `json:"event_based_billing_metric_id,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + SegmentProperty1Value *SegmentSegmentProperty1Value `json:"segment_property_1_value,omitempty"` + SegmentProperty2Value *SegmentSegmentProperty2Value `json:"segment_property_2_value,omitempty"` + SegmentProperty3Value *SegmentSegmentProperty3Value `json:"segment_property_3_value,omitempty"` + SegmentProperty4Value *SegmentSegmentProperty4Value `json:"segment_property_4_value,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + Prices []SegmentPrice `json:"prices,omitempty"` } diff --git a/models/segment_price.go b/models/segment_price.go index 47487b93..741ed153 100644 --- a/models/segment_price.go +++ b/models/segment_price.go @@ -1,84 +1,90 @@ package models import ( - "encoding/json" + "encoding/json" ) // SegmentPrice represents a SegmentPrice struct. type SegmentPrice struct { - Id *int `json:"id,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - StartingQuantity *int `json:"starting_quantity,omitempty"` - EndingQuantity Optional[int] `json:"ending_quantity"` - UnitPrice *string `json:"unit_price,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - FormattedUnitPrice *string `json:"formatted_unit_price,omitempty"` - SegmentId *int `json:"segment_id,omitempty"` + Id *int `json:"id,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + StartingQuantity *int `json:"starting_quantity,omitempty"` + EndingQuantity Optional[int] `json:"ending_quantity"` + UnitPrice *string `json:"unit_price,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + FormattedUnitPrice *string `json:"formatted_unit_price,omitempty"` + SegmentId *int `json:"segment_id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SegmentPrice. +// MarshalJSON implements the json.Marshaler interface for SegmentPrice. // It customizes the JSON marshaling process for SegmentPrice objects. func (s *SegmentPrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SegmentPrice object to a map representation for JSON marshaling. func (s *SegmentPrice) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.ComponentId != nil { - structMap["component_id"] = s.ComponentId - } - if s.StartingQuantity != nil { - structMap["starting_quantity"] = s.StartingQuantity - } - if s.EndingQuantity.IsValueSet() { - structMap["ending_quantity"] = s.EndingQuantity.Value() - } - if s.UnitPrice != nil { - structMap["unit_price"] = s.UnitPrice - } - if s.PricePointId != nil { - structMap["price_point_id"] = s.PricePointId - } - if s.FormattedUnitPrice != nil { - structMap["formatted_unit_price"] = s.FormattedUnitPrice - } - if s.SegmentId != nil { - structMap["segment_id"] = s.SegmentId - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.ComponentId != nil { + structMap["component_id"] = s.ComponentId + } + if s.StartingQuantity != nil { + structMap["starting_quantity"] = s.StartingQuantity + } + if s.EndingQuantity.IsValueSet() { + if s.EndingQuantity.Value() != nil { + structMap["ending_quantity"] = s.EndingQuantity.Value() + } else { + structMap["ending_quantity"] = nil + } + } + if s.UnitPrice != nil { + structMap["unit_price"] = s.UnitPrice + } + if s.PricePointId != nil { + structMap["price_point_id"] = s.PricePointId + } + if s.FormattedUnitPrice != nil { + structMap["formatted_unit_price"] = s.FormattedUnitPrice + } + if s.SegmentId != nil { + structMap["segment_id"] = s.SegmentId + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SegmentPrice. +// UnmarshalJSON implements the json.Unmarshaler interface for SegmentPrice. // It customizes the JSON unmarshaling process for SegmentPrice objects. func (s *SegmentPrice) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - StartingQuantity *int `json:"starting_quantity,omitempty"` - EndingQuantity Optional[int] `json:"ending_quantity"` - UnitPrice *string `json:"unit_price,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - FormattedUnitPrice *string `json:"formatted_unit_price,omitempty"` - SegmentId *int `json:"segment_id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.ComponentId = temp.ComponentId - s.StartingQuantity = temp.StartingQuantity - s.EndingQuantity = temp.EndingQuantity - s.UnitPrice = temp.UnitPrice - s.PricePointId = temp.PricePointId - s.FormattedUnitPrice = temp.FormattedUnitPrice - s.SegmentId = temp.SegmentId - return nil + var temp segmentPrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.ComponentId = temp.ComponentId + s.StartingQuantity = temp.StartingQuantity + s.EndingQuantity = temp.EndingQuantity + s.UnitPrice = temp.UnitPrice + s.PricePointId = temp.PricePointId + s.FormattedUnitPrice = temp.FormattedUnitPrice + s.SegmentId = temp.SegmentId + return nil +} + +// TODO +type segmentPrice struct { + Id *int `json:"id,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + StartingQuantity *int `json:"starting_quantity,omitempty"` + EndingQuantity Optional[int] `json:"ending_quantity"` + UnitPrice *string `json:"unit_price,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + FormattedUnitPrice *string `json:"formatted_unit_price,omitempty"` + SegmentId *int `json:"segment_id,omitempty"` } diff --git a/models/segment_response.go b/models/segment_response.go index 45e134f2..442c1837 100644 --- a/models/segment_response.go +++ b/models/segment_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // SegmentResponse represents a SegmentResponse struct. type SegmentResponse struct { - Segment *Segment `json:"segment,omitempty"` + Segment *Segment `json:"segment,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SegmentResponse. +// MarshalJSON implements the json.Marshaler interface for SegmentResponse. // It customizes the JSON marshaling process for SegmentResponse objects. func (s *SegmentResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SegmentResponse object to a map representation for JSON marshaling. func (s *SegmentResponse) toMap() map[string]any { - structMap := make(map[string]any) - if s.Segment != nil { - structMap["segment"] = s.Segment.toMap() - } - return structMap + structMap := make(map[string]any) + if s.Segment != nil { + structMap["segment"] = s.Segment.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SegmentResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SegmentResponse. // It customizes the JSON unmarshaling process for SegmentResponse objects. func (s *SegmentResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Segment *Segment `json:"segment,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Segment = temp.Segment - return nil + var temp segmentResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Segment = temp.Segment + return nil +} + +// TODO +type segmentResponse struct { + Segment *Segment `json:"segment,omitempty"` } diff --git a/models/segment_segment_property_1_value.go b/models/segment_segment_property_1_value.go new file mode 100644 index 00000000..4925f6b8 --- /dev/null +++ b/models/segment_segment_property_1_value.go @@ -0,0 +1,128 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SegmentSegmentProperty1Value represents a SegmentSegmentProperty1Value struct. +// This is a container for one-of cases. +type SegmentSegmentProperty1Value struct { + value any + isString bool + isPrecision bool + isNumber bool + isBoolean bool +} + +// String converts the SegmentSegmentProperty1Value object to a string representation. +func (s SegmentSegmentProperty1Value) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SegmentSegmentProperty1Value. +// It customizes the JSON marshaling process for SegmentSegmentProperty1Value objects. +func (s *SegmentSegmentProperty1Value) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SegmentSegmentProperty1ValueContainer.From*` functions to initialize the SegmentSegmentProperty1Value object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SegmentSegmentProperty1Value object to a map representation for JSON marshaling. +func (s *SegmentSegmentProperty1Value) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *float64: + return *obj + case *int: + return *obj + case *bool: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SegmentSegmentProperty1Value. +// It customizes the JSON unmarshaling process for SegmentSegmentProperty1Value objects. +func (s *SegmentSegmentProperty1Value) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(float64), false, &s.isPrecision), + NewTypeHolder(new(int), false, &s.isNumber), + NewTypeHolder(new(bool), false, &s.isBoolean), + ) + + s.value = result + return err +} + +func (s *SegmentSegmentProperty1Value) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SegmentSegmentProperty1Value) AsPrecision() ( + *float64, + bool) { + if !s.isPrecision { + return nil, false + } + return s.value.(*float64), true +} + +func (s *SegmentSegmentProperty1Value) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +func (s *SegmentSegmentProperty1Value) AsBoolean() ( + *bool, + bool) { + if !s.isBoolean { + return nil, false + } + return s.value.(*bool), true +} + +// internalSegmentSegmentProperty1Value represents a segmentSegmentProperty1Value struct. +// This is a container for one-of cases. +type internalSegmentSegmentProperty1Value struct{} + +var SegmentSegmentProperty1ValueContainer internalSegmentSegmentProperty1Value + +func (s *internalSegmentSegmentProperty1Value) FromString(val string) SegmentSegmentProperty1Value { + return SegmentSegmentProperty1Value{value: &val} +} + +func (s *internalSegmentSegmentProperty1Value) FromPrecision(val float64) SegmentSegmentProperty1Value { + return SegmentSegmentProperty1Value{value: &val} +} + +func (s *internalSegmentSegmentProperty1Value) FromNumber(val int) SegmentSegmentProperty1Value { + return SegmentSegmentProperty1Value{value: &val} +} + +func (s *internalSegmentSegmentProperty1Value) FromBoolean(val bool) SegmentSegmentProperty1Value { + return SegmentSegmentProperty1Value{value: &val} +} diff --git a/models/segment_segment_property_2_value.go b/models/segment_segment_property_2_value.go new file mode 100644 index 00000000..a0989882 --- /dev/null +++ b/models/segment_segment_property_2_value.go @@ -0,0 +1,128 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SegmentSegmentProperty2Value represents a SegmentSegmentProperty2Value struct. +// This is a container for one-of cases. +type SegmentSegmentProperty2Value struct { + value any + isString bool + isPrecision bool + isNumber bool + isBoolean bool +} + +// String converts the SegmentSegmentProperty2Value object to a string representation. +func (s SegmentSegmentProperty2Value) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SegmentSegmentProperty2Value. +// It customizes the JSON marshaling process for SegmentSegmentProperty2Value objects. +func (s *SegmentSegmentProperty2Value) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SegmentSegmentProperty2ValueContainer.From*` functions to initialize the SegmentSegmentProperty2Value object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SegmentSegmentProperty2Value object to a map representation for JSON marshaling. +func (s *SegmentSegmentProperty2Value) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *float64: + return *obj + case *int: + return *obj + case *bool: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SegmentSegmentProperty2Value. +// It customizes the JSON unmarshaling process for SegmentSegmentProperty2Value objects. +func (s *SegmentSegmentProperty2Value) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(float64), false, &s.isPrecision), + NewTypeHolder(new(int), false, &s.isNumber), + NewTypeHolder(new(bool), false, &s.isBoolean), + ) + + s.value = result + return err +} + +func (s *SegmentSegmentProperty2Value) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SegmentSegmentProperty2Value) AsPrecision() ( + *float64, + bool) { + if !s.isPrecision { + return nil, false + } + return s.value.(*float64), true +} + +func (s *SegmentSegmentProperty2Value) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +func (s *SegmentSegmentProperty2Value) AsBoolean() ( + *bool, + bool) { + if !s.isBoolean { + return nil, false + } + return s.value.(*bool), true +} + +// internalSegmentSegmentProperty2Value represents a segmentSegmentProperty2Value struct. +// This is a container for one-of cases. +type internalSegmentSegmentProperty2Value struct{} + +var SegmentSegmentProperty2ValueContainer internalSegmentSegmentProperty2Value + +func (s *internalSegmentSegmentProperty2Value) FromString(val string) SegmentSegmentProperty2Value { + return SegmentSegmentProperty2Value{value: &val} +} + +func (s *internalSegmentSegmentProperty2Value) FromPrecision(val float64) SegmentSegmentProperty2Value { + return SegmentSegmentProperty2Value{value: &val} +} + +func (s *internalSegmentSegmentProperty2Value) FromNumber(val int) SegmentSegmentProperty2Value { + return SegmentSegmentProperty2Value{value: &val} +} + +func (s *internalSegmentSegmentProperty2Value) FromBoolean(val bool) SegmentSegmentProperty2Value { + return SegmentSegmentProperty2Value{value: &val} +} diff --git a/models/segment_segment_property_3_value.go b/models/segment_segment_property_3_value.go new file mode 100644 index 00000000..fcea1701 --- /dev/null +++ b/models/segment_segment_property_3_value.go @@ -0,0 +1,128 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SegmentSegmentProperty3Value represents a SegmentSegmentProperty3Value struct. +// This is a container for one-of cases. +type SegmentSegmentProperty3Value struct { + value any + isString bool + isPrecision bool + isNumber bool + isBoolean bool +} + +// String converts the SegmentSegmentProperty3Value object to a string representation. +func (s SegmentSegmentProperty3Value) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SegmentSegmentProperty3Value. +// It customizes the JSON marshaling process for SegmentSegmentProperty3Value objects. +func (s *SegmentSegmentProperty3Value) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SegmentSegmentProperty3ValueContainer.From*` functions to initialize the SegmentSegmentProperty3Value object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SegmentSegmentProperty3Value object to a map representation for JSON marshaling. +func (s *SegmentSegmentProperty3Value) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *float64: + return *obj + case *int: + return *obj + case *bool: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SegmentSegmentProperty3Value. +// It customizes the JSON unmarshaling process for SegmentSegmentProperty3Value objects. +func (s *SegmentSegmentProperty3Value) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(float64), false, &s.isPrecision), + NewTypeHolder(new(int), false, &s.isNumber), + NewTypeHolder(new(bool), false, &s.isBoolean), + ) + + s.value = result + return err +} + +func (s *SegmentSegmentProperty3Value) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SegmentSegmentProperty3Value) AsPrecision() ( + *float64, + bool) { + if !s.isPrecision { + return nil, false + } + return s.value.(*float64), true +} + +func (s *SegmentSegmentProperty3Value) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +func (s *SegmentSegmentProperty3Value) AsBoolean() ( + *bool, + bool) { + if !s.isBoolean { + return nil, false + } + return s.value.(*bool), true +} + +// internalSegmentSegmentProperty3Value represents a segmentSegmentProperty3Value struct. +// This is a container for one-of cases. +type internalSegmentSegmentProperty3Value struct{} + +var SegmentSegmentProperty3ValueContainer internalSegmentSegmentProperty3Value + +func (s *internalSegmentSegmentProperty3Value) FromString(val string) SegmentSegmentProperty3Value { + return SegmentSegmentProperty3Value{value: &val} +} + +func (s *internalSegmentSegmentProperty3Value) FromPrecision(val float64) SegmentSegmentProperty3Value { + return SegmentSegmentProperty3Value{value: &val} +} + +func (s *internalSegmentSegmentProperty3Value) FromNumber(val int) SegmentSegmentProperty3Value { + return SegmentSegmentProperty3Value{value: &val} +} + +func (s *internalSegmentSegmentProperty3Value) FromBoolean(val bool) SegmentSegmentProperty3Value { + return SegmentSegmentProperty3Value{value: &val} +} diff --git a/models/segment_segment_property_4_value.go b/models/segment_segment_property_4_value.go new file mode 100644 index 00000000..b7da6c7f --- /dev/null +++ b/models/segment_segment_property_4_value.go @@ -0,0 +1,128 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SegmentSegmentProperty4Value represents a SegmentSegmentProperty4Value struct. +// This is a container for one-of cases. +type SegmentSegmentProperty4Value struct { + value any + isString bool + isPrecision bool + isNumber bool + isBoolean bool +} + +// String converts the SegmentSegmentProperty4Value object to a string representation. +func (s SegmentSegmentProperty4Value) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SegmentSegmentProperty4Value. +// It customizes the JSON marshaling process for SegmentSegmentProperty4Value objects. +func (s *SegmentSegmentProperty4Value) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SegmentSegmentProperty4ValueContainer.From*` functions to initialize the SegmentSegmentProperty4Value object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SegmentSegmentProperty4Value object to a map representation for JSON marshaling. +func (s *SegmentSegmentProperty4Value) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *float64: + return *obj + case *int: + return *obj + case *bool: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SegmentSegmentProperty4Value. +// It customizes the JSON unmarshaling process for SegmentSegmentProperty4Value objects. +func (s *SegmentSegmentProperty4Value) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(float64), false, &s.isPrecision), + NewTypeHolder(new(int), false, &s.isNumber), + NewTypeHolder(new(bool), false, &s.isBoolean), + ) + + s.value = result + return err +} + +func (s *SegmentSegmentProperty4Value) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SegmentSegmentProperty4Value) AsPrecision() ( + *float64, + bool) { + if !s.isPrecision { + return nil, false + } + return s.value.(*float64), true +} + +func (s *SegmentSegmentProperty4Value) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +func (s *SegmentSegmentProperty4Value) AsBoolean() ( + *bool, + bool) { + if !s.isBoolean { + return nil, false + } + return s.value.(*bool), true +} + +// internalSegmentSegmentProperty4Value represents a segmentSegmentProperty4Value struct. +// This is a container for one-of cases. +type internalSegmentSegmentProperty4Value struct{} + +var SegmentSegmentProperty4ValueContainer internalSegmentSegmentProperty4Value + +func (s *internalSegmentSegmentProperty4Value) FromString(val string) SegmentSegmentProperty4Value { + return SegmentSegmentProperty4Value{value: &val} +} + +func (s *internalSegmentSegmentProperty4Value) FromPrecision(val float64) SegmentSegmentProperty4Value { + return SegmentSegmentProperty4Value{value: &val} +} + +func (s *internalSegmentSegmentProperty4Value) FromNumber(val int) SegmentSegmentProperty4Value { + return SegmentSegmentProperty4Value{value: &val} +} + +func (s *internalSegmentSegmentProperty4Value) FromBoolean(val bool) SegmentSegmentProperty4Value { + return SegmentSegmentProperty4Value{value: &val} +} diff --git a/models/seller.go b/models/seller.go index a82e4926..bfcadb5d 100644 --- a/models/seller.go +++ b/models/seller.go @@ -1,60 +1,66 @@ package models import ( - "encoding/json" + "encoding/json" ) // Seller represents a Seller struct. type Seller struct { - Name *string `json:"name,omitempty"` - Address *InvoiceAddress `json:"address,omitempty"` - Phone *string `json:"phone,omitempty"` - LogoUrl Optional[string] `json:"logo_url"` + Name *string `json:"name,omitempty"` + Address *InvoiceAddress `json:"address,omitempty"` + Phone *string `json:"phone,omitempty"` + LogoUrl Optional[string] `json:"logo_url"` } -// MarshalJSON implements the json.Marshaler interface for Seller. +// MarshalJSON implements the json.Marshaler interface for Seller. // It customizes the JSON marshaling process for Seller objects. func (s *Seller) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the Seller object to a map representation for JSON marshaling. func (s *Seller) toMap() map[string]any { - structMap := make(map[string]any) - if s.Name != nil { - structMap["name"] = s.Name - } - if s.Address != nil { - structMap["address"] = s.Address.toMap() - } - if s.Phone != nil { - structMap["phone"] = s.Phone - } - if s.LogoUrl.IsValueSet() { - structMap["logo_url"] = s.LogoUrl.Value() - } - return structMap + structMap := make(map[string]any) + if s.Name != nil { + structMap["name"] = s.Name + } + if s.Address != nil { + structMap["address"] = s.Address.toMap() + } + if s.Phone != nil { + structMap["phone"] = s.Phone + } + if s.LogoUrl.IsValueSet() { + if s.LogoUrl.Value() != nil { + structMap["logo_url"] = s.LogoUrl.Value() + } else { + structMap["logo_url"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Seller. +// UnmarshalJSON implements the json.Unmarshaler interface for Seller. // It customizes the JSON unmarshaling process for Seller objects. func (s *Seller) UnmarshalJSON(input []byte) error { - temp := &struct { - Name *string `json:"name,omitempty"` - Address *InvoiceAddress `json:"address,omitempty"` - Phone *string `json:"phone,omitempty"` - LogoUrl Optional[string] `json:"logo_url"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Name = temp.Name - s.Address = temp.Address - s.Phone = temp.Phone - s.LogoUrl = temp.LogoUrl - return nil + var temp seller + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Name = temp.Name + s.Address = temp.Address + s.Phone = temp.Phone + s.LogoUrl = temp.LogoUrl + return nil +} + +// TODO +type seller struct { + Name *string `json:"name,omitempty"` + Address *InvoiceAddress `json:"address,omitempty"` + Phone *string `json:"phone,omitempty"` + LogoUrl Optional[string] `json:"logo_url"` } diff --git a/models/send_invoice_request.go b/models/send_invoice_request.go index 64322a23..d8053aa7 100644 --- a/models/send_invoice_request.go +++ b/models/send_invoice_request.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // SendInvoiceRequest represents a SendInvoiceRequest struct. type SendInvoiceRequest struct { - RecipientEmails []string `json:"recipient_emails,omitempty"` - CcRecipientEmails []string `json:"cc_recipient_emails,omitempty"` - BccRecipientEmails []string `json:"bcc_recipient_emails,omitempty"` + RecipientEmails []string `json:"recipient_emails,omitempty"` + CcRecipientEmails []string `json:"cc_recipient_emails,omitempty"` + BccRecipientEmails []string `json:"bcc_recipient_emails,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SendInvoiceRequest. +// MarshalJSON implements the json.Marshaler interface for SendInvoiceRequest. // It customizes the JSON marshaling process for SendInvoiceRequest objects. func (s *SendInvoiceRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SendInvoiceRequest object to a map representation for JSON marshaling. func (s *SendInvoiceRequest) toMap() map[string]any { - structMap := make(map[string]any) - if s.RecipientEmails != nil { - structMap["recipient_emails"] = s.RecipientEmails - } - if s.CcRecipientEmails != nil { - structMap["cc_recipient_emails"] = s.CcRecipientEmails - } - if s.BccRecipientEmails != nil { - structMap["bcc_recipient_emails"] = s.BccRecipientEmails - } - return structMap + structMap := make(map[string]any) + if s.RecipientEmails != nil { + structMap["recipient_emails"] = s.RecipientEmails + } + if s.CcRecipientEmails != nil { + structMap["cc_recipient_emails"] = s.CcRecipientEmails + } + if s.BccRecipientEmails != nil { + structMap["bcc_recipient_emails"] = s.BccRecipientEmails + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SendInvoiceRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for SendInvoiceRequest. // It customizes the JSON unmarshaling process for SendInvoiceRequest objects. func (s *SendInvoiceRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - RecipientEmails []string `json:"recipient_emails,omitempty"` - CcRecipientEmails []string `json:"cc_recipient_emails,omitempty"` - BccRecipientEmails []string `json:"bcc_recipient_emails,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.RecipientEmails = temp.RecipientEmails - s.CcRecipientEmails = temp.CcRecipientEmails - s.BccRecipientEmails = temp.BccRecipientEmails - return nil + var temp sendInvoiceRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.RecipientEmails = temp.RecipientEmails + s.CcRecipientEmails = temp.CcRecipientEmails + s.BccRecipientEmails = temp.BccRecipientEmails + return nil +} + +// TODO +type sendInvoiceRequest struct { + RecipientEmails []string `json:"recipient_emails,omitempty"` + CcRecipientEmails []string `json:"cc_recipient_emails,omitempty"` + BccRecipientEmails []string `json:"bcc_recipient_emails,omitempty"` } diff --git a/models/service_credit.go b/models/service_credit.go index eb4d5b67..041b3e74 100644 --- a/models/service_credit.go +++ b/models/service_credit.go @@ -1,70 +1,72 @@ package models import ( - "encoding/json" + "encoding/json" ) // ServiceCredit represents a ServiceCredit struct. type ServiceCredit struct { - Id *int `json:"id,omitempty"` - // The amount in cents of the entry - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - // The new balance for the credit account - EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` - // The type of entry - EntryType *ServiceCreditType `json:"entry_type,omitempty"` - // The memo attached to the entry - Memo *string `json:"memo,omitempty"` + Id *int `json:"id,omitempty"` + // The amount in cents of the entry + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + // The new balance for the credit account + EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` + // The type of entry + EntryType *ServiceCreditType `json:"entry_type,omitempty"` + // The memo attached to the entry + Memo *string `json:"memo,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for ServiceCredit. +// MarshalJSON implements the json.Marshaler interface for ServiceCredit. // It customizes the JSON marshaling process for ServiceCredit objects. func (s *ServiceCredit) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the ServiceCredit object to a map representation for JSON marshaling. func (s *ServiceCredit) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.AmountInCents != nil { - structMap["amount_in_cents"] = s.AmountInCents - } - if s.EndingBalanceInCents != nil { - structMap["ending_balance_in_cents"] = s.EndingBalanceInCents - } - if s.EntryType != nil { - structMap["entry_type"] = s.EntryType - } - if s.Memo != nil { - structMap["memo"] = s.Memo - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.AmountInCents != nil { + structMap["amount_in_cents"] = s.AmountInCents + } + if s.EndingBalanceInCents != nil { + structMap["ending_balance_in_cents"] = s.EndingBalanceInCents + } + if s.EntryType != nil { + structMap["entry_type"] = s.EntryType + } + if s.Memo != nil { + structMap["memo"] = s.Memo + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ServiceCredit. +// UnmarshalJSON implements the json.Unmarshaler interface for ServiceCredit. // It customizes the JSON unmarshaling process for ServiceCredit objects. func (s *ServiceCredit) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` - EntryType *ServiceCreditType `json:"entry_type,omitempty"` - Memo *string `json:"memo,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.AmountInCents = temp.AmountInCents - s.EndingBalanceInCents = temp.EndingBalanceInCents - s.EntryType = temp.EntryType - s.Memo = temp.Memo - return nil + var temp serviceCredit + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.AmountInCents = temp.AmountInCents + s.EndingBalanceInCents = temp.EndingBalanceInCents + s.EntryType = temp.EntryType + s.Memo = temp.Memo + return nil +} + +// TODO +type serviceCredit struct { + Id *int `json:"id,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` + EntryType *ServiceCreditType `json:"entry_type,omitempty"` + Memo *string `json:"memo,omitempty"` } diff --git a/models/service_credit_response.go b/models/service_credit_response.go index 22a9aecd..773f1105 100644 --- a/models/service_credit_response.go +++ b/models/service_credit_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // ServiceCreditResponse represents a ServiceCreditResponse struct. type ServiceCreditResponse struct { - ServiceCredit ServiceCredit `json:"service_credit"` + ServiceCredit ServiceCredit `json:"service_credit"` } -// MarshalJSON implements the json.Marshaler interface for ServiceCreditResponse. +// MarshalJSON implements the json.Marshaler interface for ServiceCreditResponse. // It customizes the JSON marshaling process for ServiceCreditResponse objects. func (s *ServiceCreditResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the ServiceCreditResponse object to a map representation for JSON marshaling. func (s *ServiceCreditResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["service_credit"] = s.ServiceCredit.toMap() - return structMap + structMap := make(map[string]any) + structMap["service_credit"] = s.ServiceCredit.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ServiceCreditResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for ServiceCreditResponse. // It customizes the JSON unmarshaling process for ServiceCreditResponse objects. func (s *ServiceCreditResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - ServiceCredit ServiceCredit `json:"service_credit"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.ServiceCredit = temp.ServiceCredit - return nil + var temp serviceCreditResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.ServiceCredit = *temp.ServiceCredit + return nil +} + +// TODO +type serviceCreditResponse struct { + ServiceCredit *ServiceCredit `json:"service_credit"` +} + +func (s *serviceCreditResponse) validate() error { + var errs []string + if s.ServiceCredit == nil { + errs = append(errs, "required field `service_credit` is missing for type `Service Credit Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/shipping_address.go b/models/shipping_address.go index 42e2a05d..bd46c582 100644 --- a/models/shipping_address.go +++ b/models/shipping_address.go @@ -1,72 +1,98 @@ package models import ( - "encoding/json" + "encoding/json" ) // ShippingAddress represents a ShippingAddress struct. type ShippingAddress struct { - Street Optional[string] `json:"street"` - Line2 Optional[string] `json:"line2"` - City Optional[string] `json:"city"` - State Optional[string] `json:"state"` - Zip Optional[string] `json:"zip"` - Country Optional[string] `json:"country"` + Street Optional[string] `json:"street"` + Line2 Optional[string] `json:"line2"` + City Optional[string] `json:"city"` + State Optional[string] `json:"state"` + Zip Optional[string] `json:"zip"` + Country Optional[string] `json:"country"` } -// MarshalJSON implements the json.Marshaler interface for ShippingAddress. +// MarshalJSON implements the json.Marshaler interface for ShippingAddress. // It customizes the JSON marshaling process for ShippingAddress objects. func (s *ShippingAddress) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the ShippingAddress object to a map representation for JSON marshaling. func (s *ShippingAddress) toMap() map[string]any { - structMap := make(map[string]any) - if s.Street.IsValueSet() { - structMap["street"] = s.Street.Value() - } - if s.Line2.IsValueSet() { - structMap["line2"] = s.Line2.Value() - } - if s.City.IsValueSet() { - structMap["city"] = s.City.Value() - } - if s.State.IsValueSet() { - structMap["state"] = s.State.Value() - } - if s.Zip.IsValueSet() { - structMap["zip"] = s.Zip.Value() - } - if s.Country.IsValueSet() { - structMap["country"] = s.Country.Value() - } - return structMap + structMap := make(map[string]any) + if s.Street.IsValueSet() { + if s.Street.Value() != nil { + structMap["street"] = s.Street.Value() + } else { + structMap["street"] = nil + } + } + if s.Line2.IsValueSet() { + if s.Line2.Value() != nil { + structMap["line2"] = s.Line2.Value() + } else { + structMap["line2"] = nil + } + } + if s.City.IsValueSet() { + if s.City.Value() != nil { + structMap["city"] = s.City.Value() + } else { + structMap["city"] = nil + } + } + if s.State.IsValueSet() { + if s.State.Value() != nil { + structMap["state"] = s.State.Value() + } else { + structMap["state"] = nil + } + } + if s.Zip.IsValueSet() { + if s.Zip.Value() != nil { + structMap["zip"] = s.Zip.Value() + } else { + structMap["zip"] = nil + } + } + if s.Country.IsValueSet() { + if s.Country.Value() != nil { + structMap["country"] = s.Country.Value() + } else { + structMap["country"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for ShippingAddress. +// UnmarshalJSON implements the json.Unmarshaler interface for ShippingAddress. // It customizes the JSON unmarshaling process for ShippingAddress objects. func (s *ShippingAddress) UnmarshalJSON(input []byte) error { - temp := &struct { - Street Optional[string] `json:"street"` - Line2 Optional[string] `json:"line2"` - City Optional[string] `json:"city"` - State Optional[string] `json:"state"` - Zip Optional[string] `json:"zip"` - Country Optional[string] `json:"country"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Street = temp.Street - s.Line2 = temp.Line2 - s.City = temp.City - s.State = temp.State - s.Zip = temp.Zip - s.Country = temp.Country - return nil + var temp shippingAddress + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Street = temp.Street + s.Line2 = temp.Line2 + s.City = temp.City + s.State = temp.State + s.Zip = temp.Zip + s.Country = temp.Country + return nil +} + +// TODO +type shippingAddress struct { + Street Optional[string] `json:"street"` + Line2 Optional[string] `json:"line2"` + City Optional[string] `json:"city"` + State Optional[string] `json:"state"` + Zip Optional[string] `json:"zip"` + Country Optional[string] `json:"country"` } diff --git a/models/signup_proforma_preview.go b/models/signup_proforma_preview.go index e68dd3a0..1209db03 100644 --- a/models/signup_proforma_preview.go +++ b/models/signup_proforma_preview.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // SignupProformaPreview represents a SignupProformaPreview struct. type SignupProformaPreview struct { - CurrentProformaInvoice *ProformaInvoice `json:"current_proforma_invoice,omitempty"` - NextProformaInvoice *ProformaInvoice `json:"next_proforma_invoice,omitempty"` + CurrentProformaInvoice *ProformaInvoice `json:"current_proforma_invoice,omitempty"` + NextProformaInvoice *ProformaInvoice `json:"next_proforma_invoice,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SignupProformaPreview. +// MarshalJSON implements the json.Marshaler interface for SignupProformaPreview. // It customizes the JSON marshaling process for SignupProformaPreview objects. func (s *SignupProformaPreview) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SignupProformaPreview object to a map representation for JSON marshaling. func (s *SignupProformaPreview) toMap() map[string]any { - structMap := make(map[string]any) - if s.CurrentProformaInvoice != nil { - structMap["current_proforma_invoice"] = s.CurrentProformaInvoice.toMap() - } - if s.NextProformaInvoice != nil { - structMap["next_proforma_invoice"] = s.NextProformaInvoice.toMap() - } - return structMap + structMap := make(map[string]any) + if s.CurrentProformaInvoice != nil { + structMap["current_proforma_invoice"] = s.CurrentProformaInvoice.toMap() + } + if s.NextProformaInvoice != nil { + structMap["next_proforma_invoice"] = s.NextProformaInvoice.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SignupProformaPreview. +// UnmarshalJSON implements the json.Unmarshaler interface for SignupProformaPreview. // It customizes the JSON unmarshaling process for SignupProformaPreview objects. func (s *SignupProformaPreview) UnmarshalJSON(input []byte) error { - temp := &struct { - CurrentProformaInvoice *ProformaInvoice `json:"current_proforma_invoice,omitempty"` - NextProformaInvoice *ProformaInvoice `json:"next_proforma_invoice,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.CurrentProformaInvoice = temp.CurrentProformaInvoice - s.NextProformaInvoice = temp.NextProformaInvoice - return nil + var temp signupProformaPreview + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.CurrentProformaInvoice = temp.CurrentProformaInvoice + s.NextProformaInvoice = temp.NextProformaInvoice + return nil +} + +// TODO +type signupProformaPreview struct { + CurrentProformaInvoice *ProformaInvoice `json:"current_proforma_invoice,omitempty"` + NextProformaInvoice *ProformaInvoice `json:"next_proforma_invoice,omitempty"` } diff --git a/models/signup_proforma_preview_response.go b/models/signup_proforma_preview_response.go index 7ebbb180..59734a9d 100644 --- a/models/signup_proforma_preview_response.go +++ b/models/signup_proforma_preview_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SignupProformaPreviewResponse represents a SignupProformaPreviewResponse struct. type SignupProformaPreviewResponse struct { - ProformaInvoicePreview SignupProformaPreview `json:"proforma_invoice_preview"` + ProformaInvoicePreview SignupProformaPreview `json:"proforma_invoice_preview"` } -// MarshalJSON implements the json.Marshaler interface for SignupProformaPreviewResponse. +// MarshalJSON implements the json.Marshaler interface for SignupProformaPreviewResponse. // It customizes the JSON marshaling process for SignupProformaPreviewResponse objects. func (s *SignupProformaPreviewResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SignupProformaPreviewResponse object to a map representation for JSON marshaling. func (s *SignupProformaPreviewResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["proforma_invoice_preview"] = s.ProformaInvoicePreview.toMap() - return structMap + structMap := make(map[string]any) + structMap["proforma_invoice_preview"] = s.ProformaInvoicePreview.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SignupProformaPreviewResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SignupProformaPreviewResponse. // It customizes the JSON unmarshaling process for SignupProformaPreviewResponse objects. func (s *SignupProformaPreviewResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - ProformaInvoicePreview SignupProformaPreview `json:"proforma_invoice_preview"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.ProformaInvoicePreview = temp.ProformaInvoicePreview - return nil + var temp signupProformaPreviewResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.ProformaInvoicePreview = *temp.ProformaInvoicePreview + return nil +} + +// TODO +type signupProformaPreviewResponse struct { + ProformaInvoicePreview *SignupProformaPreview `json:"proforma_invoice_preview"` +} + +func (s *signupProformaPreviewResponse) validate() error { + var errs []string + if s.ProformaInvoicePreview == nil { + errs = append(errs, "required field `proforma_invoice_preview` is missing for type `Signup Proforma Preview Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/site.go b/models/site.go index 5bcc7373..11d26bf4 100644 --- a/models/site.go +++ b/models/site.go @@ -1,132 +1,134 @@ package models import ( - "encoding/json" + "encoding/json" ) // Site represents a Site struct. type Site struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Subdomain *string `json:"subdomain,omitempty"` - Currency *string `json:"currency,omitempty"` - SellerId *int `json:"seller_id,omitempty"` - NonPrimaryCurrencies []string `json:"non_primary_currencies,omitempty"` - RelationshipInvoicingEnabled *bool `json:"relationship_invoicing_enabled,omitempty"` - CustomerHierarchyEnabled *bool `json:"customer_hierarchy_enabled,omitempty"` - WhopaysEnabled *bool `json:"whopays_enabled,omitempty"` - WhopaysDefaultPayer *string `json:"whopays_default_payer,omitempty"` - AllocationSettings *AllocationSettings `json:"allocation_settings,omitempty"` - DefaultPaymentCollectionMethod *string `json:"default_payment_collection_method,omitempty"` - OrganizationAddress *OrganizationAddress `json:"organization_address,omitempty"` - TaxConfiguration *TaxConfiguration `json:"tax_configuration,omitempty"` - NetTerms *NetTerms `json:"net_terms,omitempty"` - Test *bool `json:"test,omitempty"` + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Subdomain *string `json:"subdomain,omitempty"` + Currency *string `json:"currency,omitempty"` + SellerId *int `json:"seller_id,omitempty"` + NonPrimaryCurrencies []string `json:"non_primary_currencies,omitempty"` + RelationshipInvoicingEnabled *bool `json:"relationship_invoicing_enabled,omitempty"` + CustomerHierarchyEnabled *bool `json:"customer_hierarchy_enabled,omitempty"` + WhopaysEnabled *bool `json:"whopays_enabled,omitempty"` + WhopaysDefaultPayer *string `json:"whopays_default_payer,omitempty"` + AllocationSettings *AllocationSettings `json:"allocation_settings,omitempty"` + DefaultPaymentCollectionMethod *string `json:"default_payment_collection_method,omitempty"` + OrganizationAddress *OrganizationAddress `json:"organization_address,omitempty"` + TaxConfiguration *TaxConfiguration `json:"tax_configuration,omitempty"` + NetTerms *NetTerms `json:"net_terms,omitempty"` + Test *bool `json:"test,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Site. +// MarshalJSON implements the json.Marshaler interface for Site. // It customizes the JSON marshaling process for Site objects. func (s *Site) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the Site object to a map representation for JSON marshaling. func (s *Site) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.Name != nil { - structMap["name"] = s.Name - } - if s.Subdomain != nil { - structMap["subdomain"] = s.Subdomain - } - if s.Currency != nil { - structMap["currency"] = s.Currency - } - if s.SellerId != nil { - structMap["seller_id"] = s.SellerId - } - if s.NonPrimaryCurrencies != nil { - structMap["non_primary_currencies"] = s.NonPrimaryCurrencies - } - if s.RelationshipInvoicingEnabled != nil { - structMap["relationship_invoicing_enabled"] = s.RelationshipInvoicingEnabled - } - if s.CustomerHierarchyEnabled != nil { - structMap["customer_hierarchy_enabled"] = s.CustomerHierarchyEnabled - } - if s.WhopaysEnabled != nil { - structMap["whopays_enabled"] = s.WhopaysEnabled - } - if s.WhopaysDefaultPayer != nil { - structMap["whopays_default_payer"] = s.WhopaysDefaultPayer - } - if s.AllocationSettings != nil { - structMap["allocation_settings"] = s.AllocationSettings.toMap() - } - if s.DefaultPaymentCollectionMethod != nil { - structMap["default_payment_collection_method"] = s.DefaultPaymentCollectionMethod - } - if s.OrganizationAddress != nil { - structMap["organization_address"] = s.OrganizationAddress.toMap() - } - if s.TaxConfiguration != nil { - structMap["tax_configuration"] = s.TaxConfiguration.toMap() - } - if s.NetTerms != nil { - structMap["net_terms"] = s.NetTerms.toMap() - } - if s.Test != nil { - structMap["test"] = s.Test - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.Name != nil { + structMap["name"] = s.Name + } + if s.Subdomain != nil { + structMap["subdomain"] = s.Subdomain + } + if s.Currency != nil { + structMap["currency"] = s.Currency + } + if s.SellerId != nil { + structMap["seller_id"] = s.SellerId + } + if s.NonPrimaryCurrencies != nil { + structMap["non_primary_currencies"] = s.NonPrimaryCurrencies + } + if s.RelationshipInvoicingEnabled != nil { + structMap["relationship_invoicing_enabled"] = s.RelationshipInvoicingEnabled + } + if s.CustomerHierarchyEnabled != nil { + structMap["customer_hierarchy_enabled"] = s.CustomerHierarchyEnabled + } + if s.WhopaysEnabled != nil { + structMap["whopays_enabled"] = s.WhopaysEnabled + } + if s.WhopaysDefaultPayer != nil { + structMap["whopays_default_payer"] = s.WhopaysDefaultPayer + } + if s.AllocationSettings != nil { + structMap["allocation_settings"] = s.AllocationSettings.toMap() + } + if s.DefaultPaymentCollectionMethod != nil { + structMap["default_payment_collection_method"] = s.DefaultPaymentCollectionMethod + } + if s.OrganizationAddress != nil { + structMap["organization_address"] = s.OrganizationAddress.toMap() + } + if s.TaxConfiguration != nil { + structMap["tax_configuration"] = s.TaxConfiguration.toMap() + } + if s.NetTerms != nil { + structMap["net_terms"] = s.NetTerms.toMap() + } + if s.Test != nil { + structMap["test"] = s.Test + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Site. +// UnmarshalJSON implements the json.Unmarshaler interface for Site. // It customizes the JSON unmarshaling process for Site objects. func (s *Site) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Subdomain *string `json:"subdomain,omitempty"` - Currency *string `json:"currency,omitempty"` - SellerId *int `json:"seller_id,omitempty"` - NonPrimaryCurrencies []string `json:"non_primary_currencies,omitempty"` - RelationshipInvoicingEnabled *bool `json:"relationship_invoicing_enabled,omitempty"` - CustomerHierarchyEnabled *bool `json:"customer_hierarchy_enabled,omitempty"` - WhopaysEnabled *bool `json:"whopays_enabled,omitempty"` - WhopaysDefaultPayer *string `json:"whopays_default_payer,omitempty"` - AllocationSettings *AllocationSettings `json:"allocation_settings,omitempty"` - DefaultPaymentCollectionMethod *string `json:"default_payment_collection_method,omitempty"` - OrganizationAddress *OrganizationAddress `json:"organization_address,omitempty"` - TaxConfiguration *TaxConfiguration `json:"tax_configuration,omitempty"` - NetTerms *NetTerms `json:"net_terms,omitempty"` - Test *bool `json:"test,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.Name = temp.Name - s.Subdomain = temp.Subdomain - s.Currency = temp.Currency - s.SellerId = temp.SellerId - s.NonPrimaryCurrencies = temp.NonPrimaryCurrencies - s.RelationshipInvoicingEnabled = temp.RelationshipInvoicingEnabled - s.CustomerHierarchyEnabled = temp.CustomerHierarchyEnabled - s.WhopaysEnabled = temp.WhopaysEnabled - s.WhopaysDefaultPayer = temp.WhopaysDefaultPayer - s.AllocationSettings = temp.AllocationSettings - s.DefaultPaymentCollectionMethod = temp.DefaultPaymentCollectionMethod - s.OrganizationAddress = temp.OrganizationAddress - s.TaxConfiguration = temp.TaxConfiguration - s.NetTerms = temp.NetTerms - s.Test = temp.Test - return nil + var temp site + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.Name = temp.Name + s.Subdomain = temp.Subdomain + s.Currency = temp.Currency + s.SellerId = temp.SellerId + s.NonPrimaryCurrencies = temp.NonPrimaryCurrencies + s.RelationshipInvoicingEnabled = temp.RelationshipInvoicingEnabled + s.CustomerHierarchyEnabled = temp.CustomerHierarchyEnabled + s.WhopaysEnabled = temp.WhopaysEnabled + s.WhopaysDefaultPayer = temp.WhopaysDefaultPayer + s.AllocationSettings = temp.AllocationSettings + s.DefaultPaymentCollectionMethod = temp.DefaultPaymentCollectionMethod + s.OrganizationAddress = temp.OrganizationAddress + s.TaxConfiguration = temp.TaxConfiguration + s.NetTerms = temp.NetTerms + s.Test = temp.Test + return nil +} + +// TODO +type site struct { + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Subdomain *string `json:"subdomain,omitempty"` + Currency *string `json:"currency,omitempty"` + SellerId *int `json:"seller_id,omitempty"` + NonPrimaryCurrencies []string `json:"non_primary_currencies,omitempty"` + RelationshipInvoicingEnabled *bool `json:"relationship_invoicing_enabled,omitempty"` + CustomerHierarchyEnabled *bool `json:"customer_hierarchy_enabled,omitempty"` + WhopaysEnabled *bool `json:"whopays_enabled,omitempty"` + WhopaysDefaultPayer *string `json:"whopays_default_payer,omitempty"` + AllocationSettings *AllocationSettings `json:"allocation_settings,omitempty"` + DefaultPaymentCollectionMethod *string `json:"default_payment_collection_method,omitempty"` + OrganizationAddress *OrganizationAddress `json:"organization_address,omitempty"` + TaxConfiguration *TaxConfiguration `json:"tax_configuration,omitempty"` + NetTerms *NetTerms `json:"net_terms,omitempty"` + Test *bool `json:"test,omitempty"` } diff --git a/models/site_response.go b/models/site_response.go index e2203e28..fda5f553 100644 --- a/models/site_response.go +++ b/models/site_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SiteResponse represents a SiteResponse struct. type SiteResponse struct { - Site Site `json:"site"` + Site Site `json:"site"` } -// MarshalJSON implements the json.Marshaler interface for SiteResponse. +// MarshalJSON implements the json.Marshaler interface for SiteResponse. // It customizes the JSON marshaling process for SiteResponse objects. func (s *SiteResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SiteResponse object to a map representation for JSON marshaling. func (s *SiteResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["site"] = s.Site.toMap() - return structMap + structMap := make(map[string]any) + structMap["site"] = s.Site.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SiteResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SiteResponse. // It customizes the JSON unmarshaling process for SiteResponse objects. func (s *SiteResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Site Site `json:"site"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Site = temp.Site - return nil + var temp siteResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.Site = *temp.Site + return nil +} + +// TODO +type siteResponse struct { + Site *Site `json:"site"` +} + +func (s *siteResponse) validate() error { + var errs []string + if s.Site == nil { + errs = append(errs, "required field `site` is missing for type `Site Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/site_statistics.go b/models/site_statistics.go index 2e5c45a0..9a6dac1e 100644 --- a/models/site_statistics.go +++ b/models/site_statistics.go @@ -1,102 +1,104 @@ package models import ( - "encoding/json" + "encoding/json" ) // SiteStatistics represents a SiteStatistics struct. type SiteStatistics struct { - TotalSubscriptions *int `json:"total_subscriptions,omitempty"` - SubscriptionsToday *int `json:"subscriptions_today,omitempty"` - TotalRevenue *string `json:"total_revenue,omitempty"` - RevenueToday *string `json:"revenue_today,omitempty"` - RevenueThisMonth *string `json:"revenue_this_month,omitempty"` - RevenueThisYear *string `json:"revenue_this_year,omitempty"` - TotalCanceledSubscriptions *int `json:"total_canceled_subscriptions,omitempty"` - TotalActiveSubscriptions *int `json:"total_active_subscriptions,omitempty"` - TotalPastDueSubscriptions *int `json:"total_past_due_subscriptions,omitempty"` - TotalUnpaidSubscriptions *int `json:"total_unpaid_subscriptions,omitempty"` - TotalDunningSubscriptions *int `json:"total_dunning_subscriptions,omitempty"` + TotalSubscriptions *int `json:"total_subscriptions,omitempty"` + SubscriptionsToday *int `json:"subscriptions_today,omitempty"` + TotalRevenue *string `json:"total_revenue,omitempty"` + RevenueToday *string `json:"revenue_today,omitempty"` + RevenueThisMonth *string `json:"revenue_this_month,omitempty"` + RevenueThisYear *string `json:"revenue_this_year,omitempty"` + TotalCanceledSubscriptions *int `json:"total_canceled_subscriptions,omitempty"` + TotalActiveSubscriptions *int `json:"total_active_subscriptions,omitempty"` + TotalPastDueSubscriptions *int `json:"total_past_due_subscriptions,omitempty"` + TotalUnpaidSubscriptions *int `json:"total_unpaid_subscriptions,omitempty"` + TotalDunningSubscriptions *int `json:"total_dunning_subscriptions,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SiteStatistics. +// MarshalJSON implements the json.Marshaler interface for SiteStatistics. // It customizes the JSON marshaling process for SiteStatistics objects. func (s *SiteStatistics) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SiteStatistics object to a map representation for JSON marshaling. func (s *SiteStatistics) toMap() map[string]any { - structMap := make(map[string]any) - if s.TotalSubscriptions != nil { - structMap["total_subscriptions"] = s.TotalSubscriptions - } - if s.SubscriptionsToday != nil { - structMap["subscriptions_today"] = s.SubscriptionsToday - } - if s.TotalRevenue != nil { - structMap["total_revenue"] = s.TotalRevenue - } - if s.RevenueToday != nil { - structMap["revenue_today"] = s.RevenueToday - } - if s.RevenueThisMonth != nil { - structMap["revenue_this_month"] = s.RevenueThisMonth - } - if s.RevenueThisYear != nil { - structMap["revenue_this_year"] = s.RevenueThisYear - } - if s.TotalCanceledSubscriptions != nil { - structMap["total_canceled_subscriptions"] = s.TotalCanceledSubscriptions - } - if s.TotalActiveSubscriptions != nil { - structMap["total_active_subscriptions"] = s.TotalActiveSubscriptions - } - if s.TotalPastDueSubscriptions != nil { - structMap["total_past_due_subscriptions"] = s.TotalPastDueSubscriptions - } - if s.TotalUnpaidSubscriptions != nil { - structMap["total_unpaid_subscriptions"] = s.TotalUnpaidSubscriptions - } - if s.TotalDunningSubscriptions != nil { - structMap["total_dunning_subscriptions"] = s.TotalDunningSubscriptions - } - return structMap + structMap := make(map[string]any) + if s.TotalSubscriptions != nil { + structMap["total_subscriptions"] = s.TotalSubscriptions + } + if s.SubscriptionsToday != nil { + structMap["subscriptions_today"] = s.SubscriptionsToday + } + if s.TotalRevenue != nil { + structMap["total_revenue"] = s.TotalRevenue + } + if s.RevenueToday != nil { + structMap["revenue_today"] = s.RevenueToday + } + if s.RevenueThisMonth != nil { + structMap["revenue_this_month"] = s.RevenueThisMonth + } + if s.RevenueThisYear != nil { + structMap["revenue_this_year"] = s.RevenueThisYear + } + if s.TotalCanceledSubscriptions != nil { + structMap["total_canceled_subscriptions"] = s.TotalCanceledSubscriptions + } + if s.TotalActiveSubscriptions != nil { + structMap["total_active_subscriptions"] = s.TotalActiveSubscriptions + } + if s.TotalPastDueSubscriptions != nil { + structMap["total_past_due_subscriptions"] = s.TotalPastDueSubscriptions + } + if s.TotalUnpaidSubscriptions != nil { + structMap["total_unpaid_subscriptions"] = s.TotalUnpaidSubscriptions + } + if s.TotalDunningSubscriptions != nil { + structMap["total_dunning_subscriptions"] = s.TotalDunningSubscriptions + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SiteStatistics. +// UnmarshalJSON implements the json.Unmarshaler interface for SiteStatistics. // It customizes the JSON unmarshaling process for SiteStatistics objects. func (s *SiteStatistics) UnmarshalJSON(input []byte) error { - temp := &struct { - TotalSubscriptions *int `json:"total_subscriptions,omitempty"` - SubscriptionsToday *int `json:"subscriptions_today,omitempty"` - TotalRevenue *string `json:"total_revenue,omitempty"` - RevenueToday *string `json:"revenue_today,omitempty"` - RevenueThisMonth *string `json:"revenue_this_month,omitempty"` - RevenueThisYear *string `json:"revenue_this_year,omitempty"` - TotalCanceledSubscriptions *int `json:"total_canceled_subscriptions,omitempty"` - TotalActiveSubscriptions *int `json:"total_active_subscriptions,omitempty"` - TotalPastDueSubscriptions *int `json:"total_past_due_subscriptions,omitempty"` - TotalUnpaidSubscriptions *int `json:"total_unpaid_subscriptions,omitempty"` - TotalDunningSubscriptions *int `json:"total_dunning_subscriptions,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.TotalSubscriptions = temp.TotalSubscriptions - s.SubscriptionsToday = temp.SubscriptionsToday - s.TotalRevenue = temp.TotalRevenue - s.RevenueToday = temp.RevenueToday - s.RevenueThisMonth = temp.RevenueThisMonth - s.RevenueThisYear = temp.RevenueThisYear - s.TotalCanceledSubscriptions = temp.TotalCanceledSubscriptions - s.TotalActiveSubscriptions = temp.TotalActiveSubscriptions - s.TotalPastDueSubscriptions = temp.TotalPastDueSubscriptions - s.TotalUnpaidSubscriptions = temp.TotalUnpaidSubscriptions - s.TotalDunningSubscriptions = temp.TotalDunningSubscriptions - return nil + var temp siteStatistics + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.TotalSubscriptions = temp.TotalSubscriptions + s.SubscriptionsToday = temp.SubscriptionsToday + s.TotalRevenue = temp.TotalRevenue + s.RevenueToday = temp.RevenueToday + s.RevenueThisMonth = temp.RevenueThisMonth + s.RevenueThisYear = temp.RevenueThisYear + s.TotalCanceledSubscriptions = temp.TotalCanceledSubscriptions + s.TotalActiveSubscriptions = temp.TotalActiveSubscriptions + s.TotalPastDueSubscriptions = temp.TotalPastDueSubscriptions + s.TotalUnpaidSubscriptions = temp.TotalUnpaidSubscriptions + s.TotalDunningSubscriptions = temp.TotalDunningSubscriptions + return nil +} + +// TODO +type siteStatistics struct { + TotalSubscriptions *int `json:"total_subscriptions,omitempty"` + SubscriptionsToday *int `json:"subscriptions_today,omitempty"` + TotalRevenue *string `json:"total_revenue,omitempty"` + RevenueToday *string `json:"revenue_today,omitempty"` + RevenueThisMonth *string `json:"revenue_this_month,omitempty"` + RevenueThisYear *string `json:"revenue_this_year,omitempty"` + TotalCanceledSubscriptions *int `json:"total_canceled_subscriptions,omitempty"` + TotalActiveSubscriptions *int `json:"total_active_subscriptions,omitempty"` + TotalPastDueSubscriptions *int `json:"total_past_due_subscriptions,omitempty"` + TotalUnpaidSubscriptions *int `json:"total_unpaid_subscriptions,omitempty"` + TotalDunningSubscriptions *int `json:"total_dunning_subscriptions,omitempty"` } diff --git a/models/site_summary.go b/models/site_summary.go index 2284f484..737371b3 100644 --- a/models/site_summary.go +++ b/models/site_summary.go @@ -1,66 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" ) // SiteSummary represents a SiteSummary struct. type SiteSummary struct { - SellerName *string `json:"seller_name,omitempty"` - SiteName *string `json:"site_name,omitempty"` - SiteId *int `json:"site_id,omitempty"` - SiteCurrency *string `json:"site_currency,omitempty"` - Stats *SiteStatistics `json:"stats,omitempty"` + SellerName *string `json:"seller_name,omitempty"` + SiteName *string `json:"site_name,omitempty"` + SiteId *int `json:"site_id,omitempty"` + SiteCurrency *string `json:"site_currency,omitempty"` + Stats *SiteStatistics `json:"stats,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SiteSummary. +// MarshalJSON implements the json.Marshaler interface for SiteSummary. // It customizes the JSON marshaling process for SiteSummary objects. func (s *SiteSummary) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SiteSummary object to a map representation for JSON marshaling. func (s *SiteSummary) toMap() map[string]any { - structMap := make(map[string]any) - if s.SellerName != nil { - structMap["seller_name"] = s.SellerName - } - if s.SiteName != nil { - structMap["site_name"] = s.SiteName - } - if s.SiteId != nil { - structMap["site_id"] = s.SiteId - } - if s.SiteCurrency != nil { - structMap["site_currency"] = s.SiteCurrency - } - if s.Stats != nil { - structMap["stats"] = s.Stats.toMap() - } - return structMap + structMap := make(map[string]any) + if s.SellerName != nil { + structMap["seller_name"] = s.SellerName + } + if s.SiteName != nil { + structMap["site_name"] = s.SiteName + } + if s.SiteId != nil { + structMap["site_id"] = s.SiteId + } + if s.SiteCurrency != nil { + structMap["site_currency"] = s.SiteCurrency + } + if s.Stats != nil { + structMap["stats"] = s.Stats.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SiteSummary. +// UnmarshalJSON implements the json.Unmarshaler interface for SiteSummary. // It customizes the JSON unmarshaling process for SiteSummary objects. func (s *SiteSummary) UnmarshalJSON(input []byte) error { - temp := &struct { - SellerName *string `json:"seller_name,omitempty"` - SiteName *string `json:"site_name,omitempty"` - SiteId *int `json:"site_id,omitempty"` - SiteCurrency *string `json:"site_currency,omitempty"` - Stats *SiteStatistics `json:"stats,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.SellerName = temp.SellerName - s.SiteName = temp.SiteName - s.SiteId = temp.SiteId - s.SiteCurrency = temp.SiteCurrency - s.Stats = temp.Stats - return nil + var temp siteSummary + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.SellerName = temp.SellerName + s.SiteName = temp.SiteName + s.SiteId = temp.SiteId + s.SiteCurrency = temp.SiteCurrency + s.Stats = temp.Stats + return nil +} + +// TODO +type siteSummary struct { + SellerName *string `json:"seller_name,omitempty"` + SiteName *string `json:"site_name,omitempty"` + SiteId *int `json:"site_id,omitempty"` + SiteCurrency *string `json:"site_currency,omitempty"` + Stats *SiteStatistics `json:"stats,omitempty"` } diff --git a/models/subscription.go b/models/subscription.go index 05a7ff1d..649e6247 100644 --- a/models/subscription.go +++ b/models/subscription.go @@ -1,615 +1,737 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Subscription represents a Subscription struct. type Subscription struct { - // The subscription unique id within Chargify. - Id *int `json:"id,omitempty"` - // The state of a subscription. - // * **Live States** - // * `active` - A normal, active subscription. It is not in a trial and is paid and up to date. - // * `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed. - // * `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed. - // * `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state. - // * `paused` - An internal state that indicates that your account with Advanced Billing is in arrears. - // * **Problem States** - // * `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers. - // * `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed. - // * `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`. - // * **End of Life States** - // * `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription. - // While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance. - // * `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period. - // * `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.) - // * `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time. - // * `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state. - // * `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details. - // See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. - State *SubscriptionState `json:"state,omitempty"` - // Gives the current outstanding subscription balance in the number of cents. - BalanceInCents *int64 `json:"balance_in_cents,omitempty"` - // Gives the total revenue from the subscription in the number of cents. - TotalRevenueInCents *int64 `json:"total_revenue_in_cents,omitempty"` - // (Added Nov 5 2013) The recurring amount of the product (and version),currently subscribed. NOTE: this may differ from the current price of,the product, if you’ve changed the price of the product but haven’t,moved this subscription to a newer version. - ProductPriceInCents *int64 `json:"product_price_in_cents,omitempty"` - // The version of the product for the subscription. Note that this is a deprecated field kept for backwards-compatibility. - ProductVersionNumber *int `json:"product_version_number,omitempty"` - // Timestamp relating to the end of the current (recurring) period (i.e.,when the next regularly scheduled attempted charge will occur) - CurrentPeriodEndsAt *time.Time `json:"current_period_ends_at,omitempty"` - // Timestamp that indicates when capture of payment will be tried or,retried. This value will usually track the current_period_ends_at, but,will diverge if a renewal payment fails and must be retried. In that,case, the current_period_ends_at will advance to the end of the next,period (time doesn’t stop because a payment was missed) but the,next_assessment_at will be scheduled for the auto-retry time (i.e. 24,hours in the future, in some cases) - NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` - // Timestamp for when the trial period (if any) began - TrialStartedAt Optional[time.Time] `json:"trial_started_at"` - // Timestamp for when the trial period (if any) ended - TrialEndedAt Optional[time.Time] `json:"trial_ended_at"` - // Timestamp for when the subscription began (i.e. when it came out of trial, or when it began in the case of no trial) - ActivatedAt *time.Time `json:"activated_at,omitempty"` - // Timestamp giving the expiration date of this subscription (if any) - ExpiresAt Optional[time.Time] `json:"expires_at"` - // The creation date for this subscription - CreatedAt *time.Time `json:"created_at,omitempty"` - // The date of last update for this subscription - UpdatedAt *time.Time `json:"updated_at,omitempty"` - // Seller-provided reason for, or note about, the cancellation. - CancellationMessage Optional[string] `json:"cancellation_message"` - // The process used to cancel the subscription, if the subscription has been canceled. It is nil if the subscription's state is not canceled. - CancellationMethod Optional[CancellationMethod] `json:"cancellation_method"` - // Whether or not the subscription will (or has) canceled at the end of the period. - CancelAtEndOfPeriod Optional[bool] `json:"cancel_at_end_of_period"` - // The timestamp of the most recent cancellation - CanceledAt Optional[time.Time] `json:"canceled_at"` - // Timestamp relating to the start of the current (recurring) period - CurrentPeriodStartedAt *time.Time `json:"current_period_started_at,omitempty"` - // Only valid for webhook payloads The previous state for webhooks that have indicated a change in state. For normal API calls, this will always be the same as the state (current state) - PreviousState *SubscriptionState `json:"previous_state,omitempty"` - // The ID of the transaction that generated the revenue - SignupPaymentId *int `json:"signup_payment_id,omitempty"` - // The revenue, formatted as a string of decimal separated dollars and,cents, from the subscription signup ($50.00 would be formatted as,50.00) - SignupRevenue *string `json:"signup_revenue,omitempty"` - // Timestamp for when the subscription is currently set to cancel. - DelayedCancelAt Optional[time.Time] `json:"delayed_cancel_at"` - // (deprecated) The coupon code of the single coupon currently applied to the subscription. See coupon_codes instead as subscriptions can now have more than one coupon. - CouponCode Optional[string] `json:"coupon_code"` // Deprecated - // The day of the month that the subscription will charge according to calendar billing rules, if used. - SnapDay Optional[string] `json:"snap_day"` - // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. - PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` - Customer *Customer `json:"customer,omitempty"` - Product *Product `json:"product,omitempty"` - CreditCard *CreditCardPaymentProfile `json:"credit_card,omitempty"` - Group Optional[NestedSubscriptionGroup] `json:"group"` - BankAccount *BankAccountPaymentProfile `json:"bank_account,omitempty"` - // The payment profile type for the active profile on file. - PaymentType Optional[string] `json:"payment_type"` - // The subscription's unique code that can be given to referrals. - ReferralCode Optional[string] `json:"referral_code"` - // If a delayed product change is scheduled, the ID of the product that the subscription will be changed to at the next renewal. - NextProductId Optional[int] `json:"next_product_id"` - // If a delayed product change is scheduled, the handle of the product that the subscription will be changed to at the next renewal. - NextProductHandle Optional[string] `json:"next_product_handle"` - // (deprecated) How many times the subscription's single coupon has been used. This field has no replacement for multiple coupons. - CouponUseCount Optional[int] `json:"coupon_use_count"` // Deprecated - // (deprecated) How many times the subscription's single coupon may be used. This field has no replacement for multiple coupons. - CouponUsesAllowed Optional[int] `json:"coupon_uses_allowed"` // Deprecated - // If the subscription is canceled, this is their churn code. - ReasonCode Optional[string] `json:"reason_code"` - // The date the subscription is scheduled to automatically resume from the on_hold state. - AutomaticallyResumeAt Optional[time.Time] `json:"automatically_resume_at"` - // An array for all the coupons attached to the subscription. - CouponCodes []string `json:"coupon_codes,omitempty"` - // The ID of the offer associated with the subscription. - OfferId Optional[int] `json:"offer_id"` - // On Relationship Invoicing, the ID of the individual paying for the subscription. Defaults to the Customer ID unless the 'Customer Hierarchies & WhoPays' feature is enabled. - PayerId Optional[int] `json:"payer_id"` - // The balance in cents plus the estimated renewal amount in cents. - CurrentBillingAmountInCents *int64 `json:"current_billing_amount_in_cents,omitempty"` - // The product price point currently subscribed to. - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - // Price point type. We expose the following types: - // 1. **default**: a price point that is marked as a default price for a certain product. - // 2. **custom**: a custom price point. - // 3. **catalog**: a price point that is **not** marked as a default price for a certain product and is **not** a custom one. - ProductPricePointType *PricePointType `json:"product_price_point_type,omitempty"` - // If a delayed product change is scheduled, the ID of the product price point that the subscription will be changed to at the next renewal. - NextProductPricePointId Optional[int] `json:"next_product_price_point_id"` - // On Relationship Invoicing, the number of days before a renewal invoice is due. - NetTerms Optional[int] `json:"net_terms"` - // For European sites subject to PSD2 and using 3D Secure, this can be used to reference a previous transaction for the customer. This will ensure the card will be charged successfully at renewal. - StoredCredentialTransactionId Optional[int] `json:"stored_credential_transaction_id"` - // The reference value (provided by your app) for the subscription itelf. - Reference Optional[string] `json:"reference"` - // The timestamp of the most recent on hold action. - OnHoldAt Optional[time.Time] `json:"on_hold_at"` - // Boolean representing whether the subscription is prepaid and currently in dunning. Only returned for Relationship Invoicing sites with the feature enabled - PrepaidDunning *bool `json:"prepaid_dunning,omitempty"` - // Additional coupon data. To use this data you also have to include the following param in the request`include[]=coupons`. - // Only in Read Subscription Endpoint. - Coupons []SubscriptionIncludedCoupon `json:"coupons,omitempty"` - // Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute. - DunningCommunicationDelayEnabled *bool `json:"dunning_communication_delay_enabled,omitempty"` - // Time zone for the Dunning Communication Delay feature. - DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` - ReceivesInvoiceEmails Optional[bool] `json:"receives_invoice_emails"` - Locale Optional[string] `json:"locale"` - Currency *string `json:"currency,omitempty"` - ScheduledCancellationAt Optional[time.Time] `json:"scheduled_cancellation_at"` - CreditBalanceInCents *int64 `json:"credit_balance_in_cents,omitempty"` - PrepaymentBalanceInCents *int64 `json:"prepayment_balance_in_cents,omitempty"` - PrepaidConfiguration *PrepaidConfiguration `json:"prepaid_configuration,omitempty"` - // Returned only for list/read Subscription operation when `include[]=self_service_page_token` parameter is provided. - SelfServicePageToken *string `json:"self_service_page_token,omitempty"` + // The subscription unique id within Chargify. + Id *int `json:"id,omitempty"` + // The state of a subscription. + // * **Live States** + // * `active` - A normal, active subscription. It is not in a trial and is paid and up to date. + // * `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed. + // * `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed. + // * `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state. + // * `paused` - An internal state that indicates that your account with Advanced Billing is in arrears. + // * **Problem States** + // * `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers. + // * `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed. + // * `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`. + // * **End of Life States** + // * `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription. + // While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance. + // * `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period. + // * `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.) + // * `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time. + // * `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state. + // * `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details. + // See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. + State *SubscriptionState `json:"state,omitempty"` + // Gives the current outstanding subscription balance in the number of cents. + BalanceInCents *int64 `json:"balance_in_cents,omitempty"` + // Gives the total revenue from the subscription in the number of cents. + TotalRevenueInCents *int64 `json:"total_revenue_in_cents,omitempty"` + // (Added Nov 5 2013) The recurring amount of the product (and version),currently subscribed. NOTE: this may differ from the current price of,the product, if you’ve changed the price of the product but haven’t,moved this subscription to a newer version. + ProductPriceInCents *int64 `json:"product_price_in_cents,omitempty"` + // The version of the product for the subscription. Note that this is a deprecated field kept for backwards-compatibility. + ProductVersionNumber *int `json:"product_version_number,omitempty"` + // Timestamp relating to the end of the current (recurring) period (i.e.,when the next regularly scheduled attempted charge will occur) + CurrentPeriodEndsAt *time.Time `json:"current_period_ends_at,omitempty"` + // Timestamp that indicates when capture of payment will be tried or,retried. This value will usually track the current_period_ends_at, but,will diverge if a renewal payment fails and must be retried. In that,case, the current_period_ends_at will advance to the end of the next,period (time doesn’t stop because a payment was missed) but the,next_assessment_at will be scheduled for the auto-retry time (i.e. 24,hours in the future, in some cases) + NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` + // Timestamp for when the trial period (if any) began + TrialStartedAt Optional[time.Time] `json:"trial_started_at"` + // Timestamp for when the trial period (if any) ended + TrialEndedAt Optional[time.Time] `json:"trial_ended_at"` + // Timestamp for when the subscription began (i.e. when it came out of trial, or when it began in the case of no trial) + ActivatedAt *time.Time `json:"activated_at,omitempty"` + // Timestamp giving the expiration date of this subscription (if any) + ExpiresAt Optional[time.Time] `json:"expires_at"` + // The creation date for this subscription + CreatedAt *time.Time `json:"created_at,omitempty"` + // The date of last update for this subscription + UpdatedAt *time.Time `json:"updated_at,omitempty"` + // Seller-provided reason for, or note about, the cancellation. + CancellationMessage Optional[string] `json:"cancellation_message"` + // The process used to cancel the subscription, if the subscription has been canceled. It is nil if the subscription's state is not canceled. + CancellationMethod Optional[CancellationMethod] `json:"cancellation_method"` + // Whether or not the subscription will (or has) canceled at the end of the period. + CancelAtEndOfPeriod Optional[bool] `json:"cancel_at_end_of_period"` + // The timestamp of the most recent cancellation + CanceledAt Optional[time.Time] `json:"canceled_at"` + // Timestamp relating to the start of the current (recurring) period + CurrentPeriodStartedAt *time.Time `json:"current_period_started_at,omitempty"` + // Only valid for webhook payloads The previous state for webhooks that have indicated a change in state. For normal API calls, this will always be the same as the state (current state) + PreviousState *SubscriptionState `json:"previous_state,omitempty"` + // The ID of the transaction that generated the revenue + SignupPaymentId *int `json:"signup_payment_id,omitempty"` + // The revenue, formatted as a string of decimal separated dollars and,cents, from the subscription signup ($50.00 would be formatted as,50.00) + SignupRevenue *string `json:"signup_revenue,omitempty"` + // Timestamp for when the subscription is currently set to cancel. + DelayedCancelAt Optional[time.Time] `json:"delayed_cancel_at"` + // (deprecated) The coupon code of the single coupon currently applied to the subscription. See coupon_codes instead as subscriptions can now have more than one coupon. + CouponCode Optional[string] `json:"coupon_code"` // Deprecated + // The day of the month that the subscription will charge according to calendar billing rules, if used. + SnapDay Optional[string] `json:"snap_day"` + // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` + Customer *Customer `json:"customer,omitempty"` + Product *Product `json:"product,omitempty"` + CreditCard *CreditCardPaymentProfile `json:"credit_card,omitempty"` + Group Optional[SubscriptionGroup2] `json:"group"` + BankAccount *BankAccountPaymentProfile `json:"bank_account,omitempty"` + // The payment profile type for the active profile on file. + PaymentType Optional[string] `json:"payment_type"` + // The subscription's unique code that can be given to referrals. + ReferralCode Optional[string] `json:"referral_code"` + // If a delayed product change is scheduled, the ID of the product that the subscription will be changed to at the next renewal. + NextProductId Optional[int] `json:"next_product_id"` + // If a delayed product change is scheduled, the handle of the product that the subscription will be changed to at the next renewal. + NextProductHandle Optional[string] `json:"next_product_handle"` + // (deprecated) How many times the subscription's single coupon has been used. This field has no replacement for multiple coupons. + CouponUseCount Optional[int] `json:"coupon_use_count"` // Deprecated + // (deprecated) How many times the subscription's single coupon may be used. This field has no replacement for multiple coupons. + CouponUsesAllowed Optional[int] `json:"coupon_uses_allowed"` // Deprecated + // If the subscription is canceled, this is their churn code. + ReasonCode Optional[string] `json:"reason_code"` + // The date the subscription is scheduled to automatically resume from the on_hold state. + AutomaticallyResumeAt Optional[time.Time] `json:"automatically_resume_at"` + // An array for all the coupons attached to the subscription. + CouponCodes []string `json:"coupon_codes,omitempty"` + // The ID of the offer associated with the subscription. + OfferId Optional[int] `json:"offer_id"` + // On Relationship Invoicing, the ID of the individual paying for the subscription. Defaults to the Customer ID unless the 'Customer Hierarchies & WhoPays' feature is enabled. + PayerId Optional[int] `json:"payer_id"` + // The balance in cents plus the estimated renewal amount in cents. + CurrentBillingAmountInCents *int64 `json:"current_billing_amount_in_cents,omitempty"` + // The product price point currently subscribed to. + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + // Price point type. We expose the following types: + // 1. **default**: a price point that is marked as a default price for a certain product. + // 2. **custom**: a custom price point. + // 3. **catalog**: a price point that is **not** marked as a default price for a certain product and is **not** a custom one. + ProductPricePointType *PricePointType `json:"product_price_point_type,omitempty"` + // If a delayed product change is scheduled, the ID of the product price point that the subscription will be changed to at the next renewal. + NextProductPricePointId Optional[int] `json:"next_product_price_point_id"` + // On Relationship Invoicing, the number of days before a renewal invoice is due. + NetTerms Optional[int] `json:"net_terms"` + // For European sites subject to PSD2 and using 3D Secure, this can be used to reference a previous transaction for the customer. This will ensure the card will be charged successfully at renewal. + StoredCredentialTransactionId Optional[int] `json:"stored_credential_transaction_id"` + // The reference value (provided by your app) for the subscription itelf. + Reference Optional[string] `json:"reference"` + // The timestamp of the most recent on hold action. + OnHoldAt Optional[time.Time] `json:"on_hold_at"` + // Boolean representing whether the subscription is prepaid and currently in dunning. Only returned for Relationship Invoicing sites with the feature enabled + PrepaidDunning *bool `json:"prepaid_dunning,omitempty"` + // Additional coupon data. To use this data you also have to include the following param in the request`include[]=coupons`. + // Only in Read Subscription Endpoint. + Coupons []SubscriptionIncludedCoupon `json:"coupons,omitempty"` + // Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute. + DunningCommunicationDelayEnabled *bool `json:"dunning_communication_delay_enabled,omitempty"` + // Time zone for the Dunning Communication Delay feature. + DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` + ReceivesInvoiceEmails Optional[bool] `json:"receives_invoice_emails"` + Locale Optional[string] `json:"locale"` + Currency *string `json:"currency,omitempty"` + ScheduledCancellationAt Optional[time.Time] `json:"scheduled_cancellation_at"` + CreditBalanceInCents *int64 `json:"credit_balance_in_cents,omitempty"` + PrepaymentBalanceInCents *int64 `json:"prepayment_balance_in_cents,omitempty"` + PrepaidConfiguration *PrepaidConfiguration `json:"prepaid_configuration,omitempty"` + // Returned only for list/read Subscription operation when `include[]=self_service_page_token` parameter is provided. + SelfServicePageToken *string `json:"self_service_page_token,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Subscription. +// MarshalJSON implements the json.Marshaler interface for Subscription. // It customizes the JSON marshaling process for Subscription objects. func (s *Subscription) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the Subscription object to a map representation for JSON marshaling. func (s *Subscription) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.State != nil { - structMap["state"] = s.State - } - if s.BalanceInCents != nil { - structMap["balance_in_cents"] = s.BalanceInCents - } - if s.TotalRevenueInCents != nil { - structMap["total_revenue_in_cents"] = s.TotalRevenueInCents - } - if s.ProductPriceInCents != nil { - structMap["product_price_in_cents"] = s.ProductPriceInCents - } - if s.ProductVersionNumber != nil { - structMap["product_version_number"] = s.ProductVersionNumber - } - if s.CurrentPeriodEndsAt != nil { - structMap["current_period_ends_at"] = s.CurrentPeriodEndsAt.Format(time.RFC3339) - } - if s.NextAssessmentAt != nil { - structMap["next_assessment_at"] = s.NextAssessmentAt.Format(time.RFC3339) - } - if s.TrialStartedAt.IsValueSet() { - var TrialStartedAtVal *string = nil - if s.TrialStartedAt.Value() != nil { - val := s.TrialStartedAt.Value().Format(time.RFC3339) - TrialStartedAtVal = &val - } - structMap["trial_started_at"] = TrialStartedAtVal - } - if s.TrialEndedAt.IsValueSet() { - var TrialEndedAtVal *string = nil - if s.TrialEndedAt.Value() != nil { - val := s.TrialEndedAt.Value().Format(time.RFC3339) - TrialEndedAtVal = &val - } - structMap["trial_ended_at"] = TrialEndedAtVal - } - if s.ActivatedAt != nil { - structMap["activated_at"] = s.ActivatedAt.Format(time.RFC3339) - } - if s.ExpiresAt.IsValueSet() { - var ExpiresAtVal *string = nil - if s.ExpiresAt.Value() != nil { - val := s.ExpiresAt.Value().Format(time.RFC3339) - ExpiresAtVal = &val - } - structMap["expires_at"] = ExpiresAtVal - } - if s.CreatedAt != nil { - structMap["created_at"] = s.CreatedAt.Format(time.RFC3339) - } - if s.UpdatedAt != nil { - structMap["updated_at"] = s.UpdatedAt.Format(time.RFC3339) - } - if s.CancellationMessage.IsValueSet() { - structMap["cancellation_message"] = s.CancellationMessage.Value() - } - if s.CancellationMethod.IsValueSet() { - structMap["cancellation_method"] = s.CancellationMethod.Value() - } - if s.CancelAtEndOfPeriod.IsValueSet() { - structMap["cancel_at_end_of_period"] = s.CancelAtEndOfPeriod.Value() - } - if s.CanceledAt.IsValueSet() { - var CanceledAtVal *string = nil - if s.CanceledAt.Value() != nil { - val := s.CanceledAt.Value().Format(time.RFC3339) - CanceledAtVal = &val - } - structMap["canceled_at"] = CanceledAtVal - } - if s.CurrentPeriodStartedAt != nil { - structMap["current_period_started_at"] = s.CurrentPeriodStartedAt.Format(time.RFC3339) - } - if s.PreviousState != nil { - structMap["previous_state"] = s.PreviousState - } - if s.SignupPaymentId != nil { - structMap["signup_payment_id"] = s.SignupPaymentId - } - if s.SignupRevenue != nil { - structMap["signup_revenue"] = s.SignupRevenue - } - if s.DelayedCancelAt.IsValueSet() { - var DelayedCancelAtVal *string = nil - if s.DelayedCancelAt.Value() != nil { - val := s.DelayedCancelAt.Value().Format(time.RFC3339) - DelayedCancelAtVal = &val - } - structMap["delayed_cancel_at"] = DelayedCancelAtVal - } - if s.CouponCode.IsValueSet() { - structMap["coupon_code"] = s.CouponCode.Value() - } - if s.SnapDay.IsValueSet() { - structMap["snap_day"] = s.SnapDay.Value() - } - if s.PaymentCollectionMethod != nil { - structMap["payment_collection_method"] = s.PaymentCollectionMethod - } - if s.Customer != nil { - structMap["customer"] = s.Customer.toMap() - } - if s.Product != nil { - structMap["product"] = s.Product.toMap() - } - if s.CreditCard != nil { - structMap["credit_card"] = s.CreditCard.toMap() - } - if s.Group.IsValueSet() { - structMap["group"] = s.Group.Value() - } - if s.BankAccount != nil { - structMap["bank_account"] = s.BankAccount.toMap() - } - if s.PaymentType.IsValueSet() { - structMap["payment_type"] = s.PaymentType.Value() - } - if s.ReferralCode.IsValueSet() { - structMap["referral_code"] = s.ReferralCode.Value() - } - if s.NextProductId.IsValueSet() { - structMap["next_product_id"] = s.NextProductId.Value() - } - if s.NextProductHandle.IsValueSet() { - structMap["next_product_handle"] = s.NextProductHandle.Value() - } - if s.CouponUseCount.IsValueSet() { - structMap["coupon_use_count"] = s.CouponUseCount.Value() - } - if s.CouponUsesAllowed.IsValueSet() { - structMap["coupon_uses_allowed"] = s.CouponUsesAllowed.Value() - } - if s.ReasonCode.IsValueSet() { - structMap["reason_code"] = s.ReasonCode.Value() - } - if s.AutomaticallyResumeAt.IsValueSet() { - var AutomaticallyResumeAtVal *string = nil - if s.AutomaticallyResumeAt.Value() != nil { - val := s.AutomaticallyResumeAt.Value().Format(time.RFC3339) - AutomaticallyResumeAtVal = &val - } - structMap["automatically_resume_at"] = AutomaticallyResumeAtVal - } - if s.CouponCodes != nil { - structMap["coupon_codes"] = s.CouponCodes - } - if s.OfferId.IsValueSet() { - structMap["offer_id"] = s.OfferId.Value() - } - if s.PayerId.IsValueSet() { - structMap["payer_id"] = s.PayerId.Value() - } - if s.CurrentBillingAmountInCents != nil { - structMap["current_billing_amount_in_cents"] = s.CurrentBillingAmountInCents - } - if s.ProductPricePointId != nil { - structMap["product_price_point_id"] = s.ProductPricePointId - } - if s.ProductPricePointType != nil { - structMap["product_price_point_type"] = s.ProductPricePointType - } - if s.NextProductPricePointId.IsValueSet() { - structMap["next_product_price_point_id"] = s.NextProductPricePointId.Value() - } - if s.NetTerms.IsValueSet() { - structMap["net_terms"] = s.NetTerms.Value() - } - if s.StoredCredentialTransactionId.IsValueSet() { - structMap["stored_credential_transaction_id"] = s.StoredCredentialTransactionId.Value() - } - if s.Reference.IsValueSet() { - structMap["reference"] = s.Reference.Value() - } - if s.OnHoldAt.IsValueSet() { - var OnHoldAtVal *string = nil - if s.OnHoldAt.Value() != nil { - val := s.OnHoldAt.Value().Format(time.RFC3339) - OnHoldAtVal = &val - } - structMap["on_hold_at"] = OnHoldAtVal - } - if s.PrepaidDunning != nil { - structMap["prepaid_dunning"] = s.PrepaidDunning - } - if s.Coupons != nil { - structMap["coupons"] = s.Coupons - } - if s.DunningCommunicationDelayEnabled != nil { - structMap["dunning_communication_delay_enabled"] = s.DunningCommunicationDelayEnabled - } - if s.DunningCommunicationDelayTimeZone.IsValueSet() { - structMap["dunning_communication_delay_time_zone"] = s.DunningCommunicationDelayTimeZone.Value() - } - if s.ReceivesInvoiceEmails.IsValueSet() { - structMap["receives_invoice_emails"] = s.ReceivesInvoiceEmails.Value() - } - if s.Locale.IsValueSet() { - structMap["locale"] = s.Locale.Value() - } - if s.Currency != nil { - structMap["currency"] = s.Currency - } - if s.ScheduledCancellationAt.IsValueSet() { - var ScheduledCancellationAtVal *string = nil - if s.ScheduledCancellationAt.Value() != nil { - val := s.ScheduledCancellationAt.Value().Format(time.RFC3339) - ScheduledCancellationAtVal = &val - } - structMap["scheduled_cancellation_at"] = ScheduledCancellationAtVal - } - if s.CreditBalanceInCents != nil { - structMap["credit_balance_in_cents"] = s.CreditBalanceInCents - } - if s.PrepaymentBalanceInCents != nil { - structMap["prepayment_balance_in_cents"] = s.PrepaymentBalanceInCents - } - if s.PrepaidConfiguration != nil { - structMap["prepaid_configuration"] = s.PrepaidConfiguration.toMap() - } - if s.SelfServicePageToken != nil { - structMap["self_service_page_token"] = s.SelfServicePageToken - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.State != nil { + structMap["state"] = s.State + } + if s.BalanceInCents != nil { + structMap["balance_in_cents"] = s.BalanceInCents + } + if s.TotalRevenueInCents != nil { + structMap["total_revenue_in_cents"] = s.TotalRevenueInCents + } + if s.ProductPriceInCents != nil { + structMap["product_price_in_cents"] = s.ProductPriceInCents + } + if s.ProductVersionNumber != nil { + structMap["product_version_number"] = s.ProductVersionNumber + } + if s.CurrentPeriodEndsAt != nil { + structMap["current_period_ends_at"] = s.CurrentPeriodEndsAt.Format(time.RFC3339) + } + if s.NextAssessmentAt != nil { + structMap["next_assessment_at"] = s.NextAssessmentAt.Format(time.RFC3339) + } + if s.TrialStartedAt.IsValueSet() { + var TrialStartedAtVal *string = nil + if s.TrialStartedAt.Value() != nil { + val := s.TrialStartedAt.Value().Format(time.RFC3339) + TrialStartedAtVal = &val + } + if s.TrialStartedAt.Value() != nil { + structMap["trial_started_at"] = TrialStartedAtVal + } else { + structMap["trial_started_at"] = nil + } + } + if s.TrialEndedAt.IsValueSet() { + var TrialEndedAtVal *string = nil + if s.TrialEndedAt.Value() != nil { + val := s.TrialEndedAt.Value().Format(time.RFC3339) + TrialEndedAtVal = &val + } + if s.TrialEndedAt.Value() != nil { + structMap["trial_ended_at"] = TrialEndedAtVal + } else { + structMap["trial_ended_at"] = nil + } + } + if s.ActivatedAt != nil { + structMap["activated_at"] = s.ActivatedAt.Format(time.RFC3339) + } + if s.ExpiresAt.IsValueSet() { + var ExpiresAtVal *string = nil + if s.ExpiresAt.Value() != nil { + val := s.ExpiresAt.Value().Format(time.RFC3339) + ExpiresAtVal = &val + } + if s.ExpiresAt.Value() != nil { + structMap["expires_at"] = ExpiresAtVal + } else { + structMap["expires_at"] = nil + } + } + if s.CreatedAt != nil { + structMap["created_at"] = s.CreatedAt.Format(time.RFC3339) + } + if s.UpdatedAt != nil { + structMap["updated_at"] = s.UpdatedAt.Format(time.RFC3339) + } + if s.CancellationMessage.IsValueSet() { + if s.CancellationMessage.Value() != nil { + structMap["cancellation_message"] = s.CancellationMessage.Value() + } else { + structMap["cancellation_message"] = nil + } + } + if s.CancellationMethod.IsValueSet() { + if s.CancellationMethod.Value() != nil { + structMap["cancellation_method"] = s.CancellationMethod.Value() + } else { + structMap["cancellation_method"] = nil + } + } + if s.CancelAtEndOfPeriod.IsValueSet() { + if s.CancelAtEndOfPeriod.Value() != nil { + structMap["cancel_at_end_of_period"] = s.CancelAtEndOfPeriod.Value() + } else { + structMap["cancel_at_end_of_period"] = nil + } + } + if s.CanceledAt.IsValueSet() { + var CanceledAtVal *string = nil + if s.CanceledAt.Value() != nil { + val := s.CanceledAt.Value().Format(time.RFC3339) + CanceledAtVal = &val + } + if s.CanceledAt.Value() != nil { + structMap["canceled_at"] = CanceledAtVal + } else { + structMap["canceled_at"] = nil + } + } + if s.CurrentPeriodStartedAt != nil { + structMap["current_period_started_at"] = s.CurrentPeriodStartedAt.Format(time.RFC3339) + } + if s.PreviousState != nil { + structMap["previous_state"] = s.PreviousState + } + if s.SignupPaymentId != nil { + structMap["signup_payment_id"] = s.SignupPaymentId + } + if s.SignupRevenue != nil { + structMap["signup_revenue"] = s.SignupRevenue + } + if s.DelayedCancelAt.IsValueSet() { + var DelayedCancelAtVal *string = nil + if s.DelayedCancelAt.Value() != nil { + val := s.DelayedCancelAt.Value().Format(time.RFC3339) + DelayedCancelAtVal = &val + } + if s.DelayedCancelAt.Value() != nil { + structMap["delayed_cancel_at"] = DelayedCancelAtVal + } else { + structMap["delayed_cancel_at"] = nil + } + } + if s.CouponCode.IsValueSet() { + if s.CouponCode.Value() != nil { + structMap["coupon_code"] = s.CouponCode.Value() + } else { + structMap["coupon_code"] = nil + } + } + if s.SnapDay.IsValueSet() { + if s.SnapDay.Value() != nil { + structMap["snap_day"] = s.SnapDay.Value() + } else { + structMap["snap_day"] = nil + } + } + if s.PaymentCollectionMethod != nil { + structMap["payment_collection_method"] = s.PaymentCollectionMethod + } + if s.Customer != nil { + structMap["customer"] = s.Customer.toMap() + } + if s.Product != nil { + structMap["product"] = s.Product.toMap() + } + if s.CreditCard != nil { + structMap["credit_card"] = s.CreditCard.toMap() + } + if s.Group.IsValueSet() { + if s.Group.Value() != nil { + structMap["group"] = s.Group.Value().toMap() + } else { + structMap["group"] = nil + } + } + if s.BankAccount != nil { + structMap["bank_account"] = s.BankAccount.toMap() + } + if s.PaymentType.IsValueSet() { + if s.PaymentType.Value() != nil { + structMap["payment_type"] = s.PaymentType.Value() + } else { + structMap["payment_type"] = nil + } + } + if s.ReferralCode.IsValueSet() { + if s.ReferralCode.Value() != nil { + structMap["referral_code"] = s.ReferralCode.Value() + } else { + structMap["referral_code"] = nil + } + } + if s.NextProductId.IsValueSet() { + if s.NextProductId.Value() != nil { + structMap["next_product_id"] = s.NextProductId.Value() + } else { + structMap["next_product_id"] = nil + } + } + if s.NextProductHandle.IsValueSet() { + if s.NextProductHandle.Value() != nil { + structMap["next_product_handle"] = s.NextProductHandle.Value() + } else { + structMap["next_product_handle"] = nil + } + } + if s.CouponUseCount.IsValueSet() { + if s.CouponUseCount.Value() != nil { + structMap["coupon_use_count"] = s.CouponUseCount.Value() + } else { + structMap["coupon_use_count"] = nil + } + } + if s.CouponUsesAllowed.IsValueSet() { + if s.CouponUsesAllowed.Value() != nil { + structMap["coupon_uses_allowed"] = s.CouponUsesAllowed.Value() + } else { + structMap["coupon_uses_allowed"] = nil + } + } + if s.ReasonCode.IsValueSet() { + if s.ReasonCode.Value() != nil { + structMap["reason_code"] = s.ReasonCode.Value() + } else { + structMap["reason_code"] = nil + } + } + if s.AutomaticallyResumeAt.IsValueSet() { + var AutomaticallyResumeAtVal *string = nil + if s.AutomaticallyResumeAt.Value() != nil { + val := s.AutomaticallyResumeAt.Value().Format(time.RFC3339) + AutomaticallyResumeAtVal = &val + } + if s.AutomaticallyResumeAt.Value() != nil { + structMap["automatically_resume_at"] = AutomaticallyResumeAtVal + } else { + structMap["automatically_resume_at"] = nil + } + } + if s.CouponCodes != nil { + structMap["coupon_codes"] = s.CouponCodes + } + if s.OfferId.IsValueSet() { + if s.OfferId.Value() != nil { + structMap["offer_id"] = s.OfferId.Value() + } else { + structMap["offer_id"] = nil + } + } + if s.PayerId.IsValueSet() { + if s.PayerId.Value() != nil { + structMap["payer_id"] = s.PayerId.Value() + } else { + structMap["payer_id"] = nil + } + } + if s.CurrentBillingAmountInCents != nil { + structMap["current_billing_amount_in_cents"] = s.CurrentBillingAmountInCents + } + if s.ProductPricePointId != nil { + structMap["product_price_point_id"] = s.ProductPricePointId + } + if s.ProductPricePointType != nil { + structMap["product_price_point_type"] = s.ProductPricePointType + } + if s.NextProductPricePointId.IsValueSet() { + if s.NextProductPricePointId.Value() != nil { + structMap["next_product_price_point_id"] = s.NextProductPricePointId.Value() + } else { + structMap["next_product_price_point_id"] = nil + } + } + if s.NetTerms.IsValueSet() { + if s.NetTerms.Value() != nil { + structMap["net_terms"] = s.NetTerms.Value() + } else { + structMap["net_terms"] = nil + } + } + if s.StoredCredentialTransactionId.IsValueSet() { + if s.StoredCredentialTransactionId.Value() != nil { + structMap["stored_credential_transaction_id"] = s.StoredCredentialTransactionId.Value() + } else { + structMap["stored_credential_transaction_id"] = nil + } + } + if s.Reference.IsValueSet() { + if s.Reference.Value() != nil { + structMap["reference"] = s.Reference.Value() + } else { + structMap["reference"] = nil + } + } + if s.OnHoldAt.IsValueSet() { + var OnHoldAtVal *string = nil + if s.OnHoldAt.Value() != nil { + val := s.OnHoldAt.Value().Format(time.RFC3339) + OnHoldAtVal = &val + } + if s.OnHoldAt.Value() != nil { + structMap["on_hold_at"] = OnHoldAtVal + } else { + structMap["on_hold_at"] = nil + } + } + if s.PrepaidDunning != nil { + structMap["prepaid_dunning"] = s.PrepaidDunning + } + if s.Coupons != nil { + structMap["coupons"] = s.Coupons + } + if s.DunningCommunicationDelayEnabled != nil { + structMap["dunning_communication_delay_enabled"] = s.DunningCommunicationDelayEnabled + } + if s.DunningCommunicationDelayTimeZone.IsValueSet() { + if s.DunningCommunicationDelayTimeZone.Value() != nil { + structMap["dunning_communication_delay_time_zone"] = s.DunningCommunicationDelayTimeZone.Value() + } else { + structMap["dunning_communication_delay_time_zone"] = nil + } + } + if s.ReceivesInvoiceEmails.IsValueSet() { + if s.ReceivesInvoiceEmails.Value() != nil { + structMap["receives_invoice_emails"] = s.ReceivesInvoiceEmails.Value() + } else { + structMap["receives_invoice_emails"] = nil + } + } + if s.Locale.IsValueSet() { + if s.Locale.Value() != nil { + structMap["locale"] = s.Locale.Value() + } else { + structMap["locale"] = nil + } + } + if s.Currency != nil { + structMap["currency"] = s.Currency + } + if s.ScheduledCancellationAt.IsValueSet() { + var ScheduledCancellationAtVal *string = nil + if s.ScheduledCancellationAt.Value() != nil { + val := s.ScheduledCancellationAt.Value().Format(time.RFC3339) + ScheduledCancellationAtVal = &val + } + if s.ScheduledCancellationAt.Value() != nil { + structMap["scheduled_cancellation_at"] = ScheduledCancellationAtVal + } else { + structMap["scheduled_cancellation_at"] = nil + } + } + if s.CreditBalanceInCents != nil { + structMap["credit_balance_in_cents"] = s.CreditBalanceInCents + } + if s.PrepaymentBalanceInCents != nil { + structMap["prepayment_balance_in_cents"] = s.PrepaymentBalanceInCents + } + if s.PrepaidConfiguration != nil { + structMap["prepaid_configuration"] = s.PrepaidConfiguration.toMap() + } + if s.SelfServicePageToken != nil { + structMap["self_service_page_token"] = s.SelfServicePageToken + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Subscription. +// UnmarshalJSON implements the json.Unmarshaler interface for Subscription. // It customizes the JSON unmarshaling process for Subscription objects. func (s *Subscription) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - State *SubscriptionState `json:"state,omitempty"` - BalanceInCents *int64 `json:"balance_in_cents,omitempty"` - TotalRevenueInCents *int64 `json:"total_revenue_in_cents,omitempty"` - ProductPriceInCents *int64 `json:"product_price_in_cents,omitempty"` - ProductVersionNumber *int `json:"product_version_number,omitempty"` - CurrentPeriodEndsAt *string `json:"current_period_ends_at,omitempty"` - NextAssessmentAt *string `json:"next_assessment_at,omitempty"` - TrialStartedAt Optional[string] `json:"trial_started_at"` - TrialEndedAt Optional[string] `json:"trial_ended_at"` - ActivatedAt *string `json:"activated_at,omitempty"` - ExpiresAt Optional[string] `json:"expires_at"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - CancellationMessage Optional[string] `json:"cancellation_message"` - CancellationMethod Optional[CancellationMethod] `json:"cancellation_method"` - CancelAtEndOfPeriod Optional[bool] `json:"cancel_at_end_of_period"` - CanceledAt Optional[string] `json:"canceled_at"` - CurrentPeriodStartedAt *string `json:"current_period_started_at,omitempty"` - PreviousState *SubscriptionState `json:"previous_state,omitempty"` - SignupPaymentId *int `json:"signup_payment_id,omitempty"` - SignupRevenue *string `json:"signup_revenue,omitempty"` - DelayedCancelAt Optional[string] `json:"delayed_cancel_at"` - CouponCode Optional[string] `json:"coupon_code"` - SnapDay Optional[string] `json:"snap_day"` - PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` - Customer *Customer `json:"customer,omitempty"` - Product *Product `json:"product,omitempty"` - CreditCard *CreditCardPaymentProfile `json:"credit_card,omitempty"` - Group Optional[NestedSubscriptionGroup] `json:"group"` - BankAccount *BankAccountPaymentProfile `json:"bank_account,omitempty"` - PaymentType Optional[string] `json:"payment_type"` - ReferralCode Optional[string] `json:"referral_code"` - NextProductId Optional[int] `json:"next_product_id"` - NextProductHandle Optional[string] `json:"next_product_handle"` - CouponUseCount Optional[int] `json:"coupon_use_count"` - CouponUsesAllowed Optional[int] `json:"coupon_uses_allowed"` - ReasonCode Optional[string] `json:"reason_code"` - AutomaticallyResumeAt Optional[string] `json:"automatically_resume_at"` - CouponCodes []string `json:"coupon_codes,omitempty"` - OfferId Optional[int] `json:"offer_id"` - PayerId Optional[int] `json:"payer_id"` - CurrentBillingAmountInCents *int64 `json:"current_billing_amount_in_cents,omitempty"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - ProductPricePointType *PricePointType `json:"product_price_point_type,omitempty"` - NextProductPricePointId Optional[int] `json:"next_product_price_point_id"` - NetTerms Optional[int] `json:"net_terms"` - StoredCredentialTransactionId Optional[int] `json:"stored_credential_transaction_id"` - Reference Optional[string] `json:"reference"` - OnHoldAt Optional[string] `json:"on_hold_at"` - PrepaidDunning *bool `json:"prepaid_dunning,omitempty"` - Coupons []SubscriptionIncludedCoupon `json:"coupons,omitempty"` - DunningCommunicationDelayEnabled *bool `json:"dunning_communication_delay_enabled,omitempty"` - DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` - ReceivesInvoiceEmails Optional[bool] `json:"receives_invoice_emails"` - Locale Optional[string] `json:"locale"` - Currency *string `json:"currency,omitempty"` - ScheduledCancellationAt Optional[string] `json:"scheduled_cancellation_at"` - CreditBalanceInCents *int64 `json:"credit_balance_in_cents,omitempty"` - PrepaymentBalanceInCents *int64 `json:"prepayment_balance_in_cents,omitempty"` - PrepaidConfiguration *PrepaidConfiguration `json:"prepaid_configuration,omitempty"` - SelfServicePageToken *string `json:"self_service_page_token,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.State = temp.State - s.BalanceInCents = temp.BalanceInCents - s.TotalRevenueInCents = temp.TotalRevenueInCents - s.ProductPriceInCents = temp.ProductPriceInCents - s.ProductVersionNumber = temp.ProductVersionNumber - if temp.CurrentPeriodEndsAt != nil { - CurrentPeriodEndsAtVal, err := time.Parse(time.RFC3339, *temp.CurrentPeriodEndsAt) - if err != nil { - log.Fatalf("Cannot Parse current_period_ends_at as % s format.", time.RFC3339) - } - s.CurrentPeriodEndsAt = &CurrentPeriodEndsAtVal - } - if temp.NextAssessmentAt != nil { - NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) - if err != nil { - log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) - } - s.NextAssessmentAt = &NextAssessmentAtVal - } - s.TrialStartedAt.ShouldSetValue(temp.TrialStartedAt.IsValueSet()) - if temp.TrialStartedAt.Value() != nil { - TrialStartedAtVal, err := time.Parse(time.RFC3339, (*temp.TrialStartedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse trial_started_at as % s format.", time.RFC3339) - } - s.TrialStartedAt.SetValue(&TrialStartedAtVal) - } - s.TrialEndedAt.ShouldSetValue(temp.TrialEndedAt.IsValueSet()) - if temp.TrialEndedAt.Value() != nil { - TrialEndedAtVal, err := time.Parse(time.RFC3339, (*temp.TrialEndedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse trial_ended_at as % s format.", time.RFC3339) - } - s.TrialEndedAt.SetValue(&TrialEndedAtVal) - } - if temp.ActivatedAt != nil { - ActivatedAtVal, err := time.Parse(time.RFC3339, *temp.ActivatedAt) - if err != nil { - log.Fatalf("Cannot Parse activated_at as % s format.", time.RFC3339) - } - s.ActivatedAt = &ActivatedAtVal - } - s.ExpiresAt.ShouldSetValue(temp.ExpiresAt.IsValueSet()) - if temp.ExpiresAt.Value() != nil { - ExpiresAtVal, err := time.Parse(time.RFC3339, (*temp.ExpiresAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) - } - s.ExpiresAt.SetValue(&ExpiresAtVal) - } - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - s.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - s.UpdatedAt = &UpdatedAtVal - } - s.CancellationMessage = temp.CancellationMessage - s.CancellationMethod = temp.CancellationMethod - s.CancelAtEndOfPeriod = temp.CancelAtEndOfPeriod - s.CanceledAt.ShouldSetValue(temp.CanceledAt.IsValueSet()) - if temp.CanceledAt.Value() != nil { - CanceledAtVal, err := time.Parse(time.RFC3339, (*temp.CanceledAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse canceled_at as % s format.", time.RFC3339) - } - s.CanceledAt.SetValue(&CanceledAtVal) - } - if temp.CurrentPeriodStartedAt != nil { - CurrentPeriodStartedAtVal, err := time.Parse(time.RFC3339, *temp.CurrentPeriodStartedAt) - if err != nil { - log.Fatalf("Cannot Parse current_period_started_at as % s format.", time.RFC3339) - } - s.CurrentPeriodStartedAt = &CurrentPeriodStartedAtVal - } - s.PreviousState = temp.PreviousState - s.SignupPaymentId = temp.SignupPaymentId - s.SignupRevenue = temp.SignupRevenue - s.DelayedCancelAt.ShouldSetValue(temp.DelayedCancelAt.IsValueSet()) - if temp.DelayedCancelAt.Value() != nil { - DelayedCancelAtVal, err := time.Parse(time.RFC3339, (*temp.DelayedCancelAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse delayed_cancel_at as % s format.", time.RFC3339) - } - s.DelayedCancelAt.SetValue(&DelayedCancelAtVal) - } - s.CouponCode = temp.CouponCode - s.SnapDay = temp.SnapDay - s.PaymentCollectionMethod = temp.PaymentCollectionMethod - s.Customer = temp.Customer - s.Product = temp.Product - s.CreditCard = temp.CreditCard - s.Group = temp.Group - s.BankAccount = temp.BankAccount - s.PaymentType = temp.PaymentType - s.ReferralCode = temp.ReferralCode - s.NextProductId = temp.NextProductId - s.NextProductHandle = temp.NextProductHandle - s.CouponUseCount = temp.CouponUseCount - s.CouponUsesAllowed = temp.CouponUsesAllowed - s.ReasonCode = temp.ReasonCode - s.AutomaticallyResumeAt.ShouldSetValue(temp.AutomaticallyResumeAt.IsValueSet()) - if temp.AutomaticallyResumeAt.Value() != nil { - AutomaticallyResumeAtVal, err := time.Parse(time.RFC3339, (*temp.AutomaticallyResumeAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse automatically_resume_at as % s format.", time.RFC3339) - } - s.AutomaticallyResumeAt.SetValue(&AutomaticallyResumeAtVal) - } - s.CouponCodes = temp.CouponCodes - s.OfferId = temp.OfferId - s.PayerId = temp.PayerId - s.CurrentBillingAmountInCents = temp.CurrentBillingAmountInCents - s.ProductPricePointId = temp.ProductPricePointId - s.ProductPricePointType = temp.ProductPricePointType - s.NextProductPricePointId = temp.NextProductPricePointId - s.NetTerms = temp.NetTerms - s.StoredCredentialTransactionId = temp.StoredCredentialTransactionId - s.Reference = temp.Reference - s.OnHoldAt.ShouldSetValue(temp.OnHoldAt.IsValueSet()) - if temp.OnHoldAt.Value() != nil { - OnHoldAtVal, err := time.Parse(time.RFC3339, (*temp.OnHoldAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse on_hold_at as % s format.", time.RFC3339) - } - s.OnHoldAt.SetValue(&OnHoldAtVal) - } - s.PrepaidDunning = temp.PrepaidDunning - s.Coupons = temp.Coupons - s.DunningCommunicationDelayEnabled = temp.DunningCommunicationDelayEnabled - s.DunningCommunicationDelayTimeZone = temp.DunningCommunicationDelayTimeZone - s.ReceivesInvoiceEmails = temp.ReceivesInvoiceEmails - s.Locale = temp.Locale - s.Currency = temp.Currency - s.ScheduledCancellationAt.ShouldSetValue(temp.ScheduledCancellationAt.IsValueSet()) - if temp.ScheduledCancellationAt.Value() != nil { - ScheduledCancellationAtVal, err := time.Parse(time.RFC3339, (*temp.ScheduledCancellationAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse scheduled_cancellation_at as % s format.", time.RFC3339) - } - s.ScheduledCancellationAt.SetValue(&ScheduledCancellationAtVal) - } - s.CreditBalanceInCents = temp.CreditBalanceInCents - s.PrepaymentBalanceInCents = temp.PrepaymentBalanceInCents - s.PrepaidConfiguration = temp.PrepaidConfiguration - s.SelfServicePageToken = temp.SelfServicePageToken - return nil + var temp subscription + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.State = temp.State + s.BalanceInCents = temp.BalanceInCents + s.TotalRevenueInCents = temp.TotalRevenueInCents + s.ProductPriceInCents = temp.ProductPriceInCents + s.ProductVersionNumber = temp.ProductVersionNumber + if temp.CurrentPeriodEndsAt != nil { + CurrentPeriodEndsAtVal, err := time.Parse(time.RFC3339, *temp.CurrentPeriodEndsAt) + if err != nil { + log.Fatalf("Cannot Parse current_period_ends_at as % s format.", time.RFC3339) + } + s.CurrentPeriodEndsAt = &CurrentPeriodEndsAtVal + } + if temp.NextAssessmentAt != nil { + NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) + if err != nil { + log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) + } + s.NextAssessmentAt = &NextAssessmentAtVal + } + s.TrialStartedAt.ShouldSetValue(temp.TrialStartedAt.IsValueSet()) + if temp.TrialStartedAt.Value() != nil { + TrialStartedAtVal, err := time.Parse(time.RFC3339, (*temp.TrialStartedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse trial_started_at as % s format.", time.RFC3339) + } + s.TrialStartedAt.SetValue(&TrialStartedAtVal) + } + s.TrialEndedAt.ShouldSetValue(temp.TrialEndedAt.IsValueSet()) + if temp.TrialEndedAt.Value() != nil { + TrialEndedAtVal, err := time.Parse(time.RFC3339, (*temp.TrialEndedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse trial_ended_at as % s format.", time.RFC3339) + } + s.TrialEndedAt.SetValue(&TrialEndedAtVal) + } + if temp.ActivatedAt != nil { + ActivatedAtVal, err := time.Parse(time.RFC3339, *temp.ActivatedAt) + if err != nil { + log.Fatalf("Cannot Parse activated_at as % s format.", time.RFC3339) + } + s.ActivatedAt = &ActivatedAtVal + } + s.ExpiresAt.ShouldSetValue(temp.ExpiresAt.IsValueSet()) + if temp.ExpiresAt.Value() != nil { + ExpiresAtVal, err := time.Parse(time.RFC3339, (*temp.ExpiresAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse expires_at as % s format.", time.RFC3339) + } + s.ExpiresAt.SetValue(&ExpiresAtVal) + } + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + s.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + s.UpdatedAt = &UpdatedAtVal + } + s.CancellationMessage = temp.CancellationMessage + s.CancellationMethod = temp.CancellationMethod + s.CancelAtEndOfPeriod = temp.CancelAtEndOfPeriod + s.CanceledAt.ShouldSetValue(temp.CanceledAt.IsValueSet()) + if temp.CanceledAt.Value() != nil { + CanceledAtVal, err := time.Parse(time.RFC3339, (*temp.CanceledAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse canceled_at as % s format.", time.RFC3339) + } + s.CanceledAt.SetValue(&CanceledAtVal) + } + if temp.CurrentPeriodStartedAt != nil { + CurrentPeriodStartedAtVal, err := time.Parse(time.RFC3339, *temp.CurrentPeriodStartedAt) + if err != nil { + log.Fatalf("Cannot Parse current_period_started_at as % s format.", time.RFC3339) + } + s.CurrentPeriodStartedAt = &CurrentPeriodStartedAtVal + } + s.PreviousState = temp.PreviousState + s.SignupPaymentId = temp.SignupPaymentId + s.SignupRevenue = temp.SignupRevenue + s.DelayedCancelAt.ShouldSetValue(temp.DelayedCancelAt.IsValueSet()) + if temp.DelayedCancelAt.Value() != nil { + DelayedCancelAtVal, err := time.Parse(time.RFC3339, (*temp.DelayedCancelAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse delayed_cancel_at as % s format.", time.RFC3339) + } + s.DelayedCancelAt.SetValue(&DelayedCancelAtVal) + } + s.CouponCode = temp.CouponCode + s.SnapDay = temp.SnapDay + s.PaymentCollectionMethod = temp.PaymentCollectionMethod + s.Customer = temp.Customer + s.Product = temp.Product + s.CreditCard = temp.CreditCard + s.Group = temp.Group + s.BankAccount = temp.BankAccount + s.PaymentType = temp.PaymentType + s.ReferralCode = temp.ReferralCode + s.NextProductId = temp.NextProductId + s.NextProductHandle = temp.NextProductHandle + s.CouponUseCount = temp.CouponUseCount + s.CouponUsesAllowed = temp.CouponUsesAllowed + s.ReasonCode = temp.ReasonCode + s.AutomaticallyResumeAt.ShouldSetValue(temp.AutomaticallyResumeAt.IsValueSet()) + if temp.AutomaticallyResumeAt.Value() != nil { + AutomaticallyResumeAtVal, err := time.Parse(time.RFC3339, (*temp.AutomaticallyResumeAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse automatically_resume_at as % s format.", time.RFC3339) + } + s.AutomaticallyResumeAt.SetValue(&AutomaticallyResumeAtVal) + } + s.CouponCodes = temp.CouponCodes + s.OfferId = temp.OfferId + s.PayerId = temp.PayerId + s.CurrentBillingAmountInCents = temp.CurrentBillingAmountInCents + s.ProductPricePointId = temp.ProductPricePointId + s.ProductPricePointType = temp.ProductPricePointType + s.NextProductPricePointId = temp.NextProductPricePointId + s.NetTerms = temp.NetTerms + s.StoredCredentialTransactionId = temp.StoredCredentialTransactionId + s.Reference = temp.Reference + s.OnHoldAt.ShouldSetValue(temp.OnHoldAt.IsValueSet()) + if temp.OnHoldAt.Value() != nil { + OnHoldAtVal, err := time.Parse(time.RFC3339, (*temp.OnHoldAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse on_hold_at as % s format.", time.RFC3339) + } + s.OnHoldAt.SetValue(&OnHoldAtVal) + } + s.PrepaidDunning = temp.PrepaidDunning + s.Coupons = temp.Coupons + s.DunningCommunicationDelayEnabled = temp.DunningCommunicationDelayEnabled + s.DunningCommunicationDelayTimeZone = temp.DunningCommunicationDelayTimeZone + s.ReceivesInvoiceEmails = temp.ReceivesInvoiceEmails + s.Locale = temp.Locale + s.Currency = temp.Currency + s.ScheduledCancellationAt.ShouldSetValue(temp.ScheduledCancellationAt.IsValueSet()) + if temp.ScheduledCancellationAt.Value() != nil { + ScheduledCancellationAtVal, err := time.Parse(time.RFC3339, (*temp.ScheduledCancellationAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse scheduled_cancellation_at as % s format.", time.RFC3339) + } + s.ScheduledCancellationAt.SetValue(&ScheduledCancellationAtVal) + } + s.CreditBalanceInCents = temp.CreditBalanceInCents + s.PrepaymentBalanceInCents = temp.PrepaymentBalanceInCents + s.PrepaidConfiguration = temp.PrepaidConfiguration + s.SelfServicePageToken = temp.SelfServicePageToken + return nil +} + +// TODO +type subscription struct { + Id *int `json:"id,omitempty"` + State *SubscriptionState `json:"state,omitempty"` + BalanceInCents *int64 `json:"balance_in_cents,omitempty"` + TotalRevenueInCents *int64 `json:"total_revenue_in_cents,omitempty"` + ProductPriceInCents *int64 `json:"product_price_in_cents,omitempty"` + ProductVersionNumber *int `json:"product_version_number,omitempty"` + CurrentPeriodEndsAt *string `json:"current_period_ends_at,omitempty"` + NextAssessmentAt *string `json:"next_assessment_at,omitempty"` + TrialStartedAt Optional[string] `json:"trial_started_at"` + TrialEndedAt Optional[string] `json:"trial_ended_at"` + ActivatedAt *string `json:"activated_at,omitempty"` + ExpiresAt Optional[string] `json:"expires_at"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + CancellationMessage Optional[string] `json:"cancellation_message"` + CancellationMethod Optional[CancellationMethod] `json:"cancellation_method"` + CancelAtEndOfPeriod Optional[bool] `json:"cancel_at_end_of_period"` + CanceledAt Optional[string] `json:"canceled_at"` + CurrentPeriodStartedAt *string `json:"current_period_started_at,omitempty"` + PreviousState *SubscriptionState `json:"previous_state,omitempty"` + SignupPaymentId *int `json:"signup_payment_id,omitempty"` + SignupRevenue *string `json:"signup_revenue,omitempty"` + DelayedCancelAt Optional[string] `json:"delayed_cancel_at"` + CouponCode Optional[string] `json:"coupon_code"` + SnapDay Optional[string] `json:"snap_day"` + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` + Customer *Customer `json:"customer,omitempty"` + Product *Product `json:"product,omitempty"` + CreditCard *CreditCardPaymentProfile `json:"credit_card,omitempty"` + Group Optional[SubscriptionGroup2] `json:"group"` + BankAccount *BankAccountPaymentProfile `json:"bank_account,omitempty"` + PaymentType Optional[string] `json:"payment_type"` + ReferralCode Optional[string] `json:"referral_code"` + NextProductId Optional[int] `json:"next_product_id"` + NextProductHandle Optional[string] `json:"next_product_handle"` + CouponUseCount Optional[int] `json:"coupon_use_count"` + CouponUsesAllowed Optional[int] `json:"coupon_uses_allowed"` + ReasonCode Optional[string] `json:"reason_code"` + AutomaticallyResumeAt Optional[string] `json:"automatically_resume_at"` + CouponCodes []string `json:"coupon_codes,omitempty"` + OfferId Optional[int] `json:"offer_id"` + PayerId Optional[int] `json:"payer_id"` + CurrentBillingAmountInCents *int64 `json:"current_billing_amount_in_cents,omitempty"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + ProductPricePointType *PricePointType `json:"product_price_point_type,omitempty"` + NextProductPricePointId Optional[int] `json:"next_product_price_point_id"` + NetTerms Optional[int] `json:"net_terms"` + StoredCredentialTransactionId Optional[int] `json:"stored_credential_transaction_id"` + Reference Optional[string] `json:"reference"` + OnHoldAt Optional[string] `json:"on_hold_at"` + PrepaidDunning *bool `json:"prepaid_dunning,omitempty"` + Coupons []SubscriptionIncludedCoupon `json:"coupons,omitempty"` + DunningCommunicationDelayEnabled *bool `json:"dunning_communication_delay_enabled,omitempty"` + DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` + ReceivesInvoiceEmails Optional[bool] `json:"receives_invoice_emails"` + Locale Optional[string] `json:"locale"` + Currency *string `json:"currency,omitempty"` + ScheduledCancellationAt Optional[string] `json:"scheduled_cancellation_at"` + CreditBalanceInCents *int64 `json:"credit_balance_in_cents,omitempty"` + PrepaymentBalanceInCents *int64 `json:"prepayment_balance_in_cents,omitempty"` + PrepaidConfiguration *PrepaidConfiguration `json:"prepaid_configuration,omitempty"` + SelfServicePageToken *string `json:"self_service_page_token,omitempty"` } diff --git a/models/subscription_component.go b/models/subscription_component.go index e6a8b8a6..e9557376 100644 --- a/models/subscription_component.go +++ b/models/subscription_component.go @@ -1,258 +1,300 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // SubscriptionComponent represents a SubscriptionComponent struct. type SubscriptionComponent struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - // A handle for the component type - Kind *ComponentKind `json:"kind,omitempty"` - UnitName *string `json:"unit_name,omitempty"` - // (for on/off components) indicates if the component is enabled for the subscription - Enabled *bool `json:"enabled,omitempty"` - UnitBalance *int `json:"unit_balance,omitempty"` - Currency *string `json:"currency,omitempty"` - // For Quantity-based components: The current allocation for the component on the given subscription. For On/Off components: Use 1 for on. Use 0 for off. - AllocatedQuantity *interface{} `json:"allocated_quantity,omitempty"` - PricingScheme Optional[PricingScheme] `json:"pricing_scheme"` - ComponentId *int `json:"component_id,omitempty"` - ComponentHandle Optional[string] `json:"component_handle"` - SubscriptionId *int `json:"subscription_id,omitempty"` - Recurring *bool `json:"recurring,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - ArchivedAt Optional[time.Time] `json:"archived_at"` - PricePointId Optional[int] `json:"price_point_id"` - PricePointHandle Optional[string] `json:"price_point_handle"` - PricePointType *interface{} `json:"price_point_type,omitempty"` - PricePointName Optional[string] `json:"price_point_name"` - ProductFamilyId *int `json:"product_family_id,omitempty"` - ProductFamilyHandle *string `json:"product_family_handle,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` - Description Optional[string] `json:"description"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - // An optional object, will be returned if provided `include=subscription` query param. - Subscription *SubscriptionComponentSubscription `json:"subscription,omitempty"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - // The numerical interval. i.e. an interval of '30' coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + // A handle for the component type + Kind *ComponentKind `json:"kind,omitempty"` + UnitName *string `json:"unit_name,omitempty"` + // (for on/off components) indicates if the component is enabled for the subscription + Enabled *bool `json:"enabled,omitempty"` + UnitBalance *int `json:"unit_balance,omitempty"` + Currency *string `json:"currency,omitempty"` + // For Quantity-based components: The current allocation for the component on the given subscription. For On/Off components: Use 1 for on. Use 0 for off. + AllocatedQuantity *SubscriptionComponentAllocatedQuantity `json:"allocated_quantity,omitempty"` + PricingScheme Optional[SubscriptionComponentPricingScheme] `json:"pricing_scheme"` + ComponentId *int `json:"component_id,omitempty"` + ComponentHandle Optional[string] `json:"component_handle"` + SubscriptionId *int `json:"subscription_id,omitempty"` + Recurring *bool `json:"recurring,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + ArchivedAt Optional[time.Time] `json:"archived_at"` + PricePointId Optional[int] `json:"price_point_id"` + PricePointHandle Optional[string] `json:"price_point_handle"` + PricePointType *SubscriptionComponentPricePointType `json:"price_point_type,omitempty"` + PricePointName Optional[string] `json:"price_point_name"` + ProductFamilyId *int `json:"product_family_id,omitempty"` + ProductFamilyHandle *string `json:"product_family_handle,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` + Description Optional[string] `json:"description"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + // An optional object, will be returned if provided `include=subscription` query param. + Subscription *SubscriptionComponentSubscription `json:"subscription,omitempty"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + // The numerical interval. i.e. an interval of '30' coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionComponent. +// MarshalJSON implements the json.Marshaler interface for SubscriptionComponent. // It customizes the JSON marshaling process for SubscriptionComponent objects. func (s *SubscriptionComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionComponent object to a map representation for JSON marshaling. func (s *SubscriptionComponent) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.Name != nil { - structMap["name"] = s.Name - } - if s.Kind != nil { - structMap["kind"] = s.Kind - } - if s.UnitName != nil { - structMap["unit_name"] = s.UnitName - } - if s.Enabled != nil { - structMap["enabled"] = s.Enabled - } - if s.UnitBalance != nil { - structMap["unit_balance"] = s.UnitBalance - } - if s.Currency != nil { - structMap["currency"] = s.Currency - } - if s.AllocatedQuantity != nil { - structMap["allocated_quantity"] = s.AllocatedQuantity - } - if s.PricingScheme.IsValueSet() { - structMap["pricing_scheme"] = s.PricingScheme.Value() - } - if s.ComponentId != nil { - structMap["component_id"] = s.ComponentId - } - if s.ComponentHandle.IsValueSet() { - structMap["component_handle"] = s.ComponentHandle.Value() - } - if s.SubscriptionId != nil { - structMap["subscription_id"] = s.SubscriptionId - } - if s.Recurring != nil { - structMap["recurring"] = s.Recurring - } - if s.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = s.UpgradeCharge.Value() - } - if s.DowngradeCredit.IsValueSet() { - structMap["downgrade_credit"] = s.DowngradeCredit.Value() - } - if s.ArchivedAt.IsValueSet() { - var ArchivedAtVal *string = nil - if s.ArchivedAt.Value() != nil { - val := s.ArchivedAt.Value().Format(time.RFC3339) - ArchivedAtVal = &val - } - structMap["archived_at"] = ArchivedAtVal - } - if s.PricePointId.IsValueSet() { - structMap["price_point_id"] = s.PricePointId.Value() - } - if s.PricePointHandle.IsValueSet() { - structMap["price_point_handle"] = s.PricePointHandle.Value() - } - if s.PricePointType != nil { - structMap["price_point_type"] = s.PricePointType - } - if s.PricePointName.IsValueSet() { - structMap["price_point_name"] = s.PricePointName.Value() - } - if s.ProductFamilyId != nil { - structMap["product_family_id"] = s.ProductFamilyId - } - if s.ProductFamilyHandle != nil { - structMap["product_family_handle"] = s.ProductFamilyHandle - } - if s.CreatedAt != nil { - structMap["created_at"] = s.CreatedAt.Format(time.RFC3339) - } - if s.UpdatedAt != nil { - structMap["updated_at"] = s.UpdatedAt.Format(time.RFC3339) - } - if s.UseSiteExchangeRate.IsValueSet() { - structMap["use_site_exchange_rate"] = s.UseSiteExchangeRate.Value() - } - if s.Description.IsValueSet() { - structMap["description"] = s.Description.Value() - } - if s.AllowFractionalQuantities != nil { - structMap["allow_fractional_quantities"] = s.AllowFractionalQuantities - } - if s.Subscription != nil { - structMap["subscription"] = s.Subscription.toMap() - } - if s.DisplayOnHostedPage != nil { - structMap["display_on_hosted_page"] = s.DisplayOnHostedPage - } - if s.Interval != nil { - structMap["interval"] = s.Interval - } - if s.IntervalUnit != nil { - structMap["interval_unit"] = s.IntervalUnit - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.Name != nil { + structMap["name"] = s.Name + } + if s.Kind != nil { + structMap["kind"] = s.Kind + } + if s.UnitName != nil { + structMap["unit_name"] = s.UnitName + } + if s.Enabled != nil { + structMap["enabled"] = s.Enabled + } + if s.UnitBalance != nil { + structMap["unit_balance"] = s.UnitBalance + } + if s.Currency != nil { + structMap["currency"] = s.Currency + } + if s.AllocatedQuantity != nil { + structMap["allocated_quantity"] = s.AllocatedQuantity.toMap() + } + if s.PricingScheme.IsValueSet() { + if s.PricingScheme.Value() != nil { + structMap["pricing_scheme"] = s.PricingScheme.Value().toMap() + } else { + structMap["pricing_scheme"] = nil + } + } + if s.ComponentId != nil { + structMap["component_id"] = s.ComponentId + } + if s.ComponentHandle.IsValueSet() { + if s.ComponentHandle.Value() != nil { + structMap["component_handle"] = s.ComponentHandle.Value() + } else { + structMap["component_handle"] = nil + } + } + if s.SubscriptionId != nil { + structMap["subscription_id"] = s.SubscriptionId + } + if s.Recurring != nil { + structMap["recurring"] = s.Recurring + } + if s.UpgradeCharge.IsValueSet() { + if s.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = s.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + if s.DowngradeCredit.IsValueSet() { + if s.DowngradeCredit.Value() != nil { + structMap["downgrade_credit"] = s.DowngradeCredit.Value() + } else { + structMap["downgrade_credit"] = nil + } + } + if s.ArchivedAt.IsValueSet() { + var ArchivedAtVal *string = nil + if s.ArchivedAt.Value() != nil { + val := s.ArchivedAt.Value().Format(time.RFC3339) + ArchivedAtVal = &val + } + if s.ArchivedAt.Value() != nil { + structMap["archived_at"] = ArchivedAtVal + } else { + structMap["archived_at"] = nil + } + } + if s.PricePointId.IsValueSet() { + if s.PricePointId.Value() != nil { + structMap["price_point_id"] = s.PricePointId.Value() + } else { + structMap["price_point_id"] = nil + } + } + if s.PricePointHandle.IsValueSet() { + if s.PricePointHandle.Value() != nil { + structMap["price_point_handle"] = s.PricePointHandle.Value() + } else { + structMap["price_point_handle"] = nil + } + } + if s.PricePointType != nil { + structMap["price_point_type"] = s.PricePointType.toMap() + } + if s.PricePointName.IsValueSet() { + if s.PricePointName.Value() != nil { + structMap["price_point_name"] = s.PricePointName.Value() + } else { + structMap["price_point_name"] = nil + } + } + if s.ProductFamilyId != nil { + structMap["product_family_id"] = s.ProductFamilyId + } + if s.ProductFamilyHandle != nil { + structMap["product_family_handle"] = s.ProductFamilyHandle + } + if s.CreatedAt != nil { + structMap["created_at"] = s.CreatedAt.Format(time.RFC3339) + } + if s.UpdatedAt != nil { + structMap["updated_at"] = s.UpdatedAt.Format(time.RFC3339) + } + if s.UseSiteExchangeRate.IsValueSet() { + if s.UseSiteExchangeRate.Value() != nil { + structMap["use_site_exchange_rate"] = s.UseSiteExchangeRate.Value() + } else { + structMap["use_site_exchange_rate"] = nil + } + } + if s.Description.IsValueSet() { + if s.Description.Value() != nil { + structMap["description"] = s.Description.Value() + } else { + structMap["description"] = nil + } + } + if s.AllowFractionalQuantities != nil { + structMap["allow_fractional_quantities"] = s.AllowFractionalQuantities + } + if s.Subscription != nil { + structMap["subscription"] = s.Subscription.toMap() + } + if s.DisplayOnHostedPage != nil { + structMap["display_on_hosted_page"] = s.DisplayOnHostedPage + } + if s.Interval != nil { + structMap["interval"] = s.Interval + } + if s.IntervalUnit != nil { + structMap["interval_unit"] = s.IntervalUnit + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionComponent. // It customizes the JSON unmarshaling process for SubscriptionComponent objects. func (s *SubscriptionComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Kind *ComponentKind `json:"kind,omitempty"` - UnitName *string `json:"unit_name,omitempty"` - Enabled *bool `json:"enabled,omitempty"` - UnitBalance *int `json:"unit_balance,omitempty"` - Currency *string `json:"currency,omitempty"` - AllocatedQuantity *interface{} `json:"allocated_quantity,omitempty"` - PricingScheme Optional[PricingScheme] `json:"pricing_scheme"` - ComponentId *int `json:"component_id,omitempty"` - ComponentHandle Optional[string] `json:"component_handle"` - SubscriptionId *int `json:"subscription_id,omitempty"` - Recurring *bool `json:"recurring,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` - ArchivedAt Optional[string] `json:"archived_at"` - PricePointId Optional[int] `json:"price_point_id"` - PricePointHandle Optional[string] `json:"price_point_handle"` - PricePointType *interface{} `json:"price_point_type,omitempty"` - PricePointName Optional[string] `json:"price_point_name"` - ProductFamilyId *int `json:"product_family_id,omitempty"` - ProductFamilyHandle *string `json:"product_family_handle,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` - Description Optional[string] `json:"description"` - AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` - Subscription *SubscriptionComponentSubscription `json:"subscription,omitempty"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.Name = temp.Name - s.Kind = temp.Kind - s.UnitName = temp.UnitName - s.Enabled = temp.Enabled - s.UnitBalance = temp.UnitBalance - s.Currency = temp.Currency - s.AllocatedQuantity = temp.AllocatedQuantity - s.PricingScheme = temp.PricingScheme - s.ComponentId = temp.ComponentId - s.ComponentHandle = temp.ComponentHandle - s.SubscriptionId = temp.SubscriptionId - s.Recurring = temp.Recurring - s.UpgradeCharge = temp.UpgradeCharge - s.DowngradeCredit = temp.DowngradeCredit - s.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) - if temp.ArchivedAt.Value() != nil { - ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) - } - s.ArchivedAt.SetValue(&ArchivedAtVal) - } - s.PricePointId = temp.PricePointId - s.PricePointHandle = temp.PricePointHandle - s.PricePointType = temp.PricePointType - s.PricePointName = temp.PricePointName - s.ProductFamilyId = temp.ProductFamilyId - s.ProductFamilyHandle = temp.ProductFamilyHandle - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - s.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - s.UpdatedAt = &UpdatedAtVal - } - s.UseSiteExchangeRate = temp.UseSiteExchangeRate - s.Description = temp.Description - s.AllowFractionalQuantities = temp.AllowFractionalQuantities - s.Subscription = temp.Subscription - s.DisplayOnHostedPage = temp.DisplayOnHostedPage - s.Interval = temp.Interval - s.IntervalUnit = temp.IntervalUnit - return nil + var temp subscriptionComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.Name = temp.Name + s.Kind = temp.Kind + s.UnitName = temp.UnitName + s.Enabled = temp.Enabled + s.UnitBalance = temp.UnitBalance + s.Currency = temp.Currency + s.AllocatedQuantity = temp.AllocatedQuantity + s.PricingScheme = temp.PricingScheme + s.ComponentId = temp.ComponentId + s.ComponentHandle = temp.ComponentHandle + s.SubscriptionId = temp.SubscriptionId + s.Recurring = temp.Recurring + s.UpgradeCharge = temp.UpgradeCharge + s.DowngradeCredit = temp.DowngradeCredit + s.ArchivedAt.ShouldSetValue(temp.ArchivedAt.IsValueSet()) + if temp.ArchivedAt.Value() != nil { + ArchivedAtVal, err := time.Parse(time.RFC3339, (*temp.ArchivedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse archived_at as % s format.", time.RFC3339) + } + s.ArchivedAt.SetValue(&ArchivedAtVal) + } + s.PricePointId = temp.PricePointId + s.PricePointHandle = temp.PricePointHandle + s.PricePointType = temp.PricePointType + s.PricePointName = temp.PricePointName + s.ProductFamilyId = temp.ProductFamilyId + s.ProductFamilyHandle = temp.ProductFamilyHandle + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + s.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + s.UpdatedAt = &UpdatedAtVal + } + s.UseSiteExchangeRate = temp.UseSiteExchangeRate + s.Description = temp.Description + s.AllowFractionalQuantities = temp.AllowFractionalQuantities + s.Subscription = temp.Subscription + s.DisplayOnHostedPage = temp.DisplayOnHostedPage + s.Interval = temp.Interval + s.IntervalUnit = temp.IntervalUnit + return nil +} + +// TODO +type subscriptionComponent struct { + Id *int `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Kind *ComponentKind `json:"kind,omitempty"` + UnitName *string `json:"unit_name,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + UnitBalance *int `json:"unit_balance,omitempty"` + Currency *string `json:"currency,omitempty"` + AllocatedQuantity *SubscriptionComponentAllocatedQuantity `json:"allocated_quantity,omitempty"` + PricingScheme Optional[SubscriptionComponentPricingScheme] `json:"pricing_scheme"` + ComponentId *int `json:"component_id,omitempty"` + ComponentHandle Optional[string] `json:"component_handle"` + SubscriptionId *int `json:"subscription_id,omitempty"` + Recurring *bool `json:"recurring,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + DowngradeCredit Optional[CreditType] `json:"downgrade_credit"` + ArchivedAt Optional[string] `json:"archived_at"` + PricePointId Optional[int] `json:"price_point_id"` + PricePointHandle Optional[string] `json:"price_point_handle"` + PricePointType *SubscriptionComponentPricePointType `json:"price_point_type,omitempty"` + PricePointName Optional[string] `json:"price_point_name"` + ProductFamilyId *int `json:"product_family_id,omitempty"` + ProductFamilyHandle *string `json:"product_family_handle,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + UseSiteExchangeRate Optional[bool] `json:"use_site_exchange_rate"` + Description Optional[string] `json:"description"` + AllowFractionalQuantities *bool `json:"allow_fractional_quantities,omitempty"` + Subscription *SubscriptionComponentSubscription `json:"subscription,omitempty"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` } diff --git a/models/subscription_component_allocated_quantity.go b/models/subscription_component_allocated_quantity.go new file mode 100644 index 00000000..9c50e2da --- /dev/null +++ b/models/subscription_component_allocated_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionComponentAllocatedQuantity represents a SubscriptionComponentAllocatedQuantity struct. +// This is a container for one-of cases. +type SubscriptionComponentAllocatedQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the SubscriptionComponentAllocatedQuantity object to a string representation. +func (s SubscriptionComponentAllocatedQuantity) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionComponentAllocatedQuantity. +// It customizes the JSON marshaling process for SubscriptionComponentAllocatedQuantity objects. +func (s *SubscriptionComponentAllocatedQuantity) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionComponentAllocatedQuantityContainer.From*` functions to initialize the SubscriptionComponentAllocatedQuantity object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionComponentAllocatedQuantity object to a map representation for JSON marshaling. +func (s *SubscriptionComponentAllocatedQuantity) toMap() any { + switch obj := s.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionComponentAllocatedQuantity. +// It customizes the JSON unmarshaling process for SubscriptionComponentAllocatedQuantity objects. +func (s *SubscriptionComponentAllocatedQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &s.isNumber), + NewTypeHolder(new(string), false, &s.isString), + ) + + s.value = result + return err +} + +func (s *SubscriptionComponentAllocatedQuantity) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +func (s *SubscriptionComponentAllocatedQuantity) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +// internalSubscriptionComponentAllocatedQuantity represents a subscriptionComponentAllocatedQuantity struct. +// This is a container for one-of cases. +type internalSubscriptionComponentAllocatedQuantity struct{} + +var SubscriptionComponentAllocatedQuantityContainer internalSubscriptionComponentAllocatedQuantity + +func (s *internalSubscriptionComponentAllocatedQuantity) FromNumber(val int) SubscriptionComponentAllocatedQuantity { + return SubscriptionComponentAllocatedQuantity{value: &val} +} + +func (s *internalSubscriptionComponentAllocatedQuantity) FromString(val string) SubscriptionComponentAllocatedQuantity { + return SubscriptionComponentAllocatedQuantity{value: &val} +} diff --git a/models/subscription_component_allocation_error_item.go b/models/subscription_component_allocation_error_item.go index 8f1e680e..3eeca2f9 100644 --- a/models/subscription_component_allocation_error_item.go +++ b/models/subscription_component_allocation_error_item.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionComponentAllocationErrorItem represents a SubscriptionComponentAllocationErrorItem struct. type SubscriptionComponentAllocationErrorItem struct { - Kind *string `json:"kind,omitempty"` - Message *string `json:"message,omitempty"` + Kind *string `json:"kind,omitempty"` + Message *string `json:"message,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionComponentAllocationErrorItem. +// MarshalJSON implements the json.Marshaler interface for SubscriptionComponentAllocationErrorItem. // It customizes the JSON marshaling process for SubscriptionComponentAllocationErrorItem objects. func (s *SubscriptionComponentAllocationErrorItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionComponentAllocationErrorItem object to a map representation for JSON marshaling. func (s *SubscriptionComponentAllocationErrorItem) toMap() map[string]any { - structMap := make(map[string]any) - if s.Kind != nil { - structMap["kind"] = s.Kind - } - if s.Message != nil { - structMap["message"] = s.Message - } - return structMap + structMap := make(map[string]any) + if s.Kind != nil { + structMap["kind"] = s.Kind + } + if s.Message != nil { + structMap["message"] = s.Message + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionComponentAllocationErrorItem. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionComponentAllocationErrorItem. // It customizes the JSON unmarshaling process for SubscriptionComponentAllocationErrorItem objects. func (s *SubscriptionComponentAllocationErrorItem) UnmarshalJSON(input []byte) error { - temp := &struct { - Kind *string `json:"kind,omitempty"` - Message *string `json:"message,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Kind = temp.Kind - s.Message = temp.Message - return nil + var temp subscriptionComponentAllocationErrorItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Kind = temp.Kind + s.Message = temp.Message + return nil +} + +// TODO +type subscriptionComponentAllocationErrorItem struct { + Kind *string `json:"kind,omitempty"` + Message *string `json:"message,omitempty"` } diff --git a/models/subscription_component_price_point_type.go b/models/subscription_component_price_point_type.go new file mode 100644 index 00000000..7450e07a --- /dev/null +++ b/models/subscription_component_price_point_type.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionComponentPricePointType represents a SubscriptionComponentPricePointType struct. +// This is a container for one-of cases. +type SubscriptionComponentPricePointType struct { + value any + isPricePointType bool +} + +// String converts the SubscriptionComponentPricePointType object to a string representation. +func (s SubscriptionComponentPricePointType) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionComponentPricePointType. +// It customizes the JSON marshaling process for SubscriptionComponentPricePointType objects. +func (s *SubscriptionComponentPricePointType) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionComponentPricePointTypeContainer.From*` functions to initialize the SubscriptionComponentPricePointType object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionComponentPricePointType object to a map representation for JSON marshaling. +func (s *SubscriptionComponentPricePointType) toMap() any { + switch obj := s.value.(type) { + case *PricePointType: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionComponentPricePointType. +// It customizes the JSON unmarshaling process for SubscriptionComponentPricePointType objects. +func (s *SubscriptionComponentPricePointType) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(PricePointType), false, &s.isPricePointType), + ) + + s.value = result + return err +} + +func (s *SubscriptionComponentPricePointType) AsPricePointType() ( + *PricePointType, + bool) { + if !s.isPricePointType { + return nil, false + } + return s.value.(*PricePointType), true +} + +// internalSubscriptionComponentPricePointType represents a subscriptionComponentPricePointType struct. +// This is a container for one-of cases. +type internalSubscriptionComponentPricePointType struct{} + +var SubscriptionComponentPricePointTypeContainer internalSubscriptionComponentPricePointType + +func (s *internalSubscriptionComponentPricePointType) FromPricePointType(val PricePointType) SubscriptionComponentPricePointType { + return SubscriptionComponentPricePointType{value: &val} +} diff --git a/models/subscription_component_pricing_scheme.go b/models/subscription_component_pricing_scheme.go new file mode 100644 index 00000000..0327d29f --- /dev/null +++ b/models/subscription_component_pricing_scheme.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionComponentPricingScheme represents a SubscriptionComponentPricingScheme struct. +// This is a container for one-of cases. +type SubscriptionComponentPricingScheme struct { + value any + isPricingScheme bool +} + +// String converts the SubscriptionComponentPricingScheme object to a string representation. +func (s SubscriptionComponentPricingScheme) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionComponentPricingScheme. +// It customizes the JSON marshaling process for SubscriptionComponentPricingScheme objects. +func (s *SubscriptionComponentPricingScheme) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionComponentPricingSchemeContainer.From*` functions to initialize the SubscriptionComponentPricingScheme object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionComponentPricingScheme object to a map representation for JSON marshaling. +func (s *SubscriptionComponentPricingScheme) toMap() any { + switch obj := s.value.(type) { + case *PricingScheme: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionComponentPricingScheme. +// It customizes the JSON unmarshaling process for SubscriptionComponentPricingScheme objects. +func (s *SubscriptionComponentPricingScheme) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(PricingScheme), false, &s.isPricingScheme), + ) + + s.value = result + return err +} + +func (s *SubscriptionComponentPricingScheme) AsPricingScheme() ( + *PricingScheme, + bool) { + if !s.isPricingScheme { + return nil, false + } + return s.value.(*PricingScheme), true +} + +// internalSubscriptionComponentPricingScheme represents a subscriptionComponentPricingScheme struct. +// This is a container for one-of cases. +type internalSubscriptionComponentPricingScheme struct{} + +var SubscriptionComponentPricingSchemeContainer internalSubscriptionComponentPricingScheme + +func (s *internalSubscriptionComponentPricingScheme) FromPricingScheme(val PricingScheme) SubscriptionComponentPricingScheme { + return SubscriptionComponentPricingScheme{value: &val} +} diff --git a/models/subscription_component_response.go b/models/subscription_component_response.go index fa93fc00..c235997d 100644 --- a/models/subscription_component_response.go +++ b/models/subscription_component_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionComponentResponse represents a SubscriptionComponentResponse struct. type SubscriptionComponentResponse struct { - Component *SubscriptionComponent `json:"component,omitempty"` + Component *SubscriptionComponent `json:"component,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionComponentResponse. +// MarshalJSON implements the json.Marshaler interface for SubscriptionComponentResponse. // It customizes the JSON marshaling process for SubscriptionComponentResponse objects. func (s *SubscriptionComponentResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionComponentResponse object to a map representation for JSON marshaling. func (s *SubscriptionComponentResponse) toMap() map[string]any { - structMap := make(map[string]any) - if s.Component != nil { - structMap["component"] = s.Component.toMap() - } - return structMap + structMap := make(map[string]any) + if s.Component != nil { + structMap["component"] = s.Component.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionComponentResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionComponentResponse. // It customizes the JSON unmarshaling process for SubscriptionComponentResponse objects. func (s *SubscriptionComponentResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Component *SubscriptionComponent `json:"component,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Component = temp.Component - return nil + var temp subscriptionComponentResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Component = temp.Component + return nil +} + +// TODO +type subscriptionComponentResponse struct { + Component *SubscriptionComponent `json:"component,omitempty"` } diff --git a/models/subscription_component_subscription.go b/models/subscription_component_subscription.go index cd69138a..bae7470b 100644 --- a/models/subscription_component_subscription.go +++ b/models/subscription_component_subscription.go @@ -1,77 +1,79 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) -// SubscriptionComponentSubscription represents a SubscriptionComponentSubscription struct. +// SubscriptionComponentSubscription represents a SubscriptionComponentSubscription struct. // An optional object, will be returned if provided `include=subscription` query param. type SubscriptionComponentSubscription struct { - // The state of a subscription. - // * **Live States** - // * `active` - A normal, active subscription. It is not in a trial and is paid and up to date. - // * `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed. - // * `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed. - // * `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state. - // * `paused` - An internal state that indicates that your account with Advanced Billing is in arrears. - // * **Problem States** - // * `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers. - // * `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed. - // * `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`. - // * **End of Life States** - // * `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription. - // While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance. - // * `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period. - // * `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.) - // * `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time. - // * `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state. - // * `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details. - // See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. - State *SubscriptionState `json:"state,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` + // The state of a subscription. + // * **Live States** + // * `active` - A normal, active subscription. It is not in a trial and is paid and up to date. + // * `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed. + // * `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed. + // * `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state. + // * `paused` - An internal state that indicates that your account with Advanced Billing is in arrears. + // * **Problem States** + // * `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers. + // * `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed. + // * `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`. + // * **End of Life States** + // * `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription. + // While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance. + // * `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period. + // * `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.) + // * `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time. + // * `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state. + // * `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details. + // See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. + State *SubscriptionState `json:"state,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionComponentSubscription. +// MarshalJSON implements the json.Marshaler interface for SubscriptionComponentSubscription. // It customizes the JSON marshaling process for SubscriptionComponentSubscription objects. func (s *SubscriptionComponentSubscription) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionComponentSubscription object to a map representation for JSON marshaling. func (s *SubscriptionComponentSubscription) toMap() map[string]any { - structMap := make(map[string]any) - if s.State != nil { - structMap["state"] = s.State - } - if s.UpdatedAt != nil { - structMap["updated_at"] = s.UpdatedAt.Format(time.RFC3339) - } - return structMap + structMap := make(map[string]any) + if s.State != nil { + structMap["state"] = s.State + } + if s.UpdatedAt != nil { + structMap["updated_at"] = s.UpdatedAt.Format(time.RFC3339) + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionComponentSubscription. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionComponentSubscription. // It customizes the JSON unmarshaling process for SubscriptionComponentSubscription objects. func (s *SubscriptionComponentSubscription) UnmarshalJSON(input []byte) error { - temp := &struct { - State *SubscriptionState `json:"state,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.State = temp.State - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - s.UpdatedAt = &UpdatedAtVal - } - return nil + var temp subscriptionComponentSubscription + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.State = temp.State + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + s.UpdatedAt = &UpdatedAtVal + } + return nil +} + +// TODO +type subscriptionComponentSubscription struct { + State *SubscriptionState `json:"state,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` } diff --git a/models/subscription_custom_price.go b/models/subscription_custom_price.go index 1d828341..3d3e4595 100644 --- a/models/subscription_custom_price.go +++ b/models/subscription_custom_price.go @@ -1,122 +1,148 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) -// SubscriptionCustomPrice represents a SubscriptionCustomPrice struct. +// SubscriptionCustomPrice represents a SubscriptionCustomPrice struct. // (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription type SubscriptionCustomPrice struct { - // (Optional) - Name *string `json:"name,omitempty"` - // (Optional) - Handle *string `json:"handle,omitempty"` - // Required if using `custom_price` attribute. - PriceInCents interface{} `json:"price_in_cents"` - // Required if using `custom_price` attribute. - Interval interface{} `json:"interval"` - // Required if using `custom_price` attribute. - IntervalUnit IntervalUnit `json:"interval_unit"` - // (Optional) - TrialPriceInCents *interface{} `json:"trial_price_in_cents,omitempty"` - // (Optional) - TrialInterval *interface{} `json:"trial_interval,omitempty"` - // (Optional) - TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` - // (Optional) - InitialChargeInCents *interface{} `json:"initial_charge_in_cents,omitempty"` - // (Optional) - InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` - // (Optional) - ExpirationInterval *interface{} `json:"expiration_interval,omitempty"` - // (Optional) - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` - // (Optional) - TaxIncluded *bool `json:"tax_included,omitempty"` + // (Optional) + Name *string `json:"name,omitempty"` + // (Optional) + Handle *string `json:"handle,omitempty"` + // Required if using `custom_price` attribute. + PriceInCents SubscriptionCustomPricePriceInCents `json:"price_in_cents"` + // Required if using `custom_price` attribute. + Interval SubscriptionCustomPriceInterval `json:"interval"` + // Required if using `custom_price` attribute. + IntervalUnit IntervalUnit `json:"interval_unit"` + // (Optional) + TrialPriceInCents *SubscriptionCustomPriceTrialPriceInCents `json:"trial_price_in_cents,omitempty"` + // (Optional) + TrialInterval *SubscriptionCustomPriceTrialInterval `json:"trial_interval,omitempty"` + // (Optional) + TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` + // (Optional) + InitialChargeInCents *SubscriptionCustomPriceInitialChargeInCents `json:"initial_charge_in_cents,omitempty"` + // (Optional) + InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` + // (Optional) + ExpirationInterval *SubscriptionCustomPriceExpirationInterval `json:"expiration_interval,omitempty"` + // (Optional) + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` + // (Optional) + TaxIncluded *bool `json:"tax_included,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionCustomPrice. +// MarshalJSON implements the json.Marshaler interface for SubscriptionCustomPrice. // It customizes the JSON marshaling process for SubscriptionCustomPrice objects. func (s *SubscriptionCustomPrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionCustomPrice object to a map representation for JSON marshaling. func (s *SubscriptionCustomPrice) toMap() map[string]any { - structMap := make(map[string]any) - if s.Name != nil { - structMap["name"] = s.Name - } - if s.Handle != nil { - structMap["handle"] = s.Handle - } - structMap["price_in_cents"] = s.PriceInCents - structMap["interval"] = s.Interval - structMap["interval_unit"] = s.IntervalUnit - if s.TrialPriceInCents != nil { - structMap["trial_price_in_cents"] = s.TrialPriceInCents - } - if s.TrialInterval != nil { - structMap["trial_interval"] = s.TrialInterval - } - if s.TrialIntervalUnit != nil { - structMap["trial_interval_unit"] = s.TrialIntervalUnit - } - if s.InitialChargeInCents != nil { - structMap["initial_charge_in_cents"] = s.InitialChargeInCents - } - if s.InitialChargeAfterTrial != nil { - structMap["initial_charge_after_trial"] = s.InitialChargeAfterTrial - } - if s.ExpirationInterval != nil { - structMap["expiration_interval"] = s.ExpirationInterval - } - if s.ExpirationIntervalUnit != nil { - structMap["expiration_interval_unit"] = s.ExpirationIntervalUnit - } - if s.TaxIncluded != nil { - structMap["tax_included"] = s.TaxIncluded - } - return structMap + structMap := make(map[string]any) + if s.Name != nil { + structMap["name"] = s.Name + } + if s.Handle != nil { + structMap["handle"] = s.Handle + } + structMap["price_in_cents"] = s.PriceInCents.toMap() + structMap["interval"] = s.Interval.toMap() + structMap["interval_unit"] = s.IntervalUnit + if s.TrialPriceInCents != nil { + structMap["trial_price_in_cents"] = s.TrialPriceInCents.toMap() + } + if s.TrialInterval != nil { + structMap["trial_interval"] = s.TrialInterval.toMap() + } + if s.TrialIntervalUnit != nil { + structMap["trial_interval_unit"] = s.TrialIntervalUnit + } + if s.InitialChargeInCents != nil { + structMap["initial_charge_in_cents"] = s.InitialChargeInCents.toMap() + } + if s.InitialChargeAfterTrial != nil { + structMap["initial_charge_after_trial"] = s.InitialChargeAfterTrial + } + if s.ExpirationInterval != nil { + structMap["expiration_interval"] = s.ExpirationInterval.toMap() + } + if s.ExpirationIntervalUnit != nil { + structMap["expiration_interval_unit"] = s.ExpirationIntervalUnit + } + if s.TaxIncluded != nil { + structMap["tax_included"] = s.TaxIncluded + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionCustomPrice. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionCustomPrice. // It customizes the JSON unmarshaling process for SubscriptionCustomPrice objects. func (s *SubscriptionCustomPrice) UnmarshalJSON(input []byte) error { - temp := &struct { - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - PriceInCents interface{} `json:"price_in_cents"` - Interval interface{} `json:"interval"` - IntervalUnit IntervalUnit `json:"interval_unit"` - TrialPriceInCents *interface{} `json:"trial_price_in_cents,omitempty"` - TrialInterval *interface{} `json:"trial_interval,omitempty"` - TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` - InitialChargeInCents *interface{} `json:"initial_charge_in_cents,omitempty"` - InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` - ExpirationInterval *interface{} `json:"expiration_interval,omitempty"` - ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` - TaxIncluded *bool `json:"tax_included,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Name = temp.Name - s.Handle = temp.Handle - s.PriceInCents = temp.PriceInCents - s.Interval = temp.Interval - s.IntervalUnit = temp.IntervalUnit - s.TrialPriceInCents = temp.TrialPriceInCents - s.TrialInterval = temp.TrialInterval - s.TrialIntervalUnit = temp.TrialIntervalUnit - s.InitialChargeInCents = temp.InitialChargeInCents - s.InitialChargeAfterTrial = temp.InitialChargeAfterTrial - s.ExpirationInterval = temp.ExpirationInterval - s.ExpirationIntervalUnit = temp.ExpirationIntervalUnit - s.TaxIncluded = temp.TaxIncluded - return nil + var temp subscriptionCustomPrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.Name = temp.Name + s.Handle = temp.Handle + s.PriceInCents = *temp.PriceInCents + s.Interval = *temp.Interval + s.IntervalUnit = *temp.IntervalUnit + s.TrialPriceInCents = temp.TrialPriceInCents + s.TrialInterval = temp.TrialInterval + s.TrialIntervalUnit = temp.TrialIntervalUnit + s.InitialChargeInCents = temp.InitialChargeInCents + s.InitialChargeAfterTrial = temp.InitialChargeAfterTrial + s.ExpirationInterval = temp.ExpirationInterval + s.ExpirationIntervalUnit = temp.ExpirationIntervalUnit + s.TaxIncluded = temp.TaxIncluded + return nil +} + +// TODO +type subscriptionCustomPrice struct { + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + PriceInCents *SubscriptionCustomPricePriceInCents `json:"price_in_cents"` + Interval *SubscriptionCustomPriceInterval `json:"interval"` + IntervalUnit *IntervalUnit `json:"interval_unit"` + TrialPriceInCents *SubscriptionCustomPriceTrialPriceInCents `json:"trial_price_in_cents,omitempty"` + TrialInterval *SubscriptionCustomPriceTrialInterval `json:"trial_interval,omitempty"` + TrialIntervalUnit *IntervalUnit `json:"trial_interval_unit,omitempty"` + InitialChargeInCents *SubscriptionCustomPriceInitialChargeInCents `json:"initial_charge_in_cents,omitempty"` + InitialChargeAfterTrial *bool `json:"initial_charge_after_trial,omitempty"` + ExpirationInterval *SubscriptionCustomPriceExpirationInterval `json:"expiration_interval,omitempty"` + ExpirationIntervalUnit *IntervalUnit `json:"expiration_interval_unit,omitempty"` + TaxIncluded *bool `json:"tax_included,omitempty"` +} + +func (s *subscriptionCustomPrice) validate() error { + var errs []string + if s.PriceInCents == nil { + errs = append(errs, "required field `price_in_cents` is missing for type `Subscription Custom Price`") + } + if s.Interval == nil { + errs = append(errs, "required field `interval` is missing for type `Subscription Custom Price`") + } + if s.IntervalUnit == nil { + errs = append(errs, "required field `interval_unit` is missing for type `Subscription Custom Price`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_custom_price_expiration_interval.go b/models/subscription_custom_price_expiration_interval.go new file mode 100644 index 00000000..6330655a --- /dev/null +++ b/models/subscription_custom_price_expiration_interval.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionCustomPriceExpirationInterval represents a SubscriptionCustomPriceExpirationInterval struct. +// This is a container for one-of cases. +type SubscriptionCustomPriceExpirationInterval struct { + value any + isString bool + isNumber bool +} + +// String converts the SubscriptionCustomPriceExpirationInterval object to a string representation. +func (s SubscriptionCustomPriceExpirationInterval) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionCustomPriceExpirationInterval. +// It customizes the JSON marshaling process for SubscriptionCustomPriceExpirationInterval objects. +func (s *SubscriptionCustomPriceExpirationInterval) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionCustomPriceExpirationIntervalContainer.From*` functions to initialize the SubscriptionCustomPriceExpirationInterval object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionCustomPriceExpirationInterval object to a map representation for JSON marshaling. +func (s *SubscriptionCustomPriceExpirationInterval) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionCustomPriceExpirationInterval. +// It customizes the JSON unmarshaling process for SubscriptionCustomPriceExpirationInterval objects. +func (s *SubscriptionCustomPriceExpirationInterval) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int), false, &s.isNumber), + ) + + s.value = result + return err +} + +func (s *SubscriptionCustomPriceExpirationInterval) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionCustomPriceExpirationInterval) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +// internalSubscriptionCustomPriceExpirationInterval represents a subscriptionCustomPriceExpirationInterval struct. +// This is a container for one-of cases. +type internalSubscriptionCustomPriceExpirationInterval struct{} + +var SubscriptionCustomPriceExpirationIntervalContainer internalSubscriptionCustomPriceExpirationInterval + +func (s *internalSubscriptionCustomPriceExpirationInterval) FromString(val string) SubscriptionCustomPriceExpirationInterval { + return SubscriptionCustomPriceExpirationInterval{value: &val} +} + +func (s *internalSubscriptionCustomPriceExpirationInterval) FromNumber(val int) SubscriptionCustomPriceExpirationInterval { + return SubscriptionCustomPriceExpirationInterval{value: &val} +} diff --git a/models/subscription_custom_price_initial_charge_in_cents.go b/models/subscription_custom_price_initial_charge_in_cents.go new file mode 100644 index 00000000..099f444e --- /dev/null +++ b/models/subscription_custom_price_initial_charge_in_cents.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionCustomPriceInitialChargeInCents represents a SubscriptionCustomPriceInitialChargeInCents struct. +// This is a container for one-of cases. +type SubscriptionCustomPriceInitialChargeInCents struct { + value any + isString bool + isLong bool +} + +// String converts the SubscriptionCustomPriceInitialChargeInCents object to a string representation. +func (s SubscriptionCustomPriceInitialChargeInCents) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionCustomPriceInitialChargeInCents. +// It customizes the JSON marshaling process for SubscriptionCustomPriceInitialChargeInCents objects. +func (s *SubscriptionCustomPriceInitialChargeInCents) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionCustomPriceInitialChargeInCentsContainer.From*` functions to initialize the SubscriptionCustomPriceInitialChargeInCents object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionCustomPriceInitialChargeInCents object to a map representation for JSON marshaling. +func (s *SubscriptionCustomPriceInitialChargeInCents) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionCustomPriceInitialChargeInCents. +// It customizes the JSON unmarshaling process for SubscriptionCustomPriceInitialChargeInCents objects. +func (s *SubscriptionCustomPriceInitialChargeInCents) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int64), false, &s.isLong), + ) + + s.value = result + return err +} + +func (s *SubscriptionCustomPriceInitialChargeInCents) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionCustomPriceInitialChargeInCents) AsLong() ( + *int64, + bool) { + if !s.isLong { + return nil, false + } + return s.value.(*int64), true +} + +// internalSubscriptionCustomPriceInitialChargeInCents represents a subscriptionCustomPriceInitialChargeInCents struct. +// This is a container for one-of cases. +type internalSubscriptionCustomPriceInitialChargeInCents struct{} + +var SubscriptionCustomPriceInitialChargeInCentsContainer internalSubscriptionCustomPriceInitialChargeInCents + +func (s *internalSubscriptionCustomPriceInitialChargeInCents) FromString(val string) SubscriptionCustomPriceInitialChargeInCents { + return SubscriptionCustomPriceInitialChargeInCents{value: &val} +} + +func (s *internalSubscriptionCustomPriceInitialChargeInCents) FromLong(val int64) SubscriptionCustomPriceInitialChargeInCents { + return SubscriptionCustomPriceInitialChargeInCents{value: &val} +} diff --git a/models/subscription_custom_price_interval.go b/models/subscription_custom_price_interval.go new file mode 100644 index 00000000..679a164d --- /dev/null +++ b/models/subscription_custom_price_interval.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionCustomPriceInterval represents a SubscriptionCustomPriceInterval struct. +// This is a container for one-of cases. +type SubscriptionCustomPriceInterval struct { + value any + isString bool + isNumber bool +} + +// String converts the SubscriptionCustomPriceInterval object to a string representation. +func (s SubscriptionCustomPriceInterval) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionCustomPriceInterval. +// It customizes the JSON marshaling process for SubscriptionCustomPriceInterval objects. +func (s *SubscriptionCustomPriceInterval) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionCustomPriceIntervalContainer.From*` functions to initialize the SubscriptionCustomPriceInterval object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionCustomPriceInterval object to a map representation for JSON marshaling. +func (s *SubscriptionCustomPriceInterval) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionCustomPriceInterval. +// It customizes the JSON unmarshaling process for SubscriptionCustomPriceInterval objects. +func (s *SubscriptionCustomPriceInterval) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int), false, &s.isNumber), + ) + + s.value = result + return err +} + +func (s *SubscriptionCustomPriceInterval) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionCustomPriceInterval) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +// internalSubscriptionCustomPriceInterval represents a subscriptionCustomPriceInterval struct. +// This is a container for one-of cases. +type internalSubscriptionCustomPriceInterval struct{} + +var SubscriptionCustomPriceIntervalContainer internalSubscriptionCustomPriceInterval + +func (s *internalSubscriptionCustomPriceInterval) FromString(val string) SubscriptionCustomPriceInterval { + return SubscriptionCustomPriceInterval{value: &val} +} + +func (s *internalSubscriptionCustomPriceInterval) FromNumber(val int) SubscriptionCustomPriceInterval { + return SubscriptionCustomPriceInterval{value: &val} +} diff --git a/models/subscription_custom_price_price_in_cents.go b/models/subscription_custom_price_price_in_cents.go new file mode 100644 index 00000000..e988cd64 --- /dev/null +++ b/models/subscription_custom_price_price_in_cents.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionCustomPricePriceInCents represents a SubscriptionCustomPricePriceInCents struct. +// This is a container for one-of cases. +type SubscriptionCustomPricePriceInCents struct { + value any + isString bool + isLong bool +} + +// String converts the SubscriptionCustomPricePriceInCents object to a string representation. +func (s SubscriptionCustomPricePriceInCents) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionCustomPricePriceInCents. +// It customizes the JSON marshaling process for SubscriptionCustomPricePriceInCents objects. +func (s *SubscriptionCustomPricePriceInCents) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionCustomPricePriceInCentsContainer.From*` functions to initialize the SubscriptionCustomPricePriceInCents object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionCustomPricePriceInCents object to a map representation for JSON marshaling. +func (s *SubscriptionCustomPricePriceInCents) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionCustomPricePriceInCents. +// It customizes the JSON unmarshaling process for SubscriptionCustomPricePriceInCents objects. +func (s *SubscriptionCustomPricePriceInCents) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int64), false, &s.isLong), + ) + + s.value = result + return err +} + +func (s *SubscriptionCustomPricePriceInCents) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionCustomPricePriceInCents) AsLong() ( + *int64, + bool) { + if !s.isLong { + return nil, false + } + return s.value.(*int64), true +} + +// internalSubscriptionCustomPricePriceInCents represents a subscriptionCustomPricePriceInCents struct. +// This is a container for one-of cases. +type internalSubscriptionCustomPricePriceInCents struct{} + +var SubscriptionCustomPricePriceInCentsContainer internalSubscriptionCustomPricePriceInCents + +func (s *internalSubscriptionCustomPricePriceInCents) FromString(val string) SubscriptionCustomPricePriceInCents { + return SubscriptionCustomPricePriceInCents{value: &val} +} + +func (s *internalSubscriptionCustomPricePriceInCents) FromLong(val int64) SubscriptionCustomPricePriceInCents { + return SubscriptionCustomPricePriceInCents{value: &val} +} diff --git a/models/subscription_custom_price_trial_interval.go b/models/subscription_custom_price_trial_interval.go new file mode 100644 index 00000000..8d715a1d --- /dev/null +++ b/models/subscription_custom_price_trial_interval.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionCustomPriceTrialInterval represents a SubscriptionCustomPriceTrialInterval struct. +// This is a container for one-of cases. +type SubscriptionCustomPriceTrialInterval struct { + value any + isString bool + isNumber bool +} + +// String converts the SubscriptionCustomPriceTrialInterval object to a string representation. +func (s SubscriptionCustomPriceTrialInterval) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionCustomPriceTrialInterval. +// It customizes the JSON marshaling process for SubscriptionCustomPriceTrialInterval objects. +func (s *SubscriptionCustomPriceTrialInterval) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionCustomPriceTrialIntervalContainer.From*` functions to initialize the SubscriptionCustomPriceTrialInterval object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionCustomPriceTrialInterval object to a map representation for JSON marshaling. +func (s *SubscriptionCustomPriceTrialInterval) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionCustomPriceTrialInterval. +// It customizes the JSON unmarshaling process for SubscriptionCustomPriceTrialInterval objects. +func (s *SubscriptionCustomPriceTrialInterval) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int), false, &s.isNumber), + ) + + s.value = result + return err +} + +func (s *SubscriptionCustomPriceTrialInterval) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionCustomPriceTrialInterval) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +// internalSubscriptionCustomPriceTrialInterval represents a subscriptionCustomPriceTrialInterval struct. +// This is a container for one-of cases. +type internalSubscriptionCustomPriceTrialInterval struct{} + +var SubscriptionCustomPriceTrialIntervalContainer internalSubscriptionCustomPriceTrialInterval + +func (s *internalSubscriptionCustomPriceTrialInterval) FromString(val string) SubscriptionCustomPriceTrialInterval { + return SubscriptionCustomPriceTrialInterval{value: &val} +} + +func (s *internalSubscriptionCustomPriceTrialInterval) FromNumber(val int) SubscriptionCustomPriceTrialInterval { + return SubscriptionCustomPriceTrialInterval{value: &val} +} diff --git a/models/subscription_custom_price_trial_price_in_cents.go b/models/subscription_custom_price_trial_price_in_cents.go new file mode 100644 index 00000000..b1eda83a --- /dev/null +++ b/models/subscription_custom_price_trial_price_in_cents.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionCustomPriceTrialPriceInCents represents a SubscriptionCustomPriceTrialPriceInCents struct. +// This is a container for one-of cases. +type SubscriptionCustomPriceTrialPriceInCents struct { + value any + isString bool + isLong bool +} + +// String converts the SubscriptionCustomPriceTrialPriceInCents object to a string representation. +func (s SubscriptionCustomPriceTrialPriceInCents) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionCustomPriceTrialPriceInCents. +// It customizes the JSON marshaling process for SubscriptionCustomPriceTrialPriceInCents objects. +func (s *SubscriptionCustomPriceTrialPriceInCents) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionCustomPriceTrialPriceInCentsContainer.From*` functions to initialize the SubscriptionCustomPriceTrialPriceInCents object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionCustomPriceTrialPriceInCents object to a map representation for JSON marshaling. +func (s *SubscriptionCustomPriceTrialPriceInCents) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int64: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionCustomPriceTrialPriceInCents. +// It customizes the JSON unmarshaling process for SubscriptionCustomPriceTrialPriceInCents objects. +func (s *SubscriptionCustomPriceTrialPriceInCents) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int64), false, &s.isLong), + ) + + s.value = result + return err +} + +func (s *SubscriptionCustomPriceTrialPriceInCents) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionCustomPriceTrialPriceInCents) AsLong() ( + *int64, + bool) { + if !s.isLong { + return nil, false + } + return s.value.(*int64), true +} + +// internalSubscriptionCustomPriceTrialPriceInCents represents a subscriptionCustomPriceTrialPriceInCents struct. +// This is a container for one-of cases. +type internalSubscriptionCustomPriceTrialPriceInCents struct{} + +var SubscriptionCustomPriceTrialPriceInCentsContainer internalSubscriptionCustomPriceTrialPriceInCents + +func (s *internalSubscriptionCustomPriceTrialPriceInCents) FromString(val string) SubscriptionCustomPriceTrialPriceInCents { + return SubscriptionCustomPriceTrialPriceInCents{value: &val} +} + +func (s *internalSubscriptionCustomPriceTrialPriceInCents) FromLong(val int64) SubscriptionCustomPriceTrialPriceInCents { + return SubscriptionCustomPriceTrialPriceInCents{value: &val} +} diff --git a/models/subscription_group.go b/models/subscription_group.go index 921078cc..51481e07 100644 --- a/models/subscription_group.go +++ b/models/subscription_group.go @@ -1,74 +1,77 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // SubscriptionGroup represents a SubscriptionGroup struct. type SubscriptionGroup struct { - CustomerId *int `json:"customer_id,omitempty"` - PaymentProfile *SubscriptionGroupPaymentProfile `json:"payment_profile,omitempty"` - PaymentCollectionMethod *string `json:"payment_collection_method,omitempty"` - SubscriptionIds []int `json:"subscription_ids,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaymentProfile *SubscriptionGroupPaymentProfile `json:"payment_profile,omitempty"` + // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` + SubscriptionIds []int `json:"subscription_ids,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroup. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroup. // It customizes the JSON marshaling process for SubscriptionGroup objects. func (s *SubscriptionGroup) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroup object to a map representation for JSON marshaling. func (s *SubscriptionGroup) toMap() map[string]any { - structMap := make(map[string]any) - if s.CustomerId != nil { - structMap["customer_id"] = s.CustomerId - } - if s.PaymentProfile != nil { - structMap["payment_profile"] = s.PaymentProfile.toMap() - } - if s.PaymentCollectionMethod != nil { - structMap["payment_collection_method"] = s.PaymentCollectionMethod - } - if s.SubscriptionIds != nil { - structMap["subscription_ids"] = s.SubscriptionIds - } - if s.CreatedAt != nil { - structMap["created_at"] = s.CreatedAt.Format(time.RFC3339) - } - return structMap + structMap := make(map[string]any) + if s.CustomerId != nil { + structMap["customer_id"] = s.CustomerId + } + if s.PaymentProfile != nil { + structMap["payment_profile"] = s.PaymentProfile.toMap() + } + if s.PaymentCollectionMethod != nil { + structMap["payment_collection_method"] = s.PaymentCollectionMethod + } + if s.SubscriptionIds != nil { + structMap["subscription_ids"] = s.SubscriptionIds + } + if s.CreatedAt != nil { + structMap["created_at"] = s.CreatedAt.Format(time.RFC3339) + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroup. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroup. // It customizes the JSON unmarshaling process for SubscriptionGroup objects. func (s *SubscriptionGroup) UnmarshalJSON(input []byte) error { - temp := &struct { - CustomerId *int `json:"customer_id,omitempty"` - PaymentProfile *SubscriptionGroupPaymentProfile `json:"payment_profile,omitempty"` - PaymentCollectionMethod *string `json:"payment_collection_method,omitempty"` - SubscriptionIds []int `json:"subscription_ids,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.CustomerId = temp.CustomerId - s.PaymentProfile = temp.PaymentProfile - s.PaymentCollectionMethod = temp.PaymentCollectionMethod - s.SubscriptionIds = temp.SubscriptionIds - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - s.CreatedAt = &CreatedAtVal - } - return nil + var temp subscriptionGroup + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.CustomerId = temp.CustomerId + s.PaymentProfile = temp.PaymentProfile + s.PaymentCollectionMethod = temp.PaymentCollectionMethod + s.SubscriptionIds = temp.SubscriptionIds + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + s.CreatedAt = &CreatedAtVal + } + return nil +} + +// TODO +type subscriptionGroup struct { + CustomerId *int `json:"customer_id,omitempty"` + PaymentProfile *SubscriptionGroupPaymentProfile `json:"payment_profile,omitempty"` + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` + SubscriptionIds []int `json:"subscription_ids,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` } diff --git a/models/subscription_group_2.go b/models/subscription_group_2.go new file mode 100644 index 00000000..a45d1241 --- /dev/null +++ b/models/subscription_group_2.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroup2 represents a SubscriptionGroup2 struct. +// This is a container for one-of cases. +type SubscriptionGroup2 struct { + value any + isNestedSubscriptionGroup bool +} + +// String converts the SubscriptionGroup2 object to a string representation. +func (s SubscriptionGroup2) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroup2. +// It customizes the JSON marshaling process for SubscriptionGroup2 objects. +func (s *SubscriptionGroup2) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionGroup2Container.From*` functions to initialize the SubscriptionGroup2 object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroup2 object to a map representation for JSON marshaling. +func (s *SubscriptionGroup2) toMap() any { + switch obj := s.value.(type) { + case *NestedSubscriptionGroup: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroup2. +// It customizes the JSON unmarshaling process for SubscriptionGroup2 objects. +func (s *SubscriptionGroup2) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&NestedSubscriptionGroup{}, false, &s.isNestedSubscriptionGroup), + ) + + s.value = result + return err +} + +func (s *SubscriptionGroup2) AsNestedSubscriptionGroup() ( + *NestedSubscriptionGroup, + bool) { + if !s.isNestedSubscriptionGroup { + return nil, false + } + return s.value.(*NestedSubscriptionGroup), true +} + +// internalSubscriptionGroup2 represents a subscriptionGroup2 struct. +// This is a container for one-of cases. +type internalSubscriptionGroup2 struct{} + +var SubscriptionGroup2Container internalSubscriptionGroup2 + +func (s *internalSubscriptionGroup2) FromNestedSubscriptionGroup(val NestedSubscriptionGroup) SubscriptionGroup2 { + return SubscriptionGroup2{value: &val} +} diff --git a/models/subscription_group_balances.go b/models/subscription_group_balances.go index 1da5d58e..55b1a2d0 100644 --- a/models/subscription_group_balances.go +++ b/models/subscription_group_balances.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupBalances represents a SubscriptionGroupBalances struct. type SubscriptionGroupBalances struct { - Prepayments *AccountBalance `json:"prepayments,omitempty"` - ServiceCredits *AccountBalance `json:"service_credits,omitempty"` - OpenInvoices *AccountBalance `json:"open_invoices,omitempty"` - PendingDiscounts *AccountBalance `json:"pending_discounts,omitempty"` + Prepayments *AccountBalance `json:"prepayments,omitempty"` + ServiceCredits *AccountBalance `json:"service_credits,omitempty"` + OpenInvoices *AccountBalance `json:"open_invoices,omitempty"` + PendingDiscounts *AccountBalance `json:"pending_discounts,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupBalances. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupBalances. // It customizes the JSON marshaling process for SubscriptionGroupBalances objects. func (s *SubscriptionGroupBalances) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupBalances object to a map representation for JSON marshaling. func (s *SubscriptionGroupBalances) toMap() map[string]any { - structMap := make(map[string]any) - if s.Prepayments != nil { - structMap["prepayments"] = s.Prepayments.toMap() - } - if s.ServiceCredits != nil { - structMap["service_credits"] = s.ServiceCredits.toMap() - } - if s.OpenInvoices != nil { - structMap["open_invoices"] = s.OpenInvoices.toMap() - } - if s.PendingDiscounts != nil { - structMap["pending_discounts"] = s.PendingDiscounts.toMap() - } - return structMap + structMap := make(map[string]any) + if s.Prepayments != nil { + structMap["prepayments"] = s.Prepayments.toMap() + } + if s.ServiceCredits != nil { + structMap["service_credits"] = s.ServiceCredits.toMap() + } + if s.OpenInvoices != nil { + structMap["open_invoices"] = s.OpenInvoices.toMap() + } + if s.PendingDiscounts != nil { + structMap["pending_discounts"] = s.PendingDiscounts.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupBalances. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupBalances. // It customizes the JSON unmarshaling process for SubscriptionGroupBalances objects. func (s *SubscriptionGroupBalances) UnmarshalJSON(input []byte) error { - temp := &struct { - Prepayments *AccountBalance `json:"prepayments,omitempty"` - ServiceCredits *AccountBalance `json:"service_credits,omitempty"` - OpenInvoices *AccountBalance `json:"open_invoices,omitempty"` - PendingDiscounts *AccountBalance `json:"pending_discounts,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Prepayments = temp.Prepayments - s.ServiceCredits = temp.ServiceCredits - s.OpenInvoices = temp.OpenInvoices - s.PendingDiscounts = temp.PendingDiscounts - return nil + var temp subscriptionGroupBalances + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Prepayments = temp.Prepayments + s.ServiceCredits = temp.ServiceCredits + s.OpenInvoices = temp.OpenInvoices + s.PendingDiscounts = temp.PendingDiscounts + return nil +} + +// TODO +type subscriptionGroupBalances struct { + Prepayments *AccountBalance `json:"prepayments,omitempty"` + ServiceCredits *AccountBalance `json:"service_credits,omitempty"` + OpenInvoices *AccountBalance `json:"open_invoices,omitempty"` + PendingDiscounts *AccountBalance `json:"pending_discounts,omitempty"` } diff --git a/models/subscription_group_bank_account.go b/models/subscription_group_bank_account.go index 422590bd..c13b22ae 100644 --- a/models/subscription_group_bank_account.go +++ b/models/subscription_group_bank_account.go @@ -1,140 +1,142 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupBankAccount represents a SubscriptionGroupBankAccount struct. type SubscriptionGroupBankAccount struct { - // (Required when creating a subscription with ACH or GoCardless) The name of the bank where the customer’s account resides - BankName *string `json:"bank_name,omitempty"` - // (Required when creating a subscription with ACH. Required when creating a subscription with GoCardless and bank_iban is blank) The customerʼs bank account number - BankAccountNumber *string `json:"bank_account_number,omitempty"` - // (Required when creating a subscription with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API - BankRoutingNumber *string `json:"bank_routing_number,omitempty"` - // (Optional when creating a subscription with GoCardless). International Bank Account Number. Alternatively, local bank details can be provided - BankIban *string `json:"bank_iban,omitempty"` - // (Optional when creating a subscription with GoCardless) Branch code. Alternatively, an IBAN can be provided - BankBranchCode *string `json:"bank_branch_code,omitempty"` - // Defaults to checking - BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` - // Defaults to personal - BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` - PaymentType *PaymentType `json:"payment_type,omitempty"` - BillingAddress *string `json:"billing_address,omitempty"` - BillingCity *string `json:"billing_city,omitempty"` - BillingState *string `json:"billing_state,omitempty"` - BillingZip *string `json:"billing_zip,omitempty"` - BillingCountry *string `json:"billing_country,omitempty"` - ChargifyToken *string `json:"chargify_token,omitempty"` - // The vault that stores the payment profile with the provided vault_token. - CurrentVault *BankAccountVault `json:"current_vault,omitempty"` - GatewayHandle *string `json:"gateway_handle,omitempty"` + // (Required when creating a subscription with ACH or GoCardless) The name of the bank where the customer’s account resides + BankName *string `json:"bank_name,omitempty"` + // (Required when creating a subscription with ACH. Required when creating a subscription with GoCardless and bank_iban is blank) The customerʼs bank account number + BankAccountNumber *string `json:"bank_account_number,omitempty"` + // (Required when creating a subscription with ACH. Optional when creating a subscription with GoCardless). The routing number of the bank. It becomes bank_code while passing via GoCardless API + BankRoutingNumber *string `json:"bank_routing_number,omitempty"` + // (Optional when creating a subscription with GoCardless). International Bank Account Number. Alternatively, local bank details can be provided + BankIban *string `json:"bank_iban,omitempty"` + // (Optional when creating a subscription with GoCardless) Branch code. Alternatively, an IBAN can be provided + BankBranchCode *string `json:"bank_branch_code,omitempty"` + // Defaults to checking + BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` + // Defaults to personal + BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` + PaymentType *PaymentType `json:"payment_type,omitempty"` + BillingAddress *string `json:"billing_address,omitempty"` + BillingCity *string `json:"billing_city,omitempty"` + BillingState *string `json:"billing_state,omitempty"` + BillingZip *string `json:"billing_zip,omitempty"` + BillingCountry *string `json:"billing_country,omitempty"` + ChargifyToken *string `json:"chargify_token,omitempty"` + // The vault that stores the payment profile with the provided vault_token. + CurrentVault *BankAccountVault `json:"current_vault,omitempty"` + GatewayHandle *string `json:"gateway_handle,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupBankAccount. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupBankAccount. // It customizes the JSON marshaling process for SubscriptionGroupBankAccount objects. func (s *SubscriptionGroupBankAccount) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupBankAccount object to a map representation for JSON marshaling. func (s *SubscriptionGroupBankAccount) toMap() map[string]any { - structMap := make(map[string]any) - if s.BankName != nil { - structMap["bank_name"] = s.BankName - } - if s.BankAccountNumber != nil { - structMap["bank_account_number"] = s.BankAccountNumber - } - if s.BankRoutingNumber != nil { - structMap["bank_routing_number"] = s.BankRoutingNumber - } - if s.BankIban != nil { - structMap["bank_iban"] = s.BankIban - } - if s.BankBranchCode != nil { - structMap["bank_branch_code"] = s.BankBranchCode - } - if s.BankAccountType != nil { - structMap["bank_account_type"] = s.BankAccountType - } - if s.BankAccountHolderType != nil { - structMap["bank_account_holder_type"] = s.BankAccountHolderType - } - if s.PaymentType != nil { - structMap["payment_type"] = s.PaymentType - } - if s.BillingAddress != nil { - structMap["billing_address"] = s.BillingAddress - } - if s.BillingCity != nil { - structMap["billing_city"] = s.BillingCity - } - if s.BillingState != nil { - structMap["billing_state"] = s.BillingState - } - if s.BillingZip != nil { - structMap["billing_zip"] = s.BillingZip - } - if s.BillingCountry != nil { - structMap["billing_country"] = s.BillingCountry - } - if s.ChargifyToken != nil { - structMap["chargify_token"] = s.ChargifyToken - } - if s.CurrentVault != nil { - structMap["current_vault"] = s.CurrentVault - } - if s.GatewayHandle != nil { - structMap["gateway_handle"] = s.GatewayHandle - } - return structMap + structMap := make(map[string]any) + if s.BankName != nil { + structMap["bank_name"] = s.BankName + } + if s.BankAccountNumber != nil { + structMap["bank_account_number"] = s.BankAccountNumber + } + if s.BankRoutingNumber != nil { + structMap["bank_routing_number"] = s.BankRoutingNumber + } + if s.BankIban != nil { + structMap["bank_iban"] = s.BankIban + } + if s.BankBranchCode != nil { + structMap["bank_branch_code"] = s.BankBranchCode + } + if s.BankAccountType != nil { + structMap["bank_account_type"] = s.BankAccountType + } + if s.BankAccountHolderType != nil { + structMap["bank_account_holder_type"] = s.BankAccountHolderType + } + if s.PaymentType != nil { + structMap["payment_type"] = s.PaymentType + } + if s.BillingAddress != nil { + structMap["billing_address"] = s.BillingAddress + } + if s.BillingCity != nil { + structMap["billing_city"] = s.BillingCity + } + if s.BillingState != nil { + structMap["billing_state"] = s.BillingState + } + if s.BillingZip != nil { + structMap["billing_zip"] = s.BillingZip + } + if s.BillingCountry != nil { + structMap["billing_country"] = s.BillingCountry + } + if s.ChargifyToken != nil { + structMap["chargify_token"] = s.ChargifyToken + } + if s.CurrentVault != nil { + structMap["current_vault"] = s.CurrentVault + } + if s.GatewayHandle != nil { + structMap["gateway_handle"] = s.GatewayHandle + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupBankAccount. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupBankAccount. // It customizes the JSON unmarshaling process for SubscriptionGroupBankAccount objects. func (s *SubscriptionGroupBankAccount) UnmarshalJSON(input []byte) error { - temp := &struct { - BankName *string `json:"bank_name,omitempty"` - BankAccountNumber *string `json:"bank_account_number,omitempty"` - BankRoutingNumber *string `json:"bank_routing_number,omitempty"` - BankIban *string `json:"bank_iban,omitempty"` - BankBranchCode *string `json:"bank_branch_code,omitempty"` - BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` - BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` - PaymentType *PaymentType `json:"payment_type,omitempty"` - BillingAddress *string `json:"billing_address,omitempty"` - BillingCity *string `json:"billing_city,omitempty"` - BillingState *string `json:"billing_state,omitempty"` - BillingZip *string `json:"billing_zip,omitempty"` - BillingCountry *string `json:"billing_country,omitempty"` - ChargifyToken *string `json:"chargify_token,omitempty"` - CurrentVault *BankAccountVault `json:"current_vault,omitempty"` - GatewayHandle *string `json:"gateway_handle,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.BankName = temp.BankName - s.BankAccountNumber = temp.BankAccountNumber - s.BankRoutingNumber = temp.BankRoutingNumber - s.BankIban = temp.BankIban - s.BankBranchCode = temp.BankBranchCode - s.BankAccountType = temp.BankAccountType - s.BankAccountHolderType = temp.BankAccountHolderType - s.PaymentType = temp.PaymentType - s.BillingAddress = temp.BillingAddress - s.BillingCity = temp.BillingCity - s.BillingState = temp.BillingState - s.BillingZip = temp.BillingZip - s.BillingCountry = temp.BillingCountry - s.ChargifyToken = temp.ChargifyToken - s.CurrentVault = temp.CurrentVault - s.GatewayHandle = temp.GatewayHandle - return nil + var temp subscriptionGroupBankAccount + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.BankName = temp.BankName + s.BankAccountNumber = temp.BankAccountNumber + s.BankRoutingNumber = temp.BankRoutingNumber + s.BankIban = temp.BankIban + s.BankBranchCode = temp.BankBranchCode + s.BankAccountType = temp.BankAccountType + s.BankAccountHolderType = temp.BankAccountHolderType + s.PaymentType = temp.PaymentType + s.BillingAddress = temp.BillingAddress + s.BillingCity = temp.BillingCity + s.BillingState = temp.BillingState + s.BillingZip = temp.BillingZip + s.BillingCountry = temp.BillingCountry + s.ChargifyToken = temp.ChargifyToken + s.CurrentVault = temp.CurrentVault + s.GatewayHandle = temp.GatewayHandle + return nil +} + +// TODO +type subscriptionGroupBankAccount struct { + BankName *string `json:"bank_name,omitempty"` + BankAccountNumber *string `json:"bank_account_number,omitempty"` + BankRoutingNumber *string `json:"bank_routing_number,omitempty"` + BankIban *string `json:"bank_iban,omitempty"` + BankBranchCode *string `json:"bank_branch_code,omitempty"` + BankAccountType *BankAccountType `json:"bank_account_type,omitempty"` + BankAccountHolderType *BankAccountHolderType `json:"bank_account_holder_type,omitempty"` + PaymentType *PaymentType `json:"payment_type,omitempty"` + BillingAddress *string `json:"billing_address,omitempty"` + BillingCity *string `json:"billing_city,omitempty"` + BillingState *string `json:"billing_state,omitempty"` + BillingZip *string `json:"billing_zip,omitempty"` + BillingCountry *string `json:"billing_country,omitempty"` + ChargifyToken *string `json:"chargify_token,omitempty"` + CurrentVault *BankAccountVault `json:"current_vault,omitempty"` + GatewayHandle *string `json:"gateway_handle,omitempty"` } diff --git a/models/subscription_group_component_custom_price.go b/models/subscription_group_component_custom_price.go index b7000ddd..3964b8b9 100644 --- a/models/subscription_group_component_custom_price.go +++ b/models/subscription_group_component_custom_price.go @@ -1,56 +1,58 @@ package models import ( - "encoding/json" + "encoding/json" ) -// SubscriptionGroupComponentCustomPrice represents a SubscriptionGroupComponentCustomPrice struct. +// SubscriptionGroupComponentCustomPrice represents a SubscriptionGroupComponentCustomPrice struct. // Used in place of `price_point_id` to define a custom price point unique to the subscription. You still need to provide `component_id`. type SubscriptionGroupComponentCustomPrice struct { - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - Prices []Price `json:"prices,omitempty"` - OveragePricing []ComponentCustomPrice `json:"overage_pricing,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + Prices []Price `json:"prices,omitempty"` + OveragePricing []ComponentCustomPrice `json:"overage_pricing,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupComponentCustomPrice. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupComponentCustomPrice. // It customizes the JSON marshaling process for SubscriptionGroupComponentCustomPrice objects. func (s *SubscriptionGroupComponentCustomPrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupComponentCustomPrice object to a map representation for JSON marshaling. func (s *SubscriptionGroupComponentCustomPrice) toMap() map[string]any { - structMap := make(map[string]any) - if s.PricingScheme != nil { - structMap["pricing_scheme"] = s.PricingScheme - } - if s.Prices != nil { - structMap["prices"] = s.Prices - } - if s.OveragePricing != nil { - structMap["overage_pricing"] = s.OveragePricing - } - return structMap + structMap := make(map[string]any) + if s.PricingScheme != nil { + structMap["pricing_scheme"] = s.PricingScheme + } + if s.Prices != nil { + structMap["prices"] = s.Prices + } + if s.OveragePricing != nil { + structMap["overage_pricing"] = s.OveragePricing + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupComponentCustomPrice. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupComponentCustomPrice. // It customizes the JSON unmarshaling process for SubscriptionGroupComponentCustomPrice objects. func (s *SubscriptionGroupComponentCustomPrice) UnmarshalJSON(input []byte) error { - temp := &struct { - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - Prices []Price `json:"prices,omitempty"` - OveragePricing []ComponentCustomPrice `json:"overage_pricing,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.PricingScheme = temp.PricingScheme - s.Prices = temp.Prices - s.OveragePricing = temp.OveragePricing - return nil + var temp subscriptionGroupComponentCustomPrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.PricingScheme = temp.PricingScheme + s.Prices = temp.Prices + s.OveragePricing = temp.OveragePricing + return nil +} + +// TODO +type subscriptionGroupComponentCustomPrice struct { + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + Prices []Price `json:"prices,omitempty"` + OveragePricing []ComponentCustomPrice `json:"overage_pricing,omitempty"` } diff --git a/models/subscription_group_create_error_response_errors.go b/models/subscription_group_create_error_response_errors.go new file mode 100644 index 00000000..167bc6f1 --- /dev/null +++ b/models/subscription_group_create_error_response_errors.go @@ -0,0 +1,111 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupCreateErrorResponseErrors represents a SubscriptionGroupCreateErrorResponseErrors struct. +// This is a container for one-of cases. +type SubscriptionGroupCreateErrorResponseErrors struct { + value any + isSubscriptionGroupMembersArrayError bool + isSubscriptionGroupSingleError bool + isString bool +} + +// String converts the SubscriptionGroupCreateErrorResponseErrors object to a string representation. +func (s SubscriptionGroupCreateErrorResponseErrors) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupCreateErrorResponseErrors. +// It customizes the JSON marshaling process for SubscriptionGroupCreateErrorResponseErrors objects. +func (s *SubscriptionGroupCreateErrorResponseErrors) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionGroupCreateErrorResponseErrorsContainer.From*` functions to initialize the SubscriptionGroupCreateErrorResponseErrors object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupCreateErrorResponseErrors object to a map representation for JSON marshaling. +func (s *SubscriptionGroupCreateErrorResponseErrors) toMap() any { + switch obj := s.value.(type) { + case *SubscriptionGroupMembersArrayError: + return obj.toMap() + case *SubscriptionGroupSingleError: + return obj.toMap() + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupCreateErrorResponseErrors. +// It customizes the JSON unmarshaling process for SubscriptionGroupCreateErrorResponseErrors objects. +func (s *SubscriptionGroupCreateErrorResponseErrors) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&SubscriptionGroupMembersArrayError{}, false, &s.isSubscriptionGroupMembersArrayError), + NewTypeHolder(&SubscriptionGroupSingleError{}, false, &s.isSubscriptionGroupSingleError), + NewTypeHolder(new(string), false, &s.isString), + ) + + s.value = result + return err +} + +func (s *SubscriptionGroupCreateErrorResponseErrors) AsSubscriptionGroupMembersArrayError() ( + *SubscriptionGroupMembersArrayError, + bool) { + if !s.isSubscriptionGroupMembersArrayError { + return nil, false + } + return s.value.(*SubscriptionGroupMembersArrayError), true +} + +func (s *SubscriptionGroupCreateErrorResponseErrors) AsSubscriptionGroupSingleError() ( + *SubscriptionGroupSingleError, + bool) { + if !s.isSubscriptionGroupSingleError { + return nil, false + } + return s.value.(*SubscriptionGroupSingleError), true +} + +func (s *SubscriptionGroupCreateErrorResponseErrors) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +// internalSubscriptionGroupCreateErrorResponseErrors represents a subscriptionGroupCreateErrorResponseErrors struct. +// This is a container for one-of cases. +type internalSubscriptionGroupCreateErrorResponseErrors struct{} + +var SubscriptionGroupCreateErrorResponseErrorsContainer internalSubscriptionGroupCreateErrorResponseErrors + +func (s *internalSubscriptionGroupCreateErrorResponseErrors) FromSubscriptionGroupMembersArrayError(val SubscriptionGroupMembersArrayError) SubscriptionGroupCreateErrorResponseErrors { + return SubscriptionGroupCreateErrorResponseErrors{value: &val} +} + +func (s *internalSubscriptionGroupCreateErrorResponseErrors) FromSubscriptionGroupSingleError(val SubscriptionGroupSingleError) SubscriptionGroupCreateErrorResponseErrors { + return SubscriptionGroupCreateErrorResponseErrors{value: &val} +} + +func (s *internalSubscriptionGroupCreateErrorResponseErrors) FromString(val string) SubscriptionGroupCreateErrorResponseErrors { + return SubscriptionGroupCreateErrorResponseErrors{value: &val} +} diff --git a/models/subscription_group_credit_card.go b/models/subscription_group_credit_card.go index 30b7fe49..e16e74f4 100644 --- a/models/subscription_group_credit_card.go +++ b/models/subscription_group_credit_card.go @@ -1,158 +1,160 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupCreditCard represents a SubscriptionGroupCreditCard struct. type SubscriptionGroupCreditCard struct { - FullNumber *interface{} `json:"full_number,omitempty"` - ExpirationMonth *interface{} `json:"expiration_month,omitempty"` - ExpirationYear *interface{} `json:"expiration_year,omitempty"` - ChargifyToken *string `json:"chargify_token,omitempty"` - VaultToken *string `json:"vault_token,omitempty"` - // The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. - CurrentVault *CurrentVault `json:"current_vault,omitempty"` - GatewayHandle *string `json:"gateway_handle,omitempty"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - BillingAddress *string `json:"billing_address,omitempty"` - BillingAddress2 *string `json:"billing_address_2,omitempty"` - BillingCity *string `json:"billing_city,omitempty"` - BillingState *string `json:"billing_state,omitempty"` - BillingZip *string `json:"billing_zip,omitempty"` - BillingCountry *string `json:"billing_country,omitempty"` - LastFour *string `json:"last_four,omitempty"` - // The type of card used. - CardType *CardType `json:"card_type,omitempty"` - CustomerVaultToken *string `json:"customer_vault_token,omitempty"` - Cvv *string `json:"cvv,omitempty"` - PaymentType *string `json:"payment_type,omitempty"` + FullNumber *SubscriptionGroupCreditCardFullNumber `json:"full_number,omitempty"` + ExpirationMonth *SubscriptionGroupCreditCardExpirationMonth `json:"expiration_month,omitempty"` + ExpirationYear *SubscriptionGroupCreditCardExpirationYear `json:"expiration_year,omitempty"` + ChargifyToken *string `json:"chargify_token,omitempty"` + VaultToken *string `json:"vault_token,omitempty"` + // The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. + CurrentVault *CurrentVault `json:"current_vault,omitempty"` + GatewayHandle *string `json:"gateway_handle,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + BillingAddress *string `json:"billing_address,omitempty"` + BillingAddress2 *string `json:"billing_address_2,omitempty"` + BillingCity *string `json:"billing_city,omitempty"` + BillingState *string `json:"billing_state,omitempty"` + BillingZip *string `json:"billing_zip,omitempty"` + BillingCountry *string `json:"billing_country,omitempty"` + LastFour *string `json:"last_four,omitempty"` + // The type of card used. + CardType *CardType `json:"card_type,omitempty"` + CustomerVaultToken *string `json:"customer_vault_token,omitempty"` + Cvv *string `json:"cvv,omitempty"` + PaymentType *string `json:"payment_type,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupCreditCard. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupCreditCard. // It customizes the JSON marshaling process for SubscriptionGroupCreditCard objects. func (s *SubscriptionGroupCreditCard) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupCreditCard object to a map representation for JSON marshaling. func (s *SubscriptionGroupCreditCard) toMap() map[string]any { - structMap := make(map[string]any) - if s.FullNumber != nil { - structMap["full_number"] = s.FullNumber - } - if s.ExpirationMonth != nil { - structMap["expiration_month"] = s.ExpirationMonth - } - if s.ExpirationYear != nil { - structMap["expiration_year"] = s.ExpirationYear - } - if s.ChargifyToken != nil { - structMap["chargify_token"] = s.ChargifyToken - } - if s.VaultToken != nil { - structMap["vault_token"] = s.VaultToken - } - if s.CurrentVault != nil { - structMap["current_vault"] = s.CurrentVault - } - if s.GatewayHandle != nil { - structMap["gateway_handle"] = s.GatewayHandle - } - if s.FirstName != nil { - structMap["first_name"] = s.FirstName - } - if s.LastName != nil { - structMap["last_name"] = s.LastName - } - if s.BillingAddress != nil { - structMap["billing_address"] = s.BillingAddress - } - if s.BillingAddress2 != nil { - structMap["billing_address_2"] = s.BillingAddress2 - } - if s.BillingCity != nil { - structMap["billing_city"] = s.BillingCity - } - if s.BillingState != nil { - structMap["billing_state"] = s.BillingState - } - if s.BillingZip != nil { - structMap["billing_zip"] = s.BillingZip - } - if s.BillingCountry != nil { - structMap["billing_country"] = s.BillingCountry - } - if s.LastFour != nil { - structMap["last_four"] = s.LastFour - } - if s.CardType != nil { - structMap["card_type"] = s.CardType - } - if s.CustomerVaultToken != nil { - structMap["customer_vault_token"] = s.CustomerVaultToken - } - if s.Cvv != nil { - structMap["cvv"] = s.Cvv - } - if s.PaymentType != nil { - structMap["payment_type"] = s.PaymentType - } - return structMap + structMap := make(map[string]any) + if s.FullNumber != nil { + structMap["full_number"] = s.FullNumber.toMap() + } + if s.ExpirationMonth != nil { + structMap["expiration_month"] = s.ExpirationMonth.toMap() + } + if s.ExpirationYear != nil { + structMap["expiration_year"] = s.ExpirationYear.toMap() + } + if s.ChargifyToken != nil { + structMap["chargify_token"] = s.ChargifyToken + } + if s.VaultToken != nil { + structMap["vault_token"] = s.VaultToken + } + if s.CurrentVault != nil { + structMap["current_vault"] = s.CurrentVault + } + if s.GatewayHandle != nil { + structMap["gateway_handle"] = s.GatewayHandle + } + if s.FirstName != nil { + structMap["first_name"] = s.FirstName + } + if s.LastName != nil { + structMap["last_name"] = s.LastName + } + if s.BillingAddress != nil { + structMap["billing_address"] = s.BillingAddress + } + if s.BillingAddress2 != nil { + structMap["billing_address_2"] = s.BillingAddress2 + } + if s.BillingCity != nil { + structMap["billing_city"] = s.BillingCity + } + if s.BillingState != nil { + structMap["billing_state"] = s.BillingState + } + if s.BillingZip != nil { + structMap["billing_zip"] = s.BillingZip + } + if s.BillingCountry != nil { + structMap["billing_country"] = s.BillingCountry + } + if s.LastFour != nil { + structMap["last_four"] = s.LastFour + } + if s.CardType != nil { + structMap["card_type"] = s.CardType + } + if s.CustomerVaultToken != nil { + structMap["customer_vault_token"] = s.CustomerVaultToken + } + if s.Cvv != nil { + structMap["cvv"] = s.Cvv + } + if s.PaymentType != nil { + structMap["payment_type"] = s.PaymentType + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupCreditCard. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupCreditCard. // It customizes the JSON unmarshaling process for SubscriptionGroupCreditCard objects. func (s *SubscriptionGroupCreditCard) UnmarshalJSON(input []byte) error { - temp := &struct { - FullNumber *interface{} `json:"full_number,omitempty"` - ExpirationMonth *interface{} `json:"expiration_month,omitempty"` - ExpirationYear *interface{} `json:"expiration_year,omitempty"` - ChargifyToken *string `json:"chargify_token,omitempty"` - VaultToken *string `json:"vault_token,omitempty"` - CurrentVault *CurrentVault `json:"current_vault,omitempty"` - GatewayHandle *string `json:"gateway_handle,omitempty"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - BillingAddress *string `json:"billing_address,omitempty"` - BillingAddress2 *string `json:"billing_address_2,omitempty"` - BillingCity *string `json:"billing_city,omitempty"` - BillingState *string `json:"billing_state,omitempty"` - BillingZip *string `json:"billing_zip,omitempty"` - BillingCountry *string `json:"billing_country,omitempty"` - LastFour *string `json:"last_four,omitempty"` - CardType *CardType `json:"card_type,omitempty"` - CustomerVaultToken *string `json:"customer_vault_token,omitempty"` - Cvv *string `json:"cvv,omitempty"` - PaymentType *string `json:"payment_type,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.FullNumber = temp.FullNumber - s.ExpirationMonth = temp.ExpirationMonth - s.ExpirationYear = temp.ExpirationYear - s.ChargifyToken = temp.ChargifyToken - s.VaultToken = temp.VaultToken - s.CurrentVault = temp.CurrentVault - s.GatewayHandle = temp.GatewayHandle - s.FirstName = temp.FirstName - s.LastName = temp.LastName - s.BillingAddress = temp.BillingAddress - s.BillingAddress2 = temp.BillingAddress2 - s.BillingCity = temp.BillingCity - s.BillingState = temp.BillingState - s.BillingZip = temp.BillingZip - s.BillingCountry = temp.BillingCountry - s.LastFour = temp.LastFour - s.CardType = temp.CardType - s.CustomerVaultToken = temp.CustomerVaultToken - s.Cvv = temp.Cvv - s.PaymentType = temp.PaymentType - return nil + var temp subscriptionGroupCreditCard + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.FullNumber = temp.FullNumber + s.ExpirationMonth = temp.ExpirationMonth + s.ExpirationYear = temp.ExpirationYear + s.ChargifyToken = temp.ChargifyToken + s.VaultToken = temp.VaultToken + s.CurrentVault = temp.CurrentVault + s.GatewayHandle = temp.GatewayHandle + s.FirstName = temp.FirstName + s.LastName = temp.LastName + s.BillingAddress = temp.BillingAddress + s.BillingAddress2 = temp.BillingAddress2 + s.BillingCity = temp.BillingCity + s.BillingState = temp.BillingState + s.BillingZip = temp.BillingZip + s.BillingCountry = temp.BillingCountry + s.LastFour = temp.LastFour + s.CardType = temp.CardType + s.CustomerVaultToken = temp.CustomerVaultToken + s.Cvv = temp.Cvv + s.PaymentType = temp.PaymentType + return nil +} + +// TODO +type subscriptionGroupCreditCard struct { + FullNumber *SubscriptionGroupCreditCardFullNumber `json:"full_number,omitempty"` + ExpirationMonth *SubscriptionGroupCreditCardExpirationMonth `json:"expiration_month,omitempty"` + ExpirationYear *SubscriptionGroupCreditCardExpirationYear `json:"expiration_year,omitempty"` + ChargifyToken *string `json:"chargify_token,omitempty"` + VaultToken *string `json:"vault_token,omitempty"` + CurrentVault *CurrentVault `json:"current_vault,omitempty"` + GatewayHandle *string `json:"gateway_handle,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + BillingAddress *string `json:"billing_address,omitempty"` + BillingAddress2 *string `json:"billing_address_2,omitempty"` + BillingCity *string `json:"billing_city,omitempty"` + BillingState *string `json:"billing_state,omitempty"` + BillingZip *string `json:"billing_zip,omitempty"` + BillingCountry *string `json:"billing_country,omitempty"` + LastFour *string `json:"last_four,omitempty"` + CardType *CardType `json:"card_type,omitempty"` + CustomerVaultToken *string `json:"customer_vault_token,omitempty"` + Cvv *string `json:"cvv,omitempty"` + PaymentType *string `json:"payment_type,omitempty"` } diff --git a/models/subscription_group_credit_card_expiration_month.go b/models/subscription_group_credit_card_expiration_month.go new file mode 100644 index 00000000..c9e4ba09 --- /dev/null +++ b/models/subscription_group_credit_card_expiration_month.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupCreditCardExpirationMonth represents a SubscriptionGroupCreditCardExpirationMonth struct. +// This is a container for one-of cases. +type SubscriptionGroupCreditCardExpirationMonth struct { + value any + isString bool + isNumber bool +} + +// String converts the SubscriptionGroupCreditCardExpirationMonth object to a string representation. +func (s SubscriptionGroupCreditCardExpirationMonth) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupCreditCardExpirationMonth. +// It customizes the JSON marshaling process for SubscriptionGroupCreditCardExpirationMonth objects. +func (s *SubscriptionGroupCreditCardExpirationMonth) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionGroupCreditCardExpirationMonthContainer.From*` functions to initialize the SubscriptionGroupCreditCardExpirationMonth object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupCreditCardExpirationMonth object to a map representation for JSON marshaling. +func (s *SubscriptionGroupCreditCardExpirationMonth) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupCreditCardExpirationMonth. +// It customizes the JSON unmarshaling process for SubscriptionGroupCreditCardExpirationMonth objects. +func (s *SubscriptionGroupCreditCardExpirationMonth) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int), false, &s.isNumber), + ) + + s.value = result + return err +} + +func (s *SubscriptionGroupCreditCardExpirationMonth) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionGroupCreditCardExpirationMonth) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +// internalSubscriptionGroupCreditCardExpirationMonth represents a subscriptionGroupCreditCardExpirationMonth struct. +// This is a container for one-of cases. +type internalSubscriptionGroupCreditCardExpirationMonth struct{} + +var SubscriptionGroupCreditCardExpirationMonthContainer internalSubscriptionGroupCreditCardExpirationMonth + +func (s *internalSubscriptionGroupCreditCardExpirationMonth) FromString(val string) SubscriptionGroupCreditCardExpirationMonth { + return SubscriptionGroupCreditCardExpirationMonth{value: &val} +} + +func (s *internalSubscriptionGroupCreditCardExpirationMonth) FromNumber(val int) SubscriptionGroupCreditCardExpirationMonth { + return SubscriptionGroupCreditCardExpirationMonth{value: &val} +} diff --git a/models/subscription_group_credit_card_expiration_year.go b/models/subscription_group_credit_card_expiration_year.go new file mode 100644 index 00000000..655fd0f9 --- /dev/null +++ b/models/subscription_group_credit_card_expiration_year.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupCreditCardExpirationYear represents a SubscriptionGroupCreditCardExpirationYear struct. +// This is a container for one-of cases. +type SubscriptionGroupCreditCardExpirationYear struct { + value any + isString bool + isNumber bool +} + +// String converts the SubscriptionGroupCreditCardExpirationYear object to a string representation. +func (s SubscriptionGroupCreditCardExpirationYear) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupCreditCardExpirationYear. +// It customizes the JSON marshaling process for SubscriptionGroupCreditCardExpirationYear objects. +func (s *SubscriptionGroupCreditCardExpirationYear) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionGroupCreditCardExpirationYearContainer.From*` functions to initialize the SubscriptionGroupCreditCardExpirationYear object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupCreditCardExpirationYear object to a map representation for JSON marshaling. +func (s *SubscriptionGroupCreditCardExpirationYear) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupCreditCardExpirationYear. +// It customizes the JSON unmarshaling process for SubscriptionGroupCreditCardExpirationYear objects. +func (s *SubscriptionGroupCreditCardExpirationYear) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int), false, &s.isNumber), + ) + + s.value = result + return err +} + +func (s *SubscriptionGroupCreditCardExpirationYear) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionGroupCreditCardExpirationYear) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +// internalSubscriptionGroupCreditCardExpirationYear represents a subscriptionGroupCreditCardExpirationYear struct. +// This is a container for one-of cases. +type internalSubscriptionGroupCreditCardExpirationYear struct{} + +var SubscriptionGroupCreditCardExpirationYearContainer internalSubscriptionGroupCreditCardExpirationYear + +func (s *internalSubscriptionGroupCreditCardExpirationYear) FromString(val string) SubscriptionGroupCreditCardExpirationYear { + return SubscriptionGroupCreditCardExpirationYear{value: &val} +} + +func (s *internalSubscriptionGroupCreditCardExpirationYear) FromNumber(val int) SubscriptionGroupCreditCardExpirationYear { + return SubscriptionGroupCreditCardExpirationYear{value: &val} +} diff --git a/models/subscription_group_credit_card_full_number.go b/models/subscription_group_credit_card_full_number.go new file mode 100644 index 00000000..2578b66e --- /dev/null +++ b/models/subscription_group_credit_card_full_number.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupCreditCardFullNumber represents a SubscriptionGroupCreditCardFullNumber struct. +// This is a container for one-of cases. +type SubscriptionGroupCreditCardFullNumber struct { + value any + isString bool + isNumber bool +} + +// String converts the SubscriptionGroupCreditCardFullNumber object to a string representation. +func (s SubscriptionGroupCreditCardFullNumber) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupCreditCardFullNumber. +// It customizes the JSON marshaling process for SubscriptionGroupCreditCardFullNumber objects. +func (s *SubscriptionGroupCreditCardFullNumber) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionGroupCreditCardFullNumberContainer.From*` functions to initialize the SubscriptionGroupCreditCardFullNumber object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupCreditCardFullNumber object to a map representation for JSON marshaling. +func (s *SubscriptionGroupCreditCardFullNumber) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupCreditCardFullNumber. +// It customizes the JSON unmarshaling process for SubscriptionGroupCreditCardFullNumber objects. +func (s *SubscriptionGroupCreditCardFullNumber) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int), false, &s.isNumber), + ) + + s.value = result + return err +} + +func (s *SubscriptionGroupCreditCardFullNumber) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionGroupCreditCardFullNumber) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +// internalSubscriptionGroupCreditCardFullNumber represents a subscriptionGroupCreditCardFullNumber struct. +// This is a container for one-of cases. +type internalSubscriptionGroupCreditCardFullNumber struct{} + +var SubscriptionGroupCreditCardFullNumberContainer internalSubscriptionGroupCreditCardFullNumber + +func (s *internalSubscriptionGroupCreditCardFullNumber) FromString(val string) SubscriptionGroupCreditCardFullNumber { + return SubscriptionGroupCreditCardFullNumber{value: &val} +} + +func (s *internalSubscriptionGroupCreditCardFullNumber) FromNumber(val int) SubscriptionGroupCreditCardFullNumber { + return SubscriptionGroupCreditCardFullNumber{value: &val} +} diff --git a/models/subscription_group_customer.go b/models/subscription_group_customer.go index a0f97445..331f7b13 100644 --- a/models/subscription_group_customer.go +++ b/models/subscription_group_customer.go @@ -1,66 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupCustomer represents a SubscriptionGroupCustomer struct. type SubscriptionGroupCustomer struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Organization *string `json:"organization,omitempty"` - Email *string `json:"email,omitempty"` - Reference *string `json:"reference,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Organization *string `json:"organization,omitempty"` + Email *string `json:"email,omitempty"` + Reference *string `json:"reference,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupCustomer. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupCustomer. // It customizes the JSON marshaling process for SubscriptionGroupCustomer objects. func (s *SubscriptionGroupCustomer) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupCustomer object to a map representation for JSON marshaling. func (s *SubscriptionGroupCustomer) toMap() map[string]any { - structMap := make(map[string]any) - if s.FirstName != nil { - structMap["first_name"] = s.FirstName - } - if s.LastName != nil { - structMap["last_name"] = s.LastName - } - if s.Organization != nil { - structMap["organization"] = s.Organization - } - if s.Email != nil { - structMap["email"] = s.Email - } - if s.Reference != nil { - structMap["reference"] = s.Reference - } - return structMap + structMap := make(map[string]any) + if s.FirstName != nil { + structMap["first_name"] = s.FirstName + } + if s.LastName != nil { + structMap["last_name"] = s.LastName + } + if s.Organization != nil { + structMap["organization"] = s.Organization + } + if s.Email != nil { + structMap["email"] = s.Email + } + if s.Reference != nil { + structMap["reference"] = s.Reference + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupCustomer. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupCustomer. // It customizes the JSON unmarshaling process for SubscriptionGroupCustomer objects. func (s *SubscriptionGroupCustomer) UnmarshalJSON(input []byte) error { - temp := &struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Organization *string `json:"organization,omitempty"` - Email *string `json:"email,omitempty"` - Reference *string `json:"reference,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.FirstName = temp.FirstName - s.LastName = temp.LastName - s.Organization = temp.Organization - s.Email = temp.Email - s.Reference = temp.Reference - return nil + var temp subscriptionGroupCustomer + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.FirstName = temp.FirstName + s.LastName = temp.LastName + s.Organization = temp.Organization + s.Email = temp.Email + s.Reference = temp.Reference + return nil +} + +// TODO +type subscriptionGroupCustomer struct { + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Organization *string `json:"organization,omitempty"` + Email *string `json:"email,omitempty"` + Reference *string `json:"reference,omitempty"` } diff --git a/models/subscription_group_item.go b/models/subscription_group_item.go index 6e33993d..5bb9a190 100644 --- a/models/subscription_group_item.go +++ b/models/subscription_group_item.go @@ -1,96 +1,110 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupItem represents a SubscriptionGroupItem struct. type SubscriptionGroupItem struct { - Id *int `json:"id,omitempty"` - Reference Optional[string] `json:"reference"` - ProductId *int `json:"product_id,omitempty"` - ProductHandle Optional[string] `json:"product_handle"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` - Currency *string `json:"currency,omitempty"` - CouponCode Optional[string] `json:"coupon_code"` - TotalRevenueInCents *int64 `json:"total_revenue_in_cents,omitempty"` - BalanceInCents *int64 `json:"balance_in_cents,omitempty"` + Id *int `json:"id,omitempty"` + Reference Optional[string] `json:"reference"` + ProductId *int `json:"product_id,omitempty"` + ProductHandle Optional[string] `json:"product_handle"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` + Currency *string `json:"currency,omitempty"` + CouponCode Optional[string] `json:"coupon_code"` + TotalRevenueInCents *int64 `json:"total_revenue_in_cents,omitempty"` + BalanceInCents *int64 `json:"balance_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupItem. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupItem. // It customizes the JSON marshaling process for SubscriptionGroupItem objects. func (s *SubscriptionGroupItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupItem object to a map representation for JSON marshaling. func (s *SubscriptionGroupItem) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.Reference.IsValueSet() { - structMap["reference"] = s.Reference.Value() - } - if s.ProductId != nil { - structMap["product_id"] = s.ProductId - } - if s.ProductHandle.IsValueSet() { - structMap["product_handle"] = s.ProductHandle.Value() - } - if s.ProductPricePointId != nil { - structMap["product_price_point_id"] = s.ProductPricePointId - } - if s.ProductPricePointHandle != nil { - structMap["product_price_point_handle"] = s.ProductPricePointHandle - } - if s.Currency != nil { - structMap["currency"] = s.Currency - } - if s.CouponCode.IsValueSet() { - structMap["coupon_code"] = s.CouponCode.Value() - } - if s.TotalRevenueInCents != nil { - structMap["total_revenue_in_cents"] = s.TotalRevenueInCents - } - if s.BalanceInCents != nil { - structMap["balance_in_cents"] = s.BalanceInCents - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.Reference.IsValueSet() { + if s.Reference.Value() != nil { + structMap["reference"] = s.Reference.Value() + } else { + structMap["reference"] = nil + } + } + if s.ProductId != nil { + structMap["product_id"] = s.ProductId + } + if s.ProductHandle.IsValueSet() { + if s.ProductHandle.Value() != nil { + structMap["product_handle"] = s.ProductHandle.Value() + } else { + structMap["product_handle"] = nil + } + } + if s.ProductPricePointId != nil { + structMap["product_price_point_id"] = s.ProductPricePointId + } + if s.ProductPricePointHandle != nil { + structMap["product_price_point_handle"] = s.ProductPricePointHandle + } + if s.Currency != nil { + structMap["currency"] = s.Currency + } + if s.CouponCode.IsValueSet() { + if s.CouponCode.Value() != nil { + structMap["coupon_code"] = s.CouponCode.Value() + } else { + structMap["coupon_code"] = nil + } + } + if s.TotalRevenueInCents != nil { + structMap["total_revenue_in_cents"] = s.TotalRevenueInCents + } + if s.BalanceInCents != nil { + structMap["balance_in_cents"] = s.BalanceInCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupItem. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupItem. // It customizes the JSON unmarshaling process for SubscriptionGroupItem objects. func (s *SubscriptionGroupItem) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Reference Optional[string] `json:"reference"` - ProductId *int `json:"product_id,omitempty"` - ProductHandle Optional[string] `json:"product_handle"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` - Currency *string `json:"currency,omitempty"` - CouponCode Optional[string] `json:"coupon_code"` - TotalRevenueInCents *int64 `json:"total_revenue_in_cents,omitempty"` - BalanceInCents *int64 `json:"balance_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.Reference = temp.Reference - s.ProductId = temp.ProductId - s.ProductHandle = temp.ProductHandle - s.ProductPricePointId = temp.ProductPricePointId - s.ProductPricePointHandle = temp.ProductPricePointHandle - s.Currency = temp.Currency - s.CouponCode = temp.CouponCode - s.TotalRevenueInCents = temp.TotalRevenueInCents - s.BalanceInCents = temp.BalanceInCents - return nil + var temp subscriptionGroupItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.Reference = temp.Reference + s.ProductId = temp.ProductId + s.ProductHandle = temp.ProductHandle + s.ProductPricePointId = temp.ProductPricePointId + s.ProductPricePointHandle = temp.ProductPricePointHandle + s.Currency = temp.Currency + s.CouponCode = temp.CouponCode + s.TotalRevenueInCents = temp.TotalRevenueInCents + s.BalanceInCents = temp.BalanceInCents + return nil +} + +// TODO +type subscriptionGroupItem struct { + Id *int `json:"id,omitempty"` + Reference Optional[string] `json:"reference"` + ProductId *int `json:"product_id,omitempty"` + ProductHandle Optional[string] `json:"product_handle"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` + Currency *string `json:"currency,omitempty"` + CouponCode Optional[string] `json:"coupon_code"` + TotalRevenueInCents *int64 `json:"total_revenue_in_cents,omitempty"` + BalanceInCents *int64 `json:"balance_in_cents,omitempty"` } diff --git a/models/subscription_group_member_error.go b/models/subscription_group_member_error.go index e475d2ba..1386b254 100644 --- a/models/subscription_group_member_error.go +++ b/models/subscription_group_member_error.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupMemberError represents a SubscriptionGroupMemberError struct. type SubscriptionGroupMemberError struct { - Id *int `json:"id,omitempty"` - Type *string `json:"type,omitempty"` - Message *string `json:"message,omitempty"` + Id *int `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Message *string `json:"message,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupMemberError. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupMemberError. // It customizes the JSON marshaling process for SubscriptionGroupMemberError objects. func (s *SubscriptionGroupMemberError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupMemberError object to a map representation for JSON marshaling. func (s *SubscriptionGroupMemberError) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.Type != nil { - structMap["type"] = s.Type - } - if s.Message != nil { - structMap["message"] = s.Message - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.Type != nil { + structMap["type"] = s.Type + } + if s.Message != nil { + structMap["message"] = s.Message + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupMemberError. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupMemberError. // It customizes the JSON unmarshaling process for SubscriptionGroupMemberError objects. func (s *SubscriptionGroupMemberError) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Type *string `json:"type,omitempty"` - Message *string `json:"message,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.Type = temp.Type - s.Message = temp.Message - return nil + var temp subscriptionGroupMemberError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.Type = temp.Type + s.Message = temp.Message + return nil +} + +// TODO +type subscriptionGroupMemberError struct { + Id *int `json:"id,omitempty"` + Type *string `json:"type,omitempty"` + Message *string `json:"message,omitempty"` } diff --git a/models/subscription_group_members_array_error.go b/models/subscription_group_members_array_error.go new file mode 100644 index 00000000..6367cb71 --- /dev/null +++ b/models/subscription_group_members_array_error.go @@ -0,0 +1,60 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupMembersArrayError represents a SubscriptionGroupMembersArrayError struct. +type SubscriptionGroupMembersArrayError struct { + Members []string `json:"members"` +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupMembersArrayError. +// It customizes the JSON marshaling process for SubscriptionGroupMembersArrayError objects. +func (s *SubscriptionGroupMembersArrayError) MarshalJSON() ( + []byte, + error) { + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupMembersArrayError object to a map representation for JSON marshaling. +func (s *SubscriptionGroupMembersArrayError) toMap() map[string]any { + structMap := make(map[string]any) + structMap["members"] = s.Members + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupMembersArrayError. +// It customizes the JSON unmarshaling process for SubscriptionGroupMembersArrayError objects. +func (s *SubscriptionGroupMembersArrayError) UnmarshalJSON(input []byte) error { + var temp subscriptionGroupMembersArrayError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.Members = *temp.Members + return nil +} + +// TODO +type subscriptionGroupMembersArrayError struct { + Members *[]string `json:"members"` +} + +func (s *subscriptionGroupMembersArrayError) validate() error { + var errs []string + if s.Members == nil { + errs = append(errs, "required field `members` is missing for type `Subscription Group Members Array Error`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/subscription_group_payment_profile.go b/models/subscription_group_payment_profile.go index 88632afd..ea5b2fb7 100644 --- a/models/subscription_group_payment_profile.go +++ b/models/subscription_group_payment_profile.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupPaymentProfile represents a SubscriptionGroupPaymentProfile struct. type SubscriptionGroupPaymentProfile struct { - Id *int `json:"id,omitempty"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - MaskedCardNumber *string `json:"masked_card_number,omitempty"` + Id *int `json:"id,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + MaskedCardNumber *string `json:"masked_card_number,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupPaymentProfile. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupPaymentProfile. // It customizes the JSON marshaling process for SubscriptionGroupPaymentProfile objects. func (s *SubscriptionGroupPaymentProfile) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupPaymentProfile object to a map representation for JSON marshaling. func (s *SubscriptionGroupPaymentProfile) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.FirstName != nil { - structMap["first_name"] = s.FirstName - } - if s.LastName != nil { - structMap["last_name"] = s.LastName - } - if s.MaskedCardNumber != nil { - structMap["masked_card_number"] = s.MaskedCardNumber - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.FirstName != nil { + structMap["first_name"] = s.FirstName + } + if s.LastName != nil { + structMap["last_name"] = s.LastName + } + if s.MaskedCardNumber != nil { + structMap["masked_card_number"] = s.MaskedCardNumber + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupPaymentProfile. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupPaymentProfile. // It customizes the JSON unmarshaling process for SubscriptionGroupPaymentProfile objects. func (s *SubscriptionGroupPaymentProfile) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - MaskedCardNumber *string `json:"masked_card_number,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.FirstName = temp.FirstName - s.LastName = temp.LastName - s.MaskedCardNumber = temp.MaskedCardNumber - return nil + var temp subscriptionGroupPaymentProfile + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.FirstName = temp.FirstName + s.LastName = temp.LastName + s.MaskedCardNumber = temp.MaskedCardNumber + return nil +} + +// TODO +type subscriptionGroupPaymentProfile struct { + Id *int `json:"id,omitempty"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + MaskedCardNumber *string `json:"masked_card_number,omitempty"` } diff --git a/models/subscription_group_prepayment.go b/models/subscription_group_prepayment.go index fc2e8c0b..3abb07fe 100644 --- a/models/subscription_group_prepayment.go +++ b/models/subscription_group_prepayment.go @@ -1,52 +1,81 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionGroupPrepayment represents a SubscriptionGroupPrepayment struct. type SubscriptionGroupPrepayment struct { - Amount int `json:"amount"` - Details string `json:"details"` - Memo string `json:"memo"` - Method SubscriptionGroupPrepaymentMethod `json:"method"` + Amount int `json:"amount"` + Details string `json:"details"` + Memo string `json:"memo"` + Method SubscriptionGroupPrepaymentMethod `json:"method"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupPrepayment. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupPrepayment. // It customizes the JSON marshaling process for SubscriptionGroupPrepayment objects. func (s *SubscriptionGroupPrepayment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupPrepayment object to a map representation for JSON marshaling. func (s *SubscriptionGroupPrepayment) toMap() map[string]any { - structMap := make(map[string]any) - structMap["amount"] = s.Amount - structMap["details"] = s.Details - structMap["memo"] = s.Memo - structMap["method"] = s.Method - return structMap + structMap := make(map[string]any) + structMap["amount"] = s.Amount + structMap["details"] = s.Details + structMap["memo"] = s.Memo + structMap["method"] = s.Method + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupPrepayment. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupPrepayment. // It customizes the JSON unmarshaling process for SubscriptionGroupPrepayment objects. func (s *SubscriptionGroupPrepayment) UnmarshalJSON(input []byte) error { - temp := &struct { - Amount int `json:"amount"` - Details string `json:"details"` - Memo string `json:"memo"` - Method SubscriptionGroupPrepaymentMethod `json:"method"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Amount = temp.Amount - s.Details = temp.Details - s.Memo = temp.Memo - s.Method = temp.Method - return nil + var temp subscriptionGroupPrepayment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.Amount = *temp.Amount + s.Details = *temp.Details + s.Memo = *temp.Memo + s.Method = *temp.Method + return nil +} + +// TODO +type subscriptionGroupPrepayment struct { + Amount *int `json:"amount"` + Details *string `json:"details"` + Memo *string `json:"memo"` + Method *SubscriptionGroupPrepaymentMethod `json:"method"` +} + +func (s *subscriptionGroupPrepayment) validate() error { + var errs []string + if s.Amount == nil { + errs = append(errs, "required field `amount` is missing for type `Subscription Group Prepayment`") + } + if s.Details == nil { + errs = append(errs, "required field `details` is missing for type `Subscription Group Prepayment`") + } + if s.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Subscription Group Prepayment`") + } + if s.Method == nil { + errs = append(errs, "required field `method` is missing for type `Subscription Group Prepayment`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_group_prepayment_request.go b/models/subscription_group_prepayment_request.go index 061f0959..47d1e42e 100644 --- a/models/subscription_group_prepayment_request.go +++ b/models/subscription_group_prepayment_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionGroupPrepaymentRequest represents a SubscriptionGroupPrepaymentRequest struct. type SubscriptionGroupPrepaymentRequest struct { - Prepayment SubscriptionGroupPrepayment `json:"prepayment"` + Prepayment SubscriptionGroupPrepayment `json:"prepayment"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupPrepaymentRequest. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupPrepaymentRequest. // It customizes the JSON marshaling process for SubscriptionGroupPrepaymentRequest objects. func (s *SubscriptionGroupPrepaymentRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupPrepaymentRequest object to a map representation for JSON marshaling. func (s *SubscriptionGroupPrepaymentRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["prepayment"] = s.Prepayment.toMap() - return structMap + structMap := make(map[string]any) + structMap["prepayment"] = s.Prepayment.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupPrepaymentRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupPrepaymentRequest. // It customizes the JSON unmarshaling process for SubscriptionGroupPrepaymentRequest objects. func (s *SubscriptionGroupPrepaymentRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Prepayment SubscriptionGroupPrepayment `json:"prepayment"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Prepayment = temp.Prepayment - return nil + var temp subscriptionGroupPrepaymentRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.Prepayment = *temp.Prepayment + return nil +} + +// TODO +type subscriptionGroupPrepaymentRequest struct { + Prepayment *SubscriptionGroupPrepayment `json:"prepayment"` +} + +func (s *subscriptionGroupPrepaymentRequest) validate() error { + var errs []string + if s.Prepayment == nil { + errs = append(errs, "required field `prepayment` is missing for type `Subscription Group Prepayment Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_group_prepayment_response.go b/models/subscription_group_prepayment_response.go index 1d76b871..9fc99850 100644 --- a/models/subscription_group_prepayment_response.go +++ b/models/subscription_group_prepayment_response.go @@ -1,70 +1,72 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupPrepaymentResponse represents a SubscriptionGroupPrepaymentResponse struct. type SubscriptionGroupPrepaymentResponse struct { - Id *int `json:"id,omitempty"` - // The amount in cents of the entry. - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - // The ending balance in cents of the account. - EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` - // The type of entry - EntryType *ServiceCreditType `json:"entry_type,omitempty"` - // A memo attached to the entry. - Memo *string `json:"memo,omitempty"` + Id *int `json:"id,omitempty"` + // The amount in cents of the entry. + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + // The ending balance in cents of the account. + EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` + // The type of entry + EntryType *ServiceCreditType `json:"entry_type,omitempty"` + // A memo attached to the entry. + Memo *string `json:"memo,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupPrepaymentResponse. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupPrepaymentResponse. // It customizes the JSON marshaling process for SubscriptionGroupPrepaymentResponse objects. func (s *SubscriptionGroupPrepaymentResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupPrepaymentResponse object to a map representation for JSON marshaling. func (s *SubscriptionGroupPrepaymentResponse) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.AmountInCents != nil { - structMap["amount_in_cents"] = s.AmountInCents - } - if s.EndingBalanceInCents != nil { - structMap["ending_balance_in_cents"] = s.EndingBalanceInCents - } - if s.EntryType != nil { - structMap["entry_type"] = s.EntryType - } - if s.Memo != nil { - structMap["memo"] = s.Memo - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.AmountInCents != nil { + structMap["amount_in_cents"] = s.AmountInCents + } + if s.EndingBalanceInCents != nil { + structMap["ending_balance_in_cents"] = s.EndingBalanceInCents + } + if s.EntryType != nil { + structMap["entry_type"] = s.EntryType + } + if s.Memo != nil { + structMap["memo"] = s.Memo + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupPrepaymentResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupPrepaymentResponse. // It customizes the JSON unmarshaling process for SubscriptionGroupPrepaymentResponse objects. func (s *SubscriptionGroupPrepaymentResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - AmountInCents *int64 `json:"amount_in_cents,omitempty"` - EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` - EntryType *ServiceCreditType `json:"entry_type,omitempty"` - Memo *string `json:"memo,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.AmountInCents = temp.AmountInCents - s.EndingBalanceInCents = temp.EndingBalanceInCents - s.EntryType = temp.EntryType - s.Memo = temp.Memo - return nil + var temp subscriptionGroupPrepaymentResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.AmountInCents = temp.AmountInCents + s.EndingBalanceInCents = temp.EndingBalanceInCents + s.EntryType = temp.EntryType + s.Memo = temp.Memo + return nil +} + +// TODO +type subscriptionGroupPrepaymentResponse struct { + Id *int `json:"id,omitempty"` + AmountInCents *int64 `json:"amount_in_cents,omitempty"` + EndingBalanceInCents *int64 `json:"ending_balance_in_cents,omitempty"` + EntryType *ServiceCreditType `json:"entry_type,omitempty"` + Memo *string `json:"memo,omitempty"` } diff --git a/models/subscription_group_response.go b/models/subscription_group_response.go index feae7c03..9613362e 100644 --- a/models/subscription_group_response.go +++ b/models/subscription_group_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionGroupResponse represents a SubscriptionGroupResponse struct. type SubscriptionGroupResponse struct { - SubscriptionGroup SubscriptionGroup `json:"subscription_group"` + SubscriptionGroup SubscriptionGroup `json:"subscription_group"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupResponse. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupResponse. // It customizes the JSON marshaling process for SubscriptionGroupResponse objects. func (s *SubscriptionGroupResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupResponse object to a map representation for JSON marshaling. func (s *SubscriptionGroupResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscription_group"] = s.SubscriptionGroup.toMap() - return structMap + structMap := make(map[string]any) + structMap["subscription_group"] = s.SubscriptionGroup.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupResponse. // It customizes the JSON unmarshaling process for SubscriptionGroupResponse objects. func (s *SubscriptionGroupResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - SubscriptionGroup SubscriptionGroup `json:"subscription_group"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.SubscriptionGroup = temp.SubscriptionGroup - return nil + var temp subscriptionGroupResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.SubscriptionGroup = *temp.SubscriptionGroup + return nil +} + +// TODO +type subscriptionGroupResponse struct { + SubscriptionGroup *SubscriptionGroup `json:"subscription_group"` +} + +func (s *subscriptionGroupResponse) validate() error { + var errs []string + if s.SubscriptionGroup == nil { + errs = append(errs, "required field `subscription_group` is missing for type `Subscription Group Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_group_signup.go b/models/subscription_group_signup.go index 90245690..ed5f39e7 100644 --- a/models/subscription_group_signup.go +++ b/models/subscription_group_signup.go @@ -1,83 +1,103 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionGroupSignup represents a SubscriptionGroupSignup struct. type SubscriptionGroupSignup struct { - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - PayerId *int `json:"payer_id,omitempty"` - PayerReference *string `json:"payer_reference,omitempty"` - // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. - PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` - PayerAttributes *PayerAttributes `json:"payer_attributes,omitempty"` - CreditCardAttributes *SubscriptionGroupCreditCard `json:"credit_card_attributes,omitempty"` - BankAccountAttributes *SubscriptionGroupBankAccount `json:"bank_account_attributes,omitempty"` - Subscriptions []SubscriptionGroupSignupItem `json:"subscriptions"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + PayerId *int `json:"payer_id,omitempty"` + PayerReference *string `json:"payer_reference,omitempty"` + // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` + PayerAttributes *PayerAttributes `json:"payer_attributes,omitempty"` + CreditCardAttributes *SubscriptionGroupCreditCard `json:"credit_card_attributes,omitempty"` + BankAccountAttributes *SubscriptionGroupBankAccount `json:"bank_account_attributes,omitempty"` + Subscriptions []SubscriptionGroupSignupItem `json:"subscriptions"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignup. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignup. // It customizes the JSON marshaling process for SubscriptionGroupSignup objects. func (s *SubscriptionGroupSignup) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupSignup object to a map representation for JSON marshaling. func (s *SubscriptionGroupSignup) toMap() map[string]any { - structMap := make(map[string]any) - if s.PaymentProfileId != nil { - structMap["payment_profile_id"] = s.PaymentProfileId - } - if s.PayerId != nil { - structMap["payer_id"] = s.PayerId - } - if s.PayerReference != nil { - structMap["payer_reference"] = s.PayerReference - } - if s.PaymentCollectionMethod != nil { - structMap["payment_collection_method"] = s.PaymentCollectionMethod - } - if s.PayerAttributes != nil { - structMap["payer_attributes"] = s.PayerAttributes.toMap() - } - if s.CreditCardAttributes != nil { - structMap["credit_card_attributes"] = s.CreditCardAttributes.toMap() - } - if s.BankAccountAttributes != nil { - structMap["bank_account_attributes"] = s.BankAccountAttributes.toMap() - } - structMap["subscriptions"] = s.Subscriptions - return structMap + structMap := make(map[string]any) + if s.PaymentProfileId != nil { + structMap["payment_profile_id"] = s.PaymentProfileId + } + if s.PayerId != nil { + structMap["payer_id"] = s.PayerId + } + if s.PayerReference != nil { + structMap["payer_reference"] = s.PayerReference + } + if s.PaymentCollectionMethod != nil { + structMap["payment_collection_method"] = s.PaymentCollectionMethod + } + if s.PayerAttributes != nil { + structMap["payer_attributes"] = s.PayerAttributes.toMap() + } + if s.CreditCardAttributes != nil { + structMap["credit_card_attributes"] = s.CreditCardAttributes.toMap() + } + if s.BankAccountAttributes != nil { + structMap["bank_account_attributes"] = s.BankAccountAttributes.toMap() + } + structMap["subscriptions"] = s.Subscriptions + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignup. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignup. // It customizes the JSON unmarshaling process for SubscriptionGroupSignup objects. func (s *SubscriptionGroupSignup) UnmarshalJSON(input []byte) error { - temp := &struct { - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - PayerId *int `json:"payer_id,omitempty"` - PayerReference *string `json:"payer_reference,omitempty"` - PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` - PayerAttributes *PayerAttributes `json:"payer_attributes,omitempty"` - CreditCardAttributes *SubscriptionGroupCreditCard `json:"credit_card_attributes,omitempty"` - BankAccountAttributes *SubscriptionGroupBankAccount `json:"bank_account_attributes,omitempty"` - Subscriptions []SubscriptionGroupSignupItem `json:"subscriptions"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.PaymentProfileId = temp.PaymentProfileId - s.PayerId = temp.PayerId - s.PayerReference = temp.PayerReference - s.PaymentCollectionMethod = temp.PaymentCollectionMethod - s.PayerAttributes = temp.PayerAttributes - s.CreditCardAttributes = temp.CreditCardAttributes - s.BankAccountAttributes = temp.BankAccountAttributes - s.Subscriptions = temp.Subscriptions - return nil + var temp subscriptionGroupSignup + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.PaymentProfileId = temp.PaymentProfileId + s.PayerId = temp.PayerId + s.PayerReference = temp.PayerReference + s.PaymentCollectionMethod = temp.PaymentCollectionMethod + s.PayerAttributes = temp.PayerAttributes + s.CreditCardAttributes = temp.CreditCardAttributes + s.BankAccountAttributes = temp.BankAccountAttributes + s.Subscriptions = *temp.Subscriptions + return nil +} + +// TODO +type subscriptionGroupSignup struct { + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + PayerId *int `json:"payer_id,omitempty"` + PayerReference *string `json:"payer_reference,omitempty"` + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` + PayerAttributes *PayerAttributes `json:"payer_attributes,omitempty"` + CreditCardAttributes *SubscriptionGroupCreditCard `json:"credit_card_attributes,omitempty"` + BankAccountAttributes *SubscriptionGroupBankAccount `json:"bank_account_attributes,omitempty"` + Subscriptions *[]SubscriptionGroupSignupItem `json:"subscriptions"` +} + +func (s *subscriptionGroupSignup) validate() error { + var errs []string + if s.Subscriptions == nil { + errs = append(errs, "required field `subscriptions` is missing for type `Subscription Group Signup`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_group_signup_component.go b/models/subscription_group_signup_component.go index d30a4fd3..445f728e 100644 --- a/models/subscription_group_signup_component.go +++ b/models/subscription_group_signup_component.go @@ -1,68 +1,70 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupSignupComponent represents a SubscriptionGroupSignupComponent struct. type SubscriptionGroupSignupComponent struct { - // Required if passing any component to `components` attribute. - ComponentId *interface{} `json:"component_id,omitempty"` - AllocatedQuantity *interface{} `json:"allocated_quantity,omitempty"` - UnitBalance *interface{} `json:"unit_balance,omitempty"` - PricePointId *interface{} `json:"price_point_id,omitempty"` - // Used in place of `price_point_id` to define a custom price point unique to the subscription. You still need to provide `component_id`. - CustomPrice *SubscriptionGroupComponentCustomPrice `json:"custom_price,omitempty"` + // Required if passing any component to `components` attribute. + ComponentId *SubscriptionGroupSignupComponentComponentId `json:"component_id,omitempty"` + AllocatedQuantity *SubscriptionGroupSignupComponentAllocatedQuantity `json:"allocated_quantity,omitempty"` + UnitBalance *SubscriptionGroupSignupComponentUnitBalance `json:"unit_balance,omitempty"` + PricePointId *SubscriptionGroupSignupComponentPricePointId `json:"price_point_id,omitempty"` + // Used in place of `price_point_id` to define a custom price point unique to the subscription. You still need to provide `component_id`. + CustomPrice *SubscriptionGroupComponentCustomPrice `json:"custom_price,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupComponent. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupComponent. // It customizes the JSON marshaling process for SubscriptionGroupSignupComponent objects. func (s *SubscriptionGroupSignupComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupSignupComponent object to a map representation for JSON marshaling. func (s *SubscriptionGroupSignupComponent) toMap() map[string]any { - structMap := make(map[string]any) - if s.ComponentId != nil { - structMap["component_id"] = s.ComponentId - } - if s.AllocatedQuantity != nil { - structMap["allocated_quantity"] = s.AllocatedQuantity - } - if s.UnitBalance != nil { - structMap["unit_balance"] = s.UnitBalance - } - if s.PricePointId != nil { - structMap["price_point_id"] = s.PricePointId - } - if s.CustomPrice != nil { - structMap["custom_price"] = s.CustomPrice.toMap() - } - return structMap + structMap := make(map[string]any) + if s.ComponentId != nil { + structMap["component_id"] = s.ComponentId.toMap() + } + if s.AllocatedQuantity != nil { + structMap["allocated_quantity"] = s.AllocatedQuantity.toMap() + } + if s.UnitBalance != nil { + structMap["unit_balance"] = s.UnitBalance.toMap() + } + if s.PricePointId != nil { + structMap["price_point_id"] = s.PricePointId.toMap() + } + if s.CustomPrice != nil { + structMap["custom_price"] = s.CustomPrice.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupComponent. // It customizes the JSON unmarshaling process for SubscriptionGroupSignupComponent objects. func (s *SubscriptionGroupSignupComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - ComponentId *interface{} `json:"component_id,omitempty"` - AllocatedQuantity *interface{} `json:"allocated_quantity,omitempty"` - UnitBalance *interface{} `json:"unit_balance,omitempty"` - PricePointId *interface{} `json:"price_point_id,omitempty"` - CustomPrice *SubscriptionGroupComponentCustomPrice `json:"custom_price,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.ComponentId = temp.ComponentId - s.AllocatedQuantity = temp.AllocatedQuantity - s.UnitBalance = temp.UnitBalance - s.PricePointId = temp.PricePointId - s.CustomPrice = temp.CustomPrice - return nil + var temp subscriptionGroupSignupComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.ComponentId = temp.ComponentId + s.AllocatedQuantity = temp.AllocatedQuantity + s.UnitBalance = temp.UnitBalance + s.PricePointId = temp.PricePointId + s.CustomPrice = temp.CustomPrice + return nil +} + +// TODO +type subscriptionGroupSignupComponent struct { + ComponentId *SubscriptionGroupSignupComponentComponentId `json:"component_id,omitempty"` + AllocatedQuantity *SubscriptionGroupSignupComponentAllocatedQuantity `json:"allocated_quantity,omitempty"` + UnitBalance *SubscriptionGroupSignupComponentUnitBalance `json:"unit_balance,omitempty"` + PricePointId *SubscriptionGroupSignupComponentPricePointId `json:"price_point_id,omitempty"` + CustomPrice *SubscriptionGroupComponentCustomPrice `json:"custom_price,omitempty"` } diff --git a/models/subscription_group_signup_component_allocated_quantity.go b/models/subscription_group_signup_component_allocated_quantity.go new file mode 100644 index 00000000..14fc540a --- /dev/null +++ b/models/subscription_group_signup_component_allocated_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupSignupComponentAllocatedQuantity represents a SubscriptionGroupSignupComponentAllocatedQuantity struct. +// This is a container for one-of cases. +type SubscriptionGroupSignupComponentAllocatedQuantity struct { + value any + isString bool + isNumber bool +} + +// String converts the SubscriptionGroupSignupComponentAllocatedQuantity object to a string representation. +func (s SubscriptionGroupSignupComponentAllocatedQuantity) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupComponentAllocatedQuantity. +// It customizes the JSON marshaling process for SubscriptionGroupSignupComponentAllocatedQuantity objects. +func (s *SubscriptionGroupSignupComponentAllocatedQuantity) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionGroupSignupComponentAllocatedQuantityContainer.From*` functions to initialize the SubscriptionGroupSignupComponentAllocatedQuantity object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupSignupComponentAllocatedQuantity object to a map representation for JSON marshaling. +func (s *SubscriptionGroupSignupComponentAllocatedQuantity) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupComponentAllocatedQuantity. +// It customizes the JSON unmarshaling process for SubscriptionGroupSignupComponentAllocatedQuantity objects. +func (s *SubscriptionGroupSignupComponentAllocatedQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int), false, &s.isNumber), + ) + + s.value = result + return err +} + +func (s *SubscriptionGroupSignupComponentAllocatedQuantity) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionGroupSignupComponentAllocatedQuantity) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +// internalSubscriptionGroupSignupComponentAllocatedQuantity represents a subscriptionGroupSignupComponentAllocatedQuantity struct. +// This is a container for one-of cases. +type internalSubscriptionGroupSignupComponentAllocatedQuantity struct{} + +var SubscriptionGroupSignupComponentAllocatedQuantityContainer internalSubscriptionGroupSignupComponentAllocatedQuantity + +func (s *internalSubscriptionGroupSignupComponentAllocatedQuantity) FromString(val string) SubscriptionGroupSignupComponentAllocatedQuantity { + return SubscriptionGroupSignupComponentAllocatedQuantity{value: &val} +} + +func (s *internalSubscriptionGroupSignupComponentAllocatedQuantity) FromNumber(val int) SubscriptionGroupSignupComponentAllocatedQuantity { + return SubscriptionGroupSignupComponentAllocatedQuantity{value: &val} +} diff --git a/models/subscription_group_signup_component_component_id.go b/models/subscription_group_signup_component_component_id.go new file mode 100644 index 00000000..c422b76a --- /dev/null +++ b/models/subscription_group_signup_component_component_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupSignupComponentComponentId represents a SubscriptionGroupSignupComponentComponentId struct. +// This is a container for one-of cases. +type SubscriptionGroupSignupComponentComponentId struct { + value any + isString bool + isNumber bool +} + +// String converts the SubscriptionGroupSignupComponentComponentId object to a string representation. +func (s SubscriptionGroupSignupComponentComponentId) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupComponentComponentId. +// It customizes the JSON marshaling process for SubscriptionGroupSignupComponentComponentId objects. +func (s *SubscriptionGroupSignupComponentComponentId) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionGroupSignupComponentComponentIdContainer.From*` functions to initialize the SubscriptionGroupSignupComponentComponentId object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupSignupComponentComponentId object to a map representation for JSON marshaling. +func (s *SubscriptionGroupSignupComponentComponentId) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupComponentComponentId. +// It customizes the JSON unmarshaling process for SubscriptionGroupSignupComponentComponentId objects. +func (s *SubscriptionGroupSignupComponentComponentId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int), false, &s.isNumber), + ) + + s.value = result + return err +} + +func (s *SubscriptionGroupSignupComponentComponentId) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionGroupSignupComponentComponentId) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +// internalSubscriptionGroupSignupComponentComponentId represents a subscriptionGroupSignupComponentComponentId struct. +// This is a container for one-of cases. +type internalSubscriptionGroupSignupComponentComponentId struct{} + +var SubscriptionGroupSignupComponentComponentIdContainer internalSubscriptionGroupSignupComponentComponentId + +func (s *internalSubscriptionGroupSignupComponentComponentId) FromString(val string) SubscriptionGroupSignupComponentComponentId { + return SubscriptionGroupSignupComponentComponentId{value: &val} +} + +func (s *internalSubscriptionGroupSignupComponentComponentId) FromNumber(val int) SubscriptionGroupSignupComponentComponentId { + return SubscriptionGroupSignupComponentComponentId{value: &val} +} diff --git a/models/subscription_group_signup_component_price_point_id.go b/models/subscription_group_signup_component_price_point_id.go new file mode 100644 index 00000000..c315447e --- /dev/null +++ b/models/subscription_group_signup_component_price_point_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupSignupComponentPricePointId represents a SubscriptionGroupSignupComponentPricePointId struct. +// This is a container for one-of cases. +type SubscriptionGroupSignupComponentPricePointId struct { + value any + isString bool + isNumber bool +} + +// String converts the SubscriptionGroupSignupComponentPricePointId object to a string representation. +func (s SubscriptionGroupSignupComponentPricePointId) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupComponentPricePointId. +// It customizes the JSON marshaling process for SubscriptionGroupSignupComponentPricePointId objects. +func (s *SubscriptionGroupSignupComponentPricePointId) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionGroupSignupComponentPricePointIdContainer.From*` functions to initialize the SubscriptionGroupSignupComponentPricePointId object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupSignupComponentPricePointId object to a map representation for JSON marshaling. +func (s *SubscriptionGroupSignupComponentPricePointId) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupComponentPricePointId. +// It customizes the JSON unmarshaling process for SubscriptionGroupSignupComponentPricePointId objects. +func (s *SubscriptionGroupSignupComponentPricePointId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int), false, &s.isNumber), + ) + + s.value = result + return err +} + +func (s *SubscriptionGroupSignupComponentPricePointId) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionGroupSignupComponentPricePointId) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +// internalSubscriptionGroupSignupComponentPricePointId represents a subscriptionGroupSignupComponentPricePointId struct. +// This is a container for one-of cases. +type internalSubscriptionGroupSignupComponentPricePointId struct{} + +var SubscriptionGroupSignupComponentPricePointIdContainer internalSubscriptionGroupSignupComponentPricePointId + +func (s *internalSubscriptionGroupSignupComponentPricePointId) FromString(val string) SubscriptionGroupSignupComponentPricePointId { + return SubscriptionGroupSignupComponentPricePointId{value: &val} +} + +func (s *internalSubscriptionGroupSignupComponentPricePointId) FromNumber(val int) SubscriptionGroupSignupComponentPricePointId { + return SubscriptionGroupSignupComponentPricePointId{value: &val} +} diff --git a/models/subscription_group_signup_component_unit_balance.go b/models/subscription_group_signup_component_unit_balance.go new file mode 100644 index 00000000..08d41bc8 --- /dev/null +++ b/models/subscription_group_signup_component_unit_balance.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupSignupComponentUnitBalance represents a SubscriptionGroupSignupComponentUnitBalance struct. +// This is a container for one-of cases. +type SubscriptionGroupSignupComponentUnitBalance struct { + value any + isString bool + isNumber bool +} + +// String converts the SubscriptionGroupSignupComponentUnitBalance object to a string representation. +func (s SubscriptionGroupSignupComponentUnitBalance) String() string { + if bytes, err := json.Marshal(s.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupComponentUnitBalance. +// It customizes the JSON marshaling process for SubscriptionGroupSignupComponentUnitBalance objects. +func (s *SubscriptionGroupSignupComponentUnitBalance) MarshalJSON() ( + []byte, + error) { + if s.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.SubscriptionGroupSignupComponentUnitBalanceContainer.From*` functions to initialize the SubscriptionGroupSignupComponentUnitBalance object.") + } + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupSignupComponentUnitBalance object to a map representation for JSON marshaling. +func (s *SubscriptionGroupSignupComponentUnitBalance) toMap() any { + switch obj := s.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupComponentUnitBalance. +// It customizes the JSON unmarshaling process for SubscriptionGroupSignupComponentUnitBalance objects. +func (s *SubscriptionGroupSignupComponentUnitBalance) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &s.isString), + NewTypeHolder(new(int), false, &s.isNumber), + ) + + s.value = result + return err +} + +func (s *SubscriptionGroupSignupComponentUnitBalance) AsString() ( + *string, + bool) { + if !s.isString { + return nil, false + } + return s.value.(*string), true +} + +func (s *SubscriptionGroupSignupComponentUnitBalance) AsNumber() ( + *int, + bool) { + if !s.isNumber { + return nil, false + } + return s.value.(*int), true +} + +// internalSubscriptionGroupSignupComponentUnitBalance represents a subscriptionGroupSignupComponentUnitBalance struct. +// This is a container for one-of cases. +type internalSubscriptionGroupSignupComponentUnitBalance struct{} + +var SubscriptionGroupSignupComponentUnitBalanceContainer internalSubscriptionGroupSignupComponentUnitBalance + +func (s *internalSubscriptionGroupSignupComponentUnitBalance) FromString(val string) SubscriptionGroupSignupComponentUnitBalance { + return SubscriptionGroupSignupComponentUnitBalance{value: &val} +} + +func (s *internalSubscriptionGroupSignupComponentUnitBalance) FromNumber(val int) SubscriptionGroupSignupComponentUnitBalance { + return SubscriptionGroupSignupComponentUnitBalance{value: &val} +} diff --git a/models/subscription_group_signup_error.go b/models/subscription_group_signup_error.go index 3c692567..bda684f3 100644 --- a/models/subscription_group_signup_error.go +++ b/models/subscription_group_signup_error.go @@ -1,73 +1,75 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupSignupError represents a SubscriptionGroupSignupError struct. type SubscriptionGroupSignupError struct { - // Object that as key have subscription position in request subscriptions array and as value subscription errors object. - Subscriptions map[string]SubscriptionGroupSubscriptionError `json:"subscriptions,omitempty"` - PayerReference *string `json:"payer_reference,omitempty"` - Payer *PayerError `json:"payer,omitempty"` - SubscriptionGroup []string `json:"subscription_group,omitempty"` - PaymentProfileId *string `json:"payment_profile_id,omitempty"` - PayerId *string `json:"payer_id,omitempty"` + // Object that as key have subscription position in request subscriptions array and as value subscription errors object. + Subscriptions map[string]SubscriptionGroupSubscriptionError `json:"subscriptions,omitempty"` + PayerReference *string `json:"payer_reference,omitempty"` + Payer *PayerError `json:"payer,omitempty"` + SubscriptionGroup []string `json:"subscription_group,omitempty"` + PaymentProfileId *string `json:"payment_profile_id,omitempty"` + PayerId *string `json:"payer_id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupError. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupError. // It customizes the JSON marshaling process for SubscriptionGroupSignupError objects. func (s *SubscriptionGroupSignupError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupSignupError object to a map representation for JSON marshaling. func (s *SubscriptionGroupSignupError) toMap() map[string]any { - structMap := make(map[string]any) - if s.Subscriptions != nil { - structMap["subscriptions"] = s.Subscriptions - } - if s.PayerReference != nil { - structMap["payer_reference"] = s.PayerReference - } - if s.Payer != nil { - structMap["payer"] = s.Payer.toMap() - } - if s.SubscriptionGroup != nil { - structMap["subscription_group"] = s.SubscriptionGroup - } - if s.PaymentProfileId != nil { - structMap["payment_profile_id"] = s.PaymentProfileId - } - if s.PayerId != nil { - structMap["payer_id"] = s.PayerId - } - return structMap + structMap := make(map[string]any) + if s.Subscriptions != nil { + structMap["subscriptions"] = s.Subscriptions + } + if s.PayerReference != nil { + structMap["payer_reference"] = s.PayerReference + } + if s.Payer != nil { + structMap["payer"] = s.Payer.toMap() + } + if s.SubscriptionGroup != nil { + structMap["subscription_group"] = s.SubscriptionGroup + } + if s.PaymentProfileId != nil { + structMap["payment_profile_id"] = s.PaymentProfileId + } + if s.PayerId != nil { + structMap["payer_id"] = s.PayerId + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupError. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupError. // It customizes the JSON unmarshaling process for SubscriptionGroupSignupError objects. func (s *SubscriptionGroupSignupError) UnmarshalJSON(input []byte) error { - temp := &struct { - Subscriptions map[string]SubscriptionGroupSubscriptionError `json:"subscriptions,omitempty"` - PayerReference *string `json:"payer_reference,omitempty"` - Payer *PayerError `json:"payer,omitempty"` - SubscriptionGroup []string `json:"subscription_group,omitempty"` - PaymentProfileId *string `json:"payment_profile_id,omitempty"` - PayerId *string `json:"payer_id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Subscriptions = temp.Subscriptions - s.PayerReference = temp.PayerReference - s.Payer = temp.Payer - s.SubscriptionGroup = temp.SubscriptionGroup - s.PaymentProfileId = temp.PaymentProfileId - s.PayerId = temp.PayerId - return nil + var temp subscriptionGroupSignupError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Subscriptions = temp.Subscriptions + s.PayerReference = temp.PayerReference + s.Payer = temp.Payer + s.SubscriptionGroup = temp.SubscriptionGroup + s.PaymentProfileId = temp.PaymentProfileId + s.PayerId = temp.PayerId + return nil +} + +// TODO +type subscriptionGroupSignupError struct { + Subscriptions map[string]SubscriptionGroupSubscriptionError `json:"subscriptions,omitempty"` + PayerReference *string `json:"payer_reference,omitempty"` + Payer *PayerError `json:"payer,omitempty"` + SubscriptionGroup []string `json:"subscription_group,omitempty"` + PaymentProfileId *string `json:"payment_profile_id,omitempty"` + PayerId *string `json:"payer_id,omitempty"` } diff --git a/models/subscription_group_signup_failure.go b/models/subscription_group_signup_failure.go new file mode 100644 index 00000000..47632553 --- /dev/null +++ b/models/subscription_group_signup_failure.go @@ -0,0 +1,68 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupSignupFailure represents a SubscriptionGroupSignupFailure struct. +type SubscriptionGroupSignupFailure struct { + SubscriptionGroup SubscriptionGroupSignupFailureData `json:"subscription_group"` + Customer *string `json:"customer"` +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupFailure. +// It customizes the JSON marshaling process for SubscriptionGroupSignupFailure objects. +func (s *SubscriptionGroupSignupFailure) MarshalJSON() ( + []byte, + error) { + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupSignupFailure object to a map representation for JSON marshaling. +func (s *SubscriptionGroupSignupFailure) toMap() map[string]any { + structMap := make(map[string]any) + structMap["subscription_group"] = s.SubscriptionGroup.toMap() + if s.Customer != nil { + structMap["customer"] = s.Customer + } else { + structMap["customer"] = nil + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupFailure. +// It customizes the JSON unmarshaling process for SubscriptionGroupSignupFailure objects. +func (s *SubscriptionGroupSignupFailure) UnmarshalJSON(input []byte) error { + var temp subscriptionGroupSignupFailure + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.SubscriptionGroup = *temp.SubscriptionGroup + s.Customer = temp.Customer + return nil +} + +// TODO +type subscriptionGroupSignupFailure struct { + SubscriptionGroup *SubscriptionGroupSignupFailureData `json:"subscription_group"` + Customer *string `json:"customer"` +} + +func (s *subscriptionGroupSignupFailure) validate() error { + var errs []string + if s.SubscriptionGroup == nil { + errs = append(errs, "required field `subscription_group` is missing for type `Subscription Group Signup Failure`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/subscription_group_signup_failure_data.go b/models/subscription_group_signup_failure_data.go new file mode 100644 index 00000000..76dc1a0c --- /dev/null +++ b/models/subscription_group_signup_failure_data.go @@ -0,0 +1,86 @@ +package models + +import ( + "encoding/json" +) + +// SubscriptionGroupSignupFailureData represents a SubscriptionGroupSignupFailureData struct. +type SubscriptionGroupSignupFailureData struct { + PayerId *int `json:"payer_id,omitempty"` + PayerReference *string `json:"payer_reference,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + PaymentCollectionMethod *string `json:"payment_collection_method,omitempty"` + PayerAttributes *PayerAttributes `json:"payer_attributes,omitempty"` + CreditCardAttributes *SubscriptionGroupCreditCard `json:"credit_card_attributes,omitempty"` + BankAccountAttributes *SubscriptionGroupBankAccount `json:"bank_account_attributes,omitempty"` + Subscriptions []SubscriptionGroupSignupItem `json:"subscriptions,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupFailureData. +// It customizes the JSON marshaling process for SubscriptionGroupSignupFailureData objects. +func (s *SubscriptionGroupSignupFailureData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupSignupFailureData object to a map representation for JSON marshaling. +func (s *SubscriptionGroupSignupFailureData) toMap() map[string]any { + structMap := make(map[string]any) + if s.PayerId != nil { + structMap["payer_id"] = s.PayerId + } + if s.PayerReference != nil { + structMap["payer_reference"] = s.PayerReference + } + if s.PaymentProfileId != nil { + structMap["payment_profile_id"] = s.PaymentProfileId + } + if s.PaymentCollectionMethod != nil { + structMap["payment_collection_method"] = s.PaymentCollectionMethod + } + if s.PayerAttributes != nil { + structMap["payer_attributes"] = s.PayerAttributes.toMap() + } + if s.CreditCardAttributes != nil { + structMap["credit_card_attributes"] = s.CreditCardAttributes.toMap() + } + if s.BankAccountAttributes != nil { + structMap["bank_account_attributes"] = s.BankAccountAttributes.toMap() + } + if s.Subscriptions != nil { + structMap["subscriptions"] = s.Subscriptions + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupFailureData. +// It customizes the JSON unmarshaling process for SubscriptionGroupSignupFailureData objects. +func (s *SubscriptionGroupSignupFailureData) UnmarshalJSON(input []byte) error { + var temp subscriptionGroupSignupFailureData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.PayerId = temp.PayerId + s.PayerReference = temp.PayerReference + s.PaymentProfileId = temp.PaymentProfileId + s.PaymentCollectionMethod = temp.PaymentCollectionMethod + s.PayerAttributes = temp.PayerAttributes + s.CreditCardAttributes = temp.CreditCardAttributes + s.BankAccountAttributes = temp.BankAccountAttributes + s.Subscriptions = temp.Subscriptions + return nil +} + +// TODO +type subscriptionGroupSignupFailureData struct { + PayerId *int `json:"payer_id,omitempty"` + PayerReference *string `json:"payer_reference,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + PaymentCollectionMethod *string `json:"payment_collection_method,omitempty"` + PayerAttributes *PayerAttributes `json:"payer_attributes,omitempty"` + CreditCardAttributes *SubscriptionGroupCreditCard `json:"credit_card_attributes,omitempty"` + BankAccountAttributes *SubscriptionGroupBankAccount `json:"bank_account_attributes,omitempty"` + Subscriptions []SubscriptionGroupSignupItem `json:"subscriptions,omitempty"` +} diff --git a/models/subscription_group_signup_item.go b/models/subscription_group_signup_item.go index 2a6c5407..28817751 100644 --- a/models/subscription_group_signup_item.go +++ b/models/subscription_group_signup_item.go @@ -1,126 +1,128 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupSignupItem represents a SubscriptionGroupSignupItem struct. type SubscriptionGroupSignupItem struct { - // The API Handle of the product for which you are creating a subscription. Required, unless a `product_id` is given instead. - ProductHandle *string `json:"product_handle,omitempty"` - // The Product ID of the product for which you are creating a subscription. You can pass either `product_id` or `product_handle`. - ProductId *int `json:"product_id,omitempty"` - // The ID of the particular price point on the product. - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - // The user-friendly API handle of a product's particular price point. - ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` - // Use in place of passing product and component information to set up the subscription with an existing offer. May be either the Chargify ID of the offer or its handle prefixed with `handle:` - OfferId *int `json:"offer_id,omitempty"` - // The reference value (provided by your app) for the subscription itelf. - Reference *string `json:"reference,omitempty"` - // One of the subscriptions must be marked as primary in the group. - Primary *bool `json:"primary,omitempty"` - // (Optional) If Multi-Currency is enabled and the currency is configured in Chargify, pass it at signup to create a subscription on a non-default currency. Note that you cannot update the currency of an existing subscription. - Currency *string `json:"currency,omitempty"` - // An array for all the coupons attached to the subscription. - CouponCodes []string `json:"coupon_codes,omitempty"` - Components []SubscriptionGroupSignupComponent `json:"components,omitempty"` - // (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription - CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` - // (Optional). Cannot be used when also specifying next_billing_at - CalendarBilling *CalendarBilling `json:"calendar_billing,omitempty"` - // (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. - Metafields map[string]string `json:"metafields,omitempty"` + // The API Handle of the product for which you are creating a subscription. Required, unless a `product_id` is given instead. + ProductHandle *string `json:"product_handle,omitempty"` + // The Product ID of the product for which you are creating a subscription. You can pass either `product_id` or `product_handle`. + ProductId *int `json:"product_id,omitempty"` + // The ID of the particular price point on the product. + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + // The user-friendly API handle of a product's particular price point. + ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` + // Use in place of passing product and component information to set up the subscription with an existing offer. May be either the Chargify ID of the offer or its handle prefixed with `handle:` + OfferId *int `json:"offer_id,omitempty"` + // The reference value (provided by your app) for the subscription itelf. + Reference *string `json:"reference,omitempty"` + // One of the subscriptions must be marked as primary in the group. + Primary *bool `json:"primary,omitempty"` + // (Optional) If Multi-Currency is enabled and the currency is configured in Chargify, pass it at signup to create a subscription on a non-default currency. Note that you cannot update the currency of an existing subscription. + Currency *string `json:"currency,omitempty"` + // An array for all the coupons attached to the subscription. + CouponCodes []string `json:"coupon_codes,omitempty"` + Components []SubscriptionGroupSignupComponent `json:"components,omitempty"` + // (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription + CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` + // (Optional). Cannot be used when also specifying next_billing_at + CalendarBilling *CalendarBilling `json:"calendar_billing,omitempty"` + // (Optional) A set of key/value pairs representing custom fields and their values. Metafields will be created “on-the-fly” in your site for a given key, if they have not been created yet. + Metafields map[string]string `json:"metafields,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupItem. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupItem. // It customizes the JSON marshaling process for SubscriptionGroupSignupItem objects. func (s *SubscriptionGroupSignupItem) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupSignupItem object to a map representation for JSON marshaling. func (s *SubscriptionGroupSignupItem) toMap() map[string]any { - structMap := make(map[string]any) - if s.ProductHandle != nil { - structMap["product_handle"] = s.ProductHandle - } - if s.ProductId != nil { - structMap["product_id"] = s.ProductId - } - if s.ProductPricePointId != nil { - structMap["product_price_point_id"] = s.ProductPricePointId - } - if s.ProductPricePointHandle != nil { - structMap["product_price_point_handle"] = s.ProductPricePointHandle - } - if s.OfferId != nil { - structMap["offer_id"] = s.OfferId - } - if s.Reference != nil { - structMap["reference"] = s.Reference - } - if s.Primary != nil { - structMap["primary"] = s.Primary - } - if s.Currency != nil { - structMap["currency"] = s.Currency - } - if s.CouponCodes != nil { - structMap["coupon_codes"] = s.CouponCodes - } - if s.Components != nil { - structMap["components"] = s.Components - } - if s.CustomPrice != nil { - structMap["custom_price"] = s.CustomPrice.toMap() - } - if s.CalendarBilling != nil { - structMap["calendar_billing"] = s.CalendarBilling.toMap() - } - if s.Metafields != nil { - structMap["metafields"] = s.Metafields - } - return structMap + structMap := make(map[string]any) + if s.ProductHandle != nil { + structMap["product_handle"] = s.ProductHandle + } + if s.ProductId != nil { + structMap["product_id"] = s.ProductId + } + if s.ProductPricePointId != nil { + structMap["product_price_point_id"] = s.ProductPricePointId + } + if s.ProductPricePointHandle != nil { + structMap["product_price_point_handle"] = s.ProductPricePointHandle + } + if s.OfferId != nil { + structMap["offer_id"] = s.OfferId + } + if s.Reference != nil { + structMap["reference"] = s.Reference + } + if s.Primary != nil { + structMap["primary"] = s.Primary + } + if s.Currency != nil { + structMap["currency"] = s.Currency + } + if s.CouponCodes != nil { + structMap["coupon_codes"] = s.CouponCodes + } + if s.Components != nil { + structMap["components"] = s.Components + } + if s.CustomPrice != nil { + structMap["custom_price"] = s.CustomPrice.toMap() + } + if s.CalendarBilling != nil { + structMap["calendar_billing"] = s.CalendarBilling.toMap() + } + if s.Metafields != nil { + structMap["metafields"] = s.Metafields + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupItem. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupItem. // It customizes the JSON unmarshaling process for SubscriptionGroupSignupItem objects. func (s *SubscriptionGroupSignupItem) UnmarshalJSON(input []byte) error { - temp := &struct { - ProductHandle *string `json:"product_handle,omitempty"` - ProductId *int `json:"product_id,omitempty"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` - OfferId *int `json:"offer_id,omitempty"` - Reference *string `json:"reference,omitempty"` - Primary *bool `json:"primary,omitempty"` - Currency *string `json:"currency,omitempty"` - CouponCodes []string `json:"coupon_codes,omitempty"` - Components []SubscriptionGroupSignupComponent `json:"components,omitempty"` - CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` - CalendarBilling *CalendarBilling `json:"calendar_billing,omitempty"` - Metafields map[string]string `json:"metafields,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.ProductHandle = temp.ProductHandle - s.ProductId = temp.ProductId - s.ProductPricePointId = temp.ProductPricePointId - s.ProductPricePointHandle = temp.ProductPricePointHandle - s.OfferId = temp.OfferId - s.Reference = temp.Reference - s.Primary = temp.Primary - s.Currency = temp.Currency - s.CouponCodes = temp.CouponCodes - s.Components = temp.Components - s.CustomPrice = temp.CustomPrice - s.CalendarBilling = temp.CalendarBilling - s.Metafields = temp.Metafields - return nil + var temp subscriptionGroupSignupItem + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.ProductHandle = temp.ProductHandle + s.ProductId = temp.ProductId + s.ProductPricePointId = temp.ProductPricePointId + s.ProductPricePointHandle = temp.ProductPricePointHandle + s.OfferId = temp.OfferId + s.Reference = temp.Reference + s.Primary = temp.Primary + s.Currency = temp.Currency + s.CouponCodes = temp.CouponCodes + s.Components = temp.Components + s.CustomPrice = temp.CustomPrice + s.CalendarBilling = temp.CalendarBilling + s.Metafields = temp.Metafields + return nil +} + +// TODO +type subscriptionGroupSignupItem struct { + ProductHandle *string `json:"product_handle,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` + OfferId *int `json:"offer_id,omitempty"` + Reference *string `json:"reference,omitempty"` + Primary *bool `json:"primary,omitempty"` + Currency *string `json:"currency,omitempty"` + CouponCodes []string `json:"coupon_codes,omitempty"` + Components []SubscriptionGroupSignupComponent `json:"components,omitempty"` + CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` + CalendarBilling *CalendarBilling `json:"calendar_billing,omitempty"` + Metafields map[string]string `json:"metafields,omitempty"` } diff --git a/models/subscription_group_signup_request.go b/models/subscription_group_signup_request.go index 5be749f2..87438d33 100644 --- a/models/subscription_group_signup_request.go +++ b/models/subscription_group_signup_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionGroupSignupRequest represents a SubscriptionGroupSignupRequest struct. type SubscriptionGroupSignupRequest struct { - SubscriptionGroup SubscriptionGroupSignup `json:"subscription_group"` + SubscriptionGroup SubscriptionGroupSignup `json:"subscription_group"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupRequest. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupRequest. // It customizes the JSON marshaling process for SubscriptionGroupSignupRequest objects. func (s *SubscriptionGroupSignupRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupSignupRequest object to a map representation for JSON marshaling. func (s *SubscriptionGroupSignupRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscription_group"] = s.SubscriptionGroup.toMap() - return structMap + structMap := make(map[string]any) + structMap["subscription_group"] = s.SubscriptionGroup.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupRequest. // It customizes the JSON unmarshaling process for SubscriptionGroupSignupRequest objects. func (s *SubscriptionGroupSignupRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - SubscriptionGroup SubscriptionGroupSignup `json:"subscription_group"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.SubscriptionGroup = temp.SubscriptionGroup - return nil + var temp subscriptionGroupSignupRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.SubscriptionGroup = *temp.SubscriptionGroup + return nil +} + +// TODO +type subscriptionGroupSignupRequest struct { + SubscriptionGroup *SubscriptionGroupSignup `json:"subscription_group"` +} + +func (s *subscriptionGroupSignupRequest) validate() error { + var errs []string + if s.SubscriptionGroup == nil { + errs = append(errs, "required field `subscription_group` is missing for type `Subscription Group Signup Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_group_signup_response.go b/models/subscription_group_signup_response.go index f20dc1db..593f0c49 100644 --- a/models/subscription_group_signup_response.go +++ b/models/subscription_group_signup_response.go @@ -1,111 +1,133 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // SubscriptionGroupSignupResponse represents a SubscriptionGroupSignupResponse struct. type SubscriptionGroupSignupResponse struct { - Uid *string `json:"uid,omitempty"` - Scheme *int `json:"scheme,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - SubscriptionIds []int `json:"subscription_ids,omitempty"` - PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` - NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` - State *string `json:"state,omitempty"` - CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` - Subscriptions []SubscriptionGroupItem `json:"subscriptions,omitempty"` - // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. - PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` + Uid *string `json:"uid,omitempty"` + Scheme *int `json:"scheme,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + SubscriptionIds []int `json:"subscription_ids,omitempty"` + PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` + NextAssessmentAt *time.Time `json:"next_assessment_at,omitempty"` + // The state of a subscription. + // * **Live States** + // * `active` - A normal, active subscription. It is not in a trial and is paid and up to date. + // * `assessing` - An internal (transient) state that indicates a subscription is in the middle of periodic assessment. Do not base any access decisions in your app on this state, as it may not always be exposed. + // * `pending` - An internal (transient) state that indicates a subscription is in the creation process. Do not base any access decisions in your app on this state, as it may not always be exposed. + // * `trialing` - A subscription in trialing state has a valid trial subscription. This type of subscription may transition to active once payment is received when the trial has ended. Otherwise, it may go to a Problem or End of Life state. + // * `paused` - An internal state that indicates that your account with Advanced Billing is in arrears. + // * **Problem States** + // * `past_due` - Indicates that the most recent payment has failed, and payment is past due for this subscription. If you have enabled our automated dunning, this subscription will be in the dunning process (additional status and callbacks from the dunning process will be available in the future). If you are handling dunning and payment updates yourself, you will want to use this state to initiate a payment update from your customers. + // * `soft_failure` - Indicates that normal assessment/processing of the subscription has failed for a reason that cannot be fixed by the Customer. For example, a Soft Fail may result from a timeout at the gateway or incorrect credentials on your part. The subscriptions should be retried automatically. An interface is being built for you to review problems resulting from these events to take manual action when needed. + // * `unpaid` - Indicates an unpaid subscription. A subscription is marked unpaid if the retry period expires and you have configured your [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) settings to have a Final Action of `mark the subscription unpaid`. + // * **End of Life States** + // * `canceled` - Indicates a canceled subscription. This may happen at your request (via the API or the web interface) or due to the expiration of the [Dunning](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405505141005) process without payment. See the [Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021) documentation for info on how to restart a canceled subscription. + // While a subscription is canceled, its period will not advance, it will not accrue any new charges, and Advanced Billing will not attempt to collect the overdue balance. + // * `expired` - Indicates a subscription that has expired due to running its normal life cycle. Some products may be configured to have an expiration period. An expired subscription then is one that stayed active until it fulfilled its full period. + // * `failed_to_create` - Indicates that signup has failed. (You may see this state in a signup_failure webhook.) + // * `on_hold` - Indicates that a subscription’s billing has been temporarily stopped. While it is expected that the subscription will resume and return to active status, this is still treated as an “End of Life” state because the customer is not paying for services during this time. + // * `suspended` - Indicates that a prepaid subscription has used up all their prepayment balance. If a prepayment is applied, it will return to an active state. + // * `trial_ended` - A subscription in a trial_ended state is a subscription that completed a no-obligation trial and did not have a card on file at the expiration of the trial period. See [Product Pricing – No Obligation Trials](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221) for more details. + // See [Subscription States](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404222005773) for more info about subscription states and state transitions. + State *SubscriptionState `json:"state,omitempty"` + CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` + Subscriptions []SubscriptionGroupItem `json:"subscriptions,omitempty"` + // The type of payment collection to be used in the subscription. For legacy Statements Architecture valid options are - `invoice`, `automatic`. For current Relationship Invoicing Architecture valid options are - `remittance`, `automatic`, `prepaid`. + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupResponse. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupResponse. // It customizes the JSON marshaling process for SubscriptionGroupSignupResponse objects. func (s *SubscriptionGroupSignupResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupSignupResponse object to a map representation for JSON marshaling. func (s *SubscriptionGroupSignupResponse) toMap() map[string]any { - structMap := make(map[string]any) - if s.Uid != nil { - structMap["uid"] = s.Uid - } - if s.Scheme != nil { - structMap["scheme"] = s.Scheme - } - if s.CustomerId != nil { - structMap["customer_id"] = s.CustomerId - } - if s.PaymentProfileId != nil { - structMap["payment_profile_id"] = s.PaymentProfileId - } - if s.SubscriptionIds != nil { - structMap["subscription_ids"] = s.SubscriptionIds - } - if s.PrimarySubscriptionId != nil { - structMap["primary_subscription_id"] = s.PrimarySubscriptionId - } - if s.NextAssessmentAt != nil { - structMap["next_assessment_at"] = s.NextAssessmentAt.Format(time.RFC3339) - } - if s.State != nil { - structMap["state"] = s.State - } - if s.CancelAtEndOfPeriod != nil { - structMap["cancel_at_end_of_period"] = s.CancelAtEndOfPeriod - } - if s.Subscriptions != nil { - structMap["subscriptions"] = s.Subscriptions - } - if s.PaymentCollectionMethod != nil { - structMap["payment_collection_method"] = s.PaymentCollectionMethod - } - return structMap + structMap := make(map[string]any) + if s.Uid != nil { + structMap["uid"] = s.Uid + } + if s.Scheme != nil { + structMap["scheme"] = s.Scheme + } + if s.CustomerId != nil { + structMap["customer_id"] = s.CustomerId + } + if s.PaymentProfileId != nil { + structMap["payment_profile_id"] = s.PaymentProfileId + } + if s.SubscriptionIds != nil { + structMap["subscription_ids"] = s.SubscriptionIds + } + if s.PrimarySubscriptionId != nil { + structMap["primary_subscription_id"] = s.PrimarySubscriptionId + } + if s.NextAssessmentAt != nil { + structMap["next_assessment_at"] = s.NextAssessmentAt.Format(time.RFC3339) + } + if s.State != nil { + structMap["state"] = s.State + } + if s.CancelAtEndOfPeriod != nil { + structMap["cancel_at_end_of_period"] = s.CancelAtEndOfPeriod + } + if s.Subscriptions != nil { + structMap["subscriptions"] = s.Subscriptions + } + if s.PaymentCollectionMethod != nil { + structMap["payment_collection_method"] = s.PaymentCollectionMethod + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupResponse. // It customizes the JSON unmarshaling process for SubscriptionGroupSignupResponse objects. func (s *SubscriptionGroupSignupResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Uid *string `json:"uid,omitempty"` - Scheme *int `json:"scheme,omitempty"` - CustomerId *int `json:"customer_id,omitempty"` - PaymentProfileId *int `json:"payment_profile_id,omitempty"` - SubscriptionIds []int `json:"subscription_ids,omitempty"` - PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` - NextAssessmentAt *string `json:"next_assessment_at,omitempty"` - State *string `json:"state,omitempty"` - CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` - Subscriptions []SubscriptionGroupItem `json:"subscriptions,omitempty"` - PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Uid = temp.Uid - s.Scheme = temp.Scheme - s.CustomerId = temp.CustomerId - s.PaymentProfileId = temp.PaymentProfileId - s.SubscriptionIds = temp.SubscriptionIds - s.PrimarySubscriptionId = temp.PrimarySubscriptionId - if temp.NextAssessmentAt != nil { - NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) - if err != nil { - log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) - } - s.NextAssessmentAt = &NextAssessmentAtVal - } - s.State = temp.State - s.CancelAtEndOfPeriod = temp.CancelAtEndOfPeriod - s.Subscriptions = temp.Subscriptions - s.PaymentCollectionMethod = temp.PaymentCollectionMethod - return nil + var temp subscriptionGroupSignupResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Uid = temp.Uid + s.Scheme = temp.Scheme + s.CustomerId = temp.CustomerId + s.PaymentProfileId = temp.PaymentProfileId + s.SubscriptionIds = temp.SubscriptionIds + s.PrimarySubscriptionId = temp.PrimarySubscriptionId + if temp.NextAssessmentAt != nil { + NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) + if err != nil { + log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) + } + s.NextAssessmentAt = &NextAssessmentAtVal + } + s.State = temp.State + s.CancelAtEndOfPeriod = temp.CancelAtEndOfPeriod + s.Subscriptions = temp.Subscriptions + s.PaymentCollectionMethod = temp.PaymentCollectionMethod + return nil +} + +// TODO +type subscriptionGroupSignupResponse struct { + Uid *string `json:"uid,omitempty"` + Scheme *int `json:"scheme,omitempty"` + CustomerId *int `json:"customer_id,omitempty"` + PaymentProfileId *int `json:"payment_profile_id,omitempty"` + SubscriptionIds []int `json:"subscription_ids,omitempty"` + PrimarySubscriptionId *int `json:"primary_subscription_id,omitempty"` + NextAssessmentAt *string `json:"next_assessment_at,omitempty"` + State *SubscriptionState `json:"state,omitempty"` + CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period,omitempty"` + Subscriptions []SubscriptionGroupItem `json:"subscriptions,omitempty"` + PaymentCollectionMethod *CollectionMethod `json:"payment_collection_method,omitempty"` } diff --git a/models/subscription_group_signup_success.go b/models/subscription_group_signup_success.go new file mode 100644 index 00000000..44862141 --- /dev/null +++ b/models/subscription_group_signup_success.go @@ -0,0 +1,67 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupSignupSuccess represents a SubscriptionGroupSignupSuccess struct. +type SubscriptionGroupSignupSuccess struct { + SubscriptionGroup SubscriptionGroupSignupSuccessData `json:"subscription_group"` + Customer Customer `json:"customer"` +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupSuccess. +// It customizes the JSON marshaling process for SubscriptionGroupSignupSuccess objects. +func (s *SubscriptionGroupSignupSuccess) MarshalJSON() ( + []byte, + error) { + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupSignupSuccess object to a map representation for JSON marshaling. +func (s *SubscriptionGroupSignupSuccess) toMap() map[string]any { + structMap := make(map[string]any) + structMap["subscription_group"] = s.SubscriptionGroup.toMap() + structMap["customer"] = s.Customer.toMap() + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupSuccess. +// It customizes the JSON unmarshaling process for SubscriptionGroupSignupSuccess objects. +func (s *SubscriptionGroupSignupSuccess) UnmarshalJSON(input []byte) error { + var temp subscriptionGroupSignupSuccess + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.SubscriptionGroup = *temp.SubscriptionGroup + s.Customer = *temp.Customer + return nil +} + +// TODO +type subscriptionGroupSignupSuccess struct { + SubscriptionGroup *SubscriptionGroupSignupSuccessData `json:"subscription_group"` + Customer *Customer `json:"customer"` +} + +func (s *subscriptionGroupSignupSuccess) validate() error { + var errs []string + if s.SubscriptionGroup == nil { + errs = append(errs, "required field `subscription_group` is missing for type `Subscription Group Signup Success`") + } + if s.Customer == nil { + errs = append(errs, "required field `customer` is missing for type `Subscription Group Signup Success`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/subscription_group_signup_success_data.go b/models/subscription_group_signup_success_data.go new file mode 100644 index 00000000..5c92ff0e --- /dev/null +++ b/models/subscription_group_signup_success_data.go @@ -0,0 +1,122 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// SubscriptionGroupSignupSuccessData represents a SubscriptionGroupSignupSuccessData struct. +type SubscriptionGroupSignupSuccessData struct { + Uid string `json:"uid"` + Scheme int `json:"scheme"` + CustomerId int `json:"customer_id"` + PaymentProfileId int `json:"payment_profile_id"` + SubscriptionIds []int `json:"subscription_ids"` + PrimarySubscriptionId int `json:"primary_subscription_id"` + NextAssessmentAt time.Time `json:"next_assessment_at"` + State string `json:"state"` + CancelAtEndOfPeriod bool `json:"cancel_at_end_of_period"` +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSignupSuccessData. +// It customizes the JSON marshaling process for SubscriptionGroupSignupSuccessData objects. +func (s *SubscriptionGroupSignupSuccessData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupSignupSuccessData object to a map representation for JSON marshaling. +func (s *SubscriptionGroupSignupSuccessData) toMap() map[string]any { + structMap := make(map[string]any) + structMap["uid"] = s.Uid + structMap["scheme"] = s.Scheme + structMap["customer_id"] = s.CustomerId + structMap["payment_profile_id"] = s.PaymentProfileId + structMap["subscription_ids"] = s.SubscriptionIds + structMap["primary_subscription_id"] = s.PrimarySubscriptionId + structMap["next_assessment_at"] = s.NextAssessmentAt.Format(time.RFC3339) + structMap["state"] = s.State + structMap["cancel_at_end_of_period"] = s.CancelAtEndOfPeriod + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSignupSuccessData. +// It customizes the JSON unmarshaling process for SubscriptionGroupSignupSuccessData objects. +func (s *SubscriptionGroupSignupSuccessData) UnmarshalJSON(input []byte) error { + var temp subscriptionGroupSignupSuccessData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.Uid = *temp.Uid + s.Scheme = *temp.Scheme + s.CustomerId = *temp.CustomerId + s.PaymentProfileId = *temp.PaymentProfileId + s.SubscriptionIds = *temp.SubscriptionIds + s.PrimarySubscriptionId = *temp.PrimarySubscriptionId + NextAssessmentAtVal, err := time.Parse(time.RFC3339, *temp.NextAssessmentAt) + if err != nil { + log.Fatalf("Cannot Parse next_assessment_at as % s format.", time.RFC3339) + } + s.NextAssessmentAt = NextAssessmentAtVal + s.State = *temp.State + s.CancelAtEndOfPeriod = *temp.CancelAtEndOfPeriod + return nil +} + +// TODO +type subscriptionGroupSignupSuccessData struct { + Uid *string `json:"uid"` + Scheme *int `json:"scheme"` + CustomerId *int `json:"customer_id"` + PaymentProfileId *int `json:"payment_profile_id"` + SubscriptionIds *[]int `json:"subscription_ids"` + PrimarySubscriptionId *int `json:"primary_subscription_id"` + NextAssessmentAt *string `json:"next_assessment_at"` + State *string `json:"state"` + CancelAtEndOfPeriod *bool `json:"cancel_at_end_of_period"` +} + +func (s *subscriptionGroupSignupSuccessData) validate() error { + var errs []string + if s.Uid == nil { + errs = append(errs, "required field `uid` is missing for type `Subscription Group Signup Success Data`") + } + if s.Scheme == nil { + errs = append(errs, "required field `scheme` is missing for type `Subscription Group Signup Success Data`") + } + if s.CustomerId == nil { + errs = append(errs, "required field `customer_id` is missing for type `Subscription Group Signup Success Data`") + } + if s.PaymentProfileId == nil { + errs = append(errs, "required field `payment_profile_id` is missing for type `Subscription Group Signup Success Data`") + } + if s.SubscriptionIds == nil { + errs = append(errs, "required field `subscription_ids` is missing for type `Subscription Group Signup Success Data`") + } + if s.PrimarySubscriptionId == nil { + errs = append(errs, "required field `primary_subscription_id` is missing for type `Subscription Group Signup Success Data`") + } + if s.NextAssessmentAt == nil { + errs = append(errs, "required field `next_assessment_at` is missing for type `Subscription Group Signup Success Data`") + } + if s.State == nil { + errs = append(errs, "required field `state` is missing for type `Subscription Group Signup Success Data`") + } + if s.CancelAtEndOfPeriod == nil { + errs = append(errs, "required field `cancel_at_end_of_period` is missing for type `Subscription Group Signup Success Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/subscription_group_single_error.go b/models/subscription_group_single_error.go new file mode 100644 index 00000000..51cece56 --- /dev/null +++ b/models/subscription_group_single_error.go @@ -0,0 +1,60 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionGroupSingleError represents a SubscriptionGroupSingleError struct. +type SubscriptionGroupSingleError struct { + SubscriptionGroup string `json:"subscription_group"` +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSingleError. +// It customizes the JSON marshaling process for SubscriptionGroupSingleError objects. +func (s *SubscriptionGroupSingleError) MarshalJSON() ( + []byte, + error) { + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionGroupSingleError object to a map representation for JSON marshaling. +func (s *SubscriptionGroupSingleError) toMap() map[string]any { + structMap := make(map[string]any) + structMap["subscription_group"] = s.SubscriptionGroup + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSingleError. +// It customizes the JSON unmarshaling process for SubscriptionGroupSingleError objects. +func (s *SubscriptionGroupSingleError) UnmarshalJSON(input []byte) error { + var temp subscriptionGroupSingleError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.SubscriptionGroup = *temp.SubscriptionGroup + return nil +} + +// TODO +type subscriptionGroupSingleError struct { + SubscriptionGroup *string `json:"subscription_group"` +} + +func (s *subscriptionGroupSingleError) validate() error { + var errs []string + if s.SubscriptionGroup == nil { + errs = append(errs, "required field `subscription_group` is missing for type `Subscription Group Single Error`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/subscription_group_subscription_error.go b/models/subscription_group_subscription_error.go index dc7b7d29..66f2bee0 100644 --- a/models/subscription_group_subscription_error.go +++ b/models/subscription_group_subscription_error.go @@ -1,61 +1,87 @@ package models import ( - "encoding/json" + "encoding/json" ) -// SubscriptionGroupSubscriptionError represents a SubscriptionGroupSubscriptionError struct. +// SubscriptionGroupSubscriptionError represents a SubscriptionGroupSubscriptionError struct. // Object which contains subscription errors. type SubscriptionGroupSubscriptionError struct { - Product []string `json:"product,omitempty"` - ProductPricePointId []string `json:"product_price_point_id,omitempty"` - PaymentProfile []string `json:"payment_profile,omitempty"` - PaymentProfileChargifyToken []string `json:"payment_profile.chargify_token,omitempty"` + Product []string `json:"product,omitempty"` + ProductPricePointId []string `json:"product_price_point_id,omitempty"` + PaymentProfile []string `json:"payment_profile,omitempty"` + PaymentProfileChargifyToken []string `json:"payment_profile.chargify_token,omitempty"` + Base []string `json:"base,omitempty"` + PaymentProfileExpirationMonth []string `json:"payment_profile.expiration_month,omitempty"` + PaymentProfileExpirationYear []string `json:"payment_profile.expiration_year,omitempty"` + PaymentProfileFullNumber []string `json:"payment_profile.full_number,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSubscriptionError. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupSubscriptionError. // It customizes the JSON marshaling process for SubscriptionGroupSubscriptionError objects. func (s *SubscriptionGroupSubscriptionError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupSubscriptionError object to a map representation for JSON marshaling. func (s *SubscriptionGroupSubscriptionError) toMap() map[string]any { - structMap := make(map[string]any) - if s.Product != nil { - structMap["product"] = s.Product - } - if s.ProductPricePointId != nil { - structMap["product_price_point_id"] = s.ProductPricePointId - } - if s.PaymentProfile != nil { - structMap["payment_profile"] = s.PaymentProfile - } - if s.PaymentProfileChargifyToken != nil { - structMap["payment_profile.chargify_token"] = s.PaymentProfileChargifyToken - } - return structMap + structMap := make(map[string]any) + if s.Product != nil { + structMap["product"] = s.Product + } + if s.ProductPricePointId != nil { + structMap["product_price_point_id"] = s.ProductPricePointId + } + if s.PaymentProfile != nil { + structMap["payment_profile"] = s.PaymentProfile + } + if s.PaymentProfileChargifyToken != nil { + structMap["payment_profile.chargify_token"] = s.PaymentProfileChargifyToken + } + if s.Base != nil { + structMap["base"] = s.Base + } + if s.PaymentProfileExpirationMonth != nil { + structMap["payment_profile.expiration_month"] = s.PaymentProfileExpirationMonth + } + if s.PaymentProfileExpirationYear != nil { + structMap["payment_profile.expiration_year"] = s.PaymentProfileExpirationYear + } + if s.PaymentProfileFullNumber != nil { + structMap["payment_profile.full_number"] = s.PaymentProfileFullNumber + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSubscriptionError. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupSubscriptionError. // It customizes the JSON unmarshaling process for SubscriptionGroupSubscriptionError objects. func (s *SubscriptionGroupSubscriptionError) UnmarshalJSON(input []byte) error { - temp := &struct { - Product []string `json:"product,omitempty"` - ProductPricePointId []string `json:"product_price_point_id,omitempty"` - PaymentProfile []string `json:"payment_profile,omitempty"` - PaymentProfileChargifyToken []string `json:"payment_profile.chargify_token,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Product = temp.Product - s.ProductPricePointId = temp.ProductPricePointId - s.PaymentProfile = temp.PaymentProfile - s.PaymentProfileChargifyToken = temp.PaymentProfileChargifyToken - return nil + var temp subscriptionGroupSubscriptionError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Product = temp.Product + s.ProductPricePointId = temp.ProductPricePointId + s.PaymentProfile = temp.PaymentProfile + s.PaymentProfileChargifyToken = temp.PaymentProfileChargifyToken + s.Base = temp.Base + s.PaymentProfileExpirationMonth = temp.PaymentProfileExpirationMonth + s.PaymentProfileExpirationYear = temp.PaymentProfileExpirationYear + s.PaymentProfileFullNumber = temp.PaymentProfileFullNumber + return nil +} + +// TODO +type subscriptionGroupSubscriptionError struct { + Product []string `json:"product,omitempty"` + ProductPricePointId []string `json:"product_price_point_id,omitempty"` + PaymentProfile []string `json:"payment_profile,omitempty"` + PaymentProfileChargifyToken []string `json:"payment_profile.chargify_token,omitempty"` + Base []string `json:"base,omitempty"` + PaymentProfileExpirationMonth []string `json:"payment_profile.expiration_month,omitempty"` + PaymentProfileExpirationYear []string `json:"payment_profile.expiration_year,omitempty"` + PaymentProfileFullNumber []string `json:"payment_profile.full_number,omitempty"` } diff --git a/models/subscription_group_update_error.go b/models/subscription_group_update_error.go index f86a10e7..2f698768 100644 --- a/models/subscription_group_update_error.go +++ b/models/subscription_group_update_error.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionGroupUpdateError represents a SubscriptionGroupUpdateError struct. type SubscriptionGroupUpdateError struct { - Members []SubscriptionGroupMemberError `json:"members,omitempty"` + Members []SubscriptionGroupMemberError `json:"members,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupUpdateError. +// MarshalJSON implements the json.Marshaler interface for SubscriptionGroupUpdateError. // It customizes the JSON marshaling process for SubscriptionGroupUpdateError objects. func (s *SubscriptionGroupUpdateError) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionGroupUpdateError object to a map representation for JSON marshaling. func (s *SubscriptionGroupUpdateError) toMap() map[string]any { - structMap := make(map[string]any) - if s.Members != nil { - structMap["members"] = s.Members - } - return structMap + structMap := make(map[string]any) + if s.Members != nil { + structMap["members"] = s.Members + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupUpdateError. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionGroupUpdateError. // It customizes the JSON unmarshaling process for SubscriptionGroupUpdateError objects. func (s *SubscriptionGroupUpdateError) UnmarshalJSON(input []byte) error { - temp := &struct { - Members []SubscriptionGroupMemberError `json:"members,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Members = temp.Members - return nil + var temp subscriptionGroupUpdateError + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Members = temp.Members + return nil +} + +// TODO +type subscriptionGroupUpdateError struct { + Members []SubscriptionGroupMemberError `json:"members,omitempty"` } diff --git a/models/subscription_included_coupon.go b/models/subscription_included_coupon.go index f370f10e..7f1f20f5 100644 --- a/models/subscription_included_coupon.go +++ b/models/subscription_included_coupon.go @@ -1,78 +1,92 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionIncludedCoupon represents a SubscriptionIncludedCoupon struct. type SubscriptionIncludedCoupon struct { - Code *string `json:"code,omitempty"` - UseCount *int `json:"use_count,omitempty"` - UsesAllowed *int `json:"uses_allowed,omitempty"` - ExpiresAt Optional[string] `json:"expires_at"` - Recurring *bool `json:"recurring,omitempty"` - AmountInCents Optional[int64] `json:"amount_in_cents"` - Percentage Optional[string] `json:"percentage"` + Code *string `json:"code,omitempty"` + UseCount *int `json:"use_count,omitempty"` + UsesAllowed *int `json:"uses_allowed,omitempty"` + ExpiresAt Optional[string] `json:"expires_at"` + Recurring *bool `json:"recurring,omitempty"` + AmountInCents Optional[int64] `json:"amount_in_cents"` + Percentage Optional[string] `json:"percentage"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionIncludedCoupon. +// MarshalJSON implements the json.Marshaler interface for SubscriptionIncludedCoupon. // It customizes the JSON marshaling process for SubscriptionIncludedCoupon objects. func (s *SubscriptionIncludedCoupon) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionIncludedCoupon object to a map representation for JSON marshaling. func (s *SubscriptionIncludedCoupon) toMap() map[string]any { - structMap := make(map[string]any) - if s.Code != nil { - structMap["code"] = s.Code - } - if s.UseCount != nil { - structMap["use_count"] = s.UseCount - } - if s.UsesAllowed != nil { - structMap["uses_allowed"] = s.UsesAllowed - } - if s.ExpiresAt.IsValueSet() { - structMap["expires_at"] = s.ExpiresAt.Value() - } - if s.Recurring != nil { - structMap["recurring"] = s.Recurring - } - if s.AmountInCents.IsValueSet() { - structMap["amount_in_cents"] = s.AmountInCents.Value() - } - if s.Percentage.IsValueSet() { - structMap["percentage"] = s.Percentage.Value() - } - return structMap + structMap := make(map[string]any) + if s.Code != nil { + structMap["code"] = s.Code + } + if s.UseCount != nil { + structMap["use_count"] = s.UseCount + } + if s.UsesAllowed != nil { + structMap["uses_allowed"] = s.UsesAllowed + } + if s.ExpiresAt.IsValueSet() { + if s.ExpiresAt.Value() != nil { + structMap["expires_at"] = s.ExpiresAt.Value() + } else { + structMap["expires_at"] = nil + } + } + if s.Recurring != nil { + structMap["recurring"] = s.Recurring + } + if s.AmountInCents.IsValueSet() { + if s.AmountInCents.Value() != nil { + structMap["amount_in_cents"] = s.AmountInCents.Value() + } else { + structMap["amount_in_cents"] = nil + } + } + if s.Percentage.IsValueSet() { + if s.Percentage.Value() != nil { + structMap["percentage"] = s.Percentage.Value() + } else { + structMap["percentage"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionIncludedCoupon. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionIncludedCoupon. // It customizes the JSON unmarshaling process for SubscriptionIncludedCoupon objects. func (s *SubscriptionIncludedCoupon) UnmarshalJSON(input []byte) error { - temp := &struct { - Code *string `json:"code,omitempty"` - UseCount *int `json:"use_count,omitempty"` - UsesAllowed *int `json:"uses_allowed,omitempty"` - ExpiresAt Optional[string] `json:"expires_at"` - Recurring *bool `json:"recurring,omitempty"` - AmountInCents Optional[int64] `json:"amount_in_cents"` - Percentage Optional[string] `json:"percentage"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Code = temp.Code - s.UseCount = temp.UseCount - s.UsesAllowed = temp.UsesAllowed - s.ExpiresAt = temp.ExpiresAt - s.Recurring = temp.Recurring - s.AmountInCents = temp.AmountInCents - s.Percentage = temp.Percentage - return nil + var temp subscriptionIncludedCoupon + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Code = temp.Code + s.UseCount = temp.UseCount + s.UsesAllowed = temp.UsesAllowed + s.ExpiresAt = temp.ExpiresAt + s.Recurring = temp.Recurring + s.AmountInCents = temp.AmountInCents + s.Percentage = temp.Percentage + return nil +} + +// TODO +type subscriptionIncludedCoupon struct { + Code *string `json:"code,omitempty"` + UseCount *int `json:"use_count,omitempty"` + UsesAllowed *int `json:"uses_allowed,omitempty"` + ExpiresAt Optional[string] `json:"expires_at"` + Recurring *bool `json:"recurring,omitempty"` + AmountInCents Optional[int64] `json:"amount_in_cents"` + Percentage Optional[string] `json:"percentage"` } diff --git a/models/subscription_migration_preview.go b/models/subscription_migration_preview.go index acb9c89c..ba9e9e53 100644 --- a/models/subscription_migration_preview.go +++ b/models/subscription_migration_preview.go @@ -1,64 +1,66 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionMigrationPreview represents a SubscriptionMigrationPreview struct. type SubscriptionMigrationPreview struct { - // The amount of the prorated adjustment that would be issued for the current subscription. - ProratedAdjustmentInCents *int64 `json:"prorated_adjustment_in_cents,omitempty"` - // The amount of the charge that would be created for the new product. - ChargeInCents *int64 `json:"charge_in_cents,omitempty"` - // The amount of the payment due in the case of an upgrade. - PaymentDueInCents *int64 `json:"payment_due_in_cents,omitempty"` - // Represents a credit in cents that is applied to your subscription as part of a migration process for a specific product, which reduces the amount owed for the subscription. - CreditAppliedInCents *int64 `json:"credit_applied_in_cents,omitempty"` + // The amount of the prorated adjustment that would be issued for the current subscription. + ProratedAdjustmentInCents *int64 `json:"prorated_adjustment_in_cents,omitempty"` + // The amount of the charge that would be created for the new product. + ChargeInCents *int64 `json:"charge_in_cents,omitempty"` + // The amount of the payment due in the case of an upgrade. + PaymentDueInCents *int64 `json:"payment_due_in_cents,omitempty"` + // Represents a credit in cents that is applied to your subscription as part of a migration process for a specific product, which reduces the amount owed for the subscription. + CreditAppliedInCents *int64 `json:"credit_applied_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionMigrationPreview. +// MarshalJSON implements the json.Marshaler interface for SubscriptionMigrationPreview. // It customizes the JSON marshaling process for SubscriptionMigrationPreview objects. func (s *SubscriptionMigrationPreview) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionMigrationPreview object to a map representation for JSON marshaling. func (s *SubscriptionMigrationPreview) toMap() map[string]any { - structMap := make(map[string]any) - if s.ProratedAdjustmentInCents != nil { - structMap["prorated_adjustment_in_cents"] = s.ProratedAdjustmentInCents - } - if s.ChargeInCents != nil { - structMap["charge_in_cents"] = s.ChargeInCents - } - if s.PaymentDueInCents != nil { - structMap["payment_due_in_cents"] = s.PaymentDueInCents - } - if s.CreditAppliedInCents != nil { - structMap["credit_applied_in_cents"] = s.CreditAppliedInCents - } - return structMap + structMap := make(map[string]any) + if s.ProratedAdjustmentInCents != nil { + structMap["prorated_adjustment_in_cents"] = s.ProratedAdjustmentInCents + } + if s.ChargeInCents != nil { + structMap["charge_in_cents"] = s.ChargeInCents + } + if s.PaymentDueInCents != nil { + structMap["payment_due_in_cents"] = s.PaymentDueInCents + } + if s.CreditAppliedInCents != nil { + structMap["credit_applied_in_cents"] = s.CreditAppliedInCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMigrationPreview. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMigrationPreview. // It customizes the JSON unmarshaling process for SubscriptionMigrationPreview objects. func (s *SubscriptionMigrationPreview) UnmarshalJSON(input []byte) error { - temp := &struct { - ProratedAdjustmentInCents *int64 `json:"prorated_adjustment_in_cents,omitempty"` - ChargeInCents *int64 `json:"charge_in_cents,omitempty"` - PaymentDueInCents *int64 `json:"payment_due_in_cents,omitempty"` - CreditAppliedInCents *int64 `json:"credit_applied_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.ProratedAdjustmentInCents = temp.ProratedAdjustmentInCents - s.ChargeInCents = temp.ChargeInCents - s.PaymentDueInCents = temp.PaymentDueInCents - s.CreditAppliedInCents = temp.CreditAppliedInCents - return nil + var temp subscriptionMigrationPreview + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.ProratedAdjustmentInCents = temp.ProratedAdjustmentInCents + s.ChargeInCents = temp.ChargeInCents + s.PaymentDueInCents = temp.PaymentDueInCents + s.CreditAppliedInCents = temp.CreditAppliedInCents + return nil +} + +// TODO +type subscriptionMigrationPreview struct { + ProratedAdjustmentInCents *int64 `json:"prorated_adjustment_in_cents,omitempty"` + ChargeInCents *int64 `json:"charge_in_cents,omitempty"` + PaymentDueInCents *int64 `json:"payment_due_in_cents,omitempty"` + CreditAppliedInCents *int64 `json:"credit_applied_in_cents,omitempty"` } diff --git a/models/subscription_migration_preview_options.go b/models/subscription_migration_preview_options.go index 066a9caa..520cf6d7 100644 --- a/models/subscription_migration_preview_options.go +++ b/models/subscription_migration_preview_options.go @@ -1,113 +1,115 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // SubscriptionMigrationPreviewOptions represents a SubscriptionMigrationPreviewOptions struct. type SubscriptionMigrationPreviewOptions struct { - // The ID of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. - ProductId *int `json:"product_id,omitempty"` - // The ID of the specified product's price point. This can be passed to migrate to a non-default price point. - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - // Whether to include the trial period configured for the product price point when starting a new billing period. Note that if preserve_period is set, then include_trial will be ignored. - IncludeTrial *bool `json:"include_trial,omitempty"` - // If `true` is sent initial charges will be assessed. - IncludeInitialCharge *bool `json:"include_initial_charge,omitempty"` - // If `true` is sent, any coupons associated with the subscription will be applied to the migration. If `false` is sent, coupons will not be applied. Note: When migrating to a new product family, the coupon cannot migrate. - IncludeCoupons *bool `json:"include_coupons,omitempty"` - // If `false` is sent, the subscription's billing period will be reset to today and the full price of the new product will be charged. If `true` is sent, the billing period will not change and a prorated charge will be issued for the new product. - PreservePeriod *bool `json:"preserve_period,omitempty"` - // The handle of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. - ProductHandle *string `json:"product_handle,omitempty"` - // The ID or handle of the specified product's price point. This can be passed to migrate to a non-default price point. - ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` - Proration *Proration `json:"proration,omitempty"` - // The date that the proration is calculated from for the preview - ProrationDate *time.Time `json:"proration_date,omitempty"` + // The ID of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. + ProductId *int `json:"product_id,omitempty"` + // The ID of the specified product's price point. This can be passed to migrate to a non-default price point. + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + // Whether to include the trial period configured for the product price point when starting a new billing period. Note that if preserve_period is set, then include_trial will be ignored. + IncludeTrial *bool `json:"include_trial,omitempty"` + // If `true` is sent initial charges will be assessed. + IncludeInitialCharge *bool `json:"include_initial_charge,omitempty"` + // If `true` is sent, any coupons associated with the subscription will be applied to the migration. If `false` is sent, coupons will not be applied. Note: When migrating to a new product family, the coupon cannot migrate. + IncludeCoupons *bool `json:"include_coupons,omitempty"` + // If `false` is sent, the subscription's billing period will be reset to today and the full price of the new product will be charged. If `true` is sent, the billing period will not change and a prorated charge will be issued for the new product. + PreservePeriod *bool `json:"preserve_period,omitempty"` + // The handle of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. + ProductHandle *string `json:"product_handle,omitempty"` + // The ID or handle of the specified product's price point. This can be passed to migrate to a non-default price point. + ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` + Proration *Proration `json:"proration,omitempty"` + // The date that the proration is calculated from for the preview + ProrationDate *time.Time `json:"proration_date,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionMigrationPreviewOptions. +// MarshalJSON implements the json.Marshaler interface for SubscriptionMigrationPreviewOptions. // It customizes the JSON marshaling process for SubscriptionMigrationPreviewOptions objects. func (s *SubscriptionMigrationPreviewOptions) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionMigrationPreviewOptions object to a map representation for JSON marshaling. func (s *SubscriptionMigrationPreviewOptions) toMap() map[string]any { - structMap := make(map[string]any) - if s.ProductId != nil { - structMap["product_id"] = s.ProductId - } - if s.ProductPricePointId != nil { - structMap["product_price_point_id"] = s.ProductPricePointId - } - if s.IncludeTrial != nil { - structMap["include_trial"] = s.IncludeTrial - } - if s.IncludeInitialCharge != nil { - structMap["include_initial_charge"] = s.IncludeInitialCharge - } - if s.IncludeCoupons != nil { - structMap["include_coupons"] = s.IncludeCoupons - } - if s.PreservePeriod != nil { - structMap["preserve_period"] = s.PreservePeriod - } - if s.ProductHandle != nil { - structMap["product_handle"] = s.ProductHandle - } - if s.ProductPricePointHandle != nil { - structMap["product_price_point_handle"] = s.ProductPricePointHandle - } - if s.Proration != nil { - structMap["proration"] = s.Proration.toMap() - } - if s.ProrationDate != nil { - structMap["proration_date"] = s.ProrationDate.Format(time.RFC3339) - } - return structMap + structMap := make(map[string]any) + if s.ProductId != nil { + structMap["product_id"] = s.ProductId + } + if s.ProductPricePointId != nil { + structMap["product_price_point_id"] = s.ProductPricePointId + } + if s.IncludeTrial != nil { + structMap["include_trial"] = s.IncludeTrial + } + if s.IncludeInitialCharge != nil { + structMap["include_initial_charge"] = s.IncludeInitialCharge + } + if s.IncludeCoupons != nil { + structMap["include_coupons"] = s.IncludeCoupons + } + if s.PreservePeriod != nil { + structMap["preserve_period"] = s.PreservePeriod + } + if s.ProductHandle != nil { + structMap["product_handle"] = s.ProductHandle + } + if s.ProductPricePointHandle != nil { + structMap["product_price_point_handle"] = s.ProductPricePointHandle + } + if s.Proration != nil { + structMap["proration"] = s.Proration.toMap() + } + if s.ProrationDate != nil { + structMap["proration_date"] = s.ProrationDate.Format(time.RFC3339) + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMigrationPreviewOptions. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMigrationPreviewOptions. // It customizes the JSON unmarshaling process for SubscriptionMigrationPreviewOptions objects. func (s *SubscriptionMigrationPreviewOptions) UnmarshalJSON(input []byte) error { - temp := &struct { - ProductId *int `json:"product_id,omitempty"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - IncludeTrial *bool `json:"include_trial,omitempty"` - IncludeInitialCharge *bool `json:"include_initial_charge,omitempty"` - IncludeCoupons *bool `json:"include_coupons,omitempty"` - PreservePeriod *bool `json:"preserve_period,omitempty"` - ProductHandle *string `json:"product_handle,omitempty"` - ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` - Proration *Proration `json:"proration,omitempty"` - ProrationDate *string `json:"proration_date,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.ProductId = temp.ProductId - s.ProductPricePointId = temp.ProductPricePointId - s.IncludeTrial = temp.IncludeTrial - s.IncludeInitialCharge = temp.IncludeInitialCharge - s.IncludeCoupons = temp.IncludeCoupons - s.PreservePeriod = temp.PreservePeriod - s.ProductHandle = temp.ProductHandle - s.ProductPricePointHandle = temp.ProductPricePointHandle - s.Proration = temp.Proration - if temp.ProrationDate != nil { - ProrationDateVal, err := time.Parse(time.RFC3339, *temp.ProrationDate) - if err != nil { - log.Fatalf("Cannot Parse proration_date as % s format.", time.RFC3339) - } - s.ProrationDate = &ProrationDateVal - } - return nil + var temp subscriptionMigrationPreviewOptions + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.ProductId = temp.ProductId + s.ProductPricePointId = temp.ProductPricePointId + s.IncludeTrial = temp.IncludeTrial + s.IncludeInitialCharge = temp.IncludeInitialCharge + s.IncludeCoupons = temp.IncludeCoupons + s.PreservePeriod = temp.PreservePeriod + s.ProductHandle = temp.ProductHandle + s.ProductPricePointHandle = temp.ProductPricePointHandle + s.Proration = temp.Proration + if temp.ProrationDate != nil { + ProrationDateVal, err := time.Parse(time.RFC3339, *temp.ProrationDate) + if err != nil { + log.Fatalf("Cannot Parse proration_date as % s format.", time.RFC3339) + } + s.ProrationDate = &ProrationDateVal + } + return nil +} + +// TODO +type subscriptionMigrationPreviewOptions struct { + ProductId *int `json:"product_id,omitempty"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + IncludeTrial *bool `json:"include_trial,omitempty"` + IncludeInitialCharge *bool `json:"include_initial_charge,omitempty"` + IncludeCoupons *bool `json:"include_coupons,omitempty"` + PreservePeriod *bool `json:"preserve_period,omitempty"` + ProductHandle *string `json:"product_handle,omitempty"` + ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` + Proration *Proration `json:"proration,omitempty"` + ProrationDate *string `json:"proration_date,omitempty"` } diff --git a/models/subscription_migration_preview_request.go b/models/subscription_migration_preview_request.go index 0816d1cc..8e42926f 100644 --- a/models/subscription_migration_preview_request.go +++ b/models/subscription_migration_preview_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionMigrationPreviewRequest represents a SubscriptionMigrationPreviewRequest struct. type SubscriptionMigrationPreviewRequest struct { - Migration SubscriptionMigrationPreviewOptions `json:"migration"` + Migration SubscriptionMigrationPreviewOptions `json:"migration"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionMigrationPreviewRequest. +// MarshalJSON implements the json.Marshaler interface for SubscriptionMigrationPreviewRequest. // It customizes the JSON marshaling process for SubscriptionMigrationPreviewRequest objects. func (s *SubscriptionMigrationPreviewRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionMigrationPreviewRequest object to a map representation for JSON marshaling. func (s *SubscriptionMigrationPreviewRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["migration"] = s.Migration.toMap() - return structMap + structMap := make(map[string]any) + structMap["migration"] = s.Migration.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMigrationPreviewRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMigrationPreviewRequest. // It customizes the JSON unmarshaling process for SubscriptionMigrationPreviewRequest objects. func (s *SubscriptionMigrationPreviewRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Migration SubscriptionMigrationPreviewOptions `json:"migration"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Migration = temp.Migration - return nil + var temp subscriptionMigrationPreviewRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.Migration = *temp.Migration + return nil +} + +// TODO +type subscriptionMigrationPreviewRequest struct { + Migration *SubscriptionMigrationPreviewOptions `json:"migration"` +} + +func (s *subscriptionMigrationPreviewRequest) validate() error { + var errs []string + if s.Migration == nil { + errs = append(errs, "required field `migration` is missing for type `Subscription Migration Preview Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_migration_preview_response.go b/models/subscription_migration_preview_response.go index 65521cee..9102add5 100644 --- a/models/subscription_migration_preview_response.go +++ b/models/subscription_migration_preview_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionMigrationPreviewResponse represents a SubscriptionMigrationPreviewResponse struct. type SubscriptionMigrationPreviewResponse struct { - Migration SubscriptionMigrationPreview `json:"migration"` + Migration SubscriptionMigrationPreview `json:"migration"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionMigrationPreviewResponse. +// MarshalJSON implements the json.Marshaler interface for SubscriptionMigrationPreviewResponse. // It customizes the JSON marshaling process for SubscriptionMigrationPreviewResponse objects. func (s *SubscriptionMigrationPreviewResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionMigrationPreviewResponse object to a map representation for JSON marshaling. func (s *SubscriptionMigrationPreviewResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["migration"] = s.Migration.toMap() - return structMap + structMap := make(map[string]any) + structMap["migration"] = s.Migration.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMigrationPreviewResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMigrationPreviewResponse. // It customizes the JSON unmarshaling process for SubscriptionMigrationPreviewResponse objects. func (s *SubscriptionMigrationPreviewResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Migration SubscriptionMigrationPreview `json:"migration"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Migration = temp.Migration - return nil + var temp subscriptionMigrationPreviewResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.Migration = *temp.Migration + return nil +} + +// TODO +type subscriptionMigrationPreviewResponse struct { + Migration *SubscriptionMigrationPreview `json:"migration"` +} + +func (s *subscriptionMigrationPreviewResponse) validate() error { + var errs []string + if s.Migration == nil { + errs = append(errs, "required field `migration` is missing for type `Subscription Migration Preview Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_mrr.go b/models/subscription_mrr.go index f0f69772..fd94916e 100644 --- a/models/subscription_mrr.go +++ b/models/subscription_mrr.go @@ -1,50 +1,73 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionMRR represents a SubscriptionMRR struct. type SubscriptionMRR struct { - SubscriptionId int `json:"subscription_id"` - MrrAmountInCents int64 `json:"mrr_amount_in_cents"` - Breakouts *SubscriptionMRRBreakout `json:"breakouts,omitempty"` + SubscriptionId int `json:"subscription_id"` + MrrAmountInCents int64 `json:"mrr_amount_in_cents"` + Breakouts *SubscriptionMRRBreakout `json:"breakouts,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionMRR. +// MarshalJSON implements the json.Marshaler interface for SubscriptionMRR. // It customizes the JSON marshaling process for SubscriptionMRR objects. func (s *SubscriptionMRR) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionMRR object to a map representation for JSON marshaling. func (s *SubscriptionMRR) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscription_id"] = s.SubscriptionId - structMap["mrr_amount_in_cents"] = s.MrrAmountInCents - if s.Breakouts != nil { - structMap["breakouts"] = s.Breakouts.toMap() - } - return structMap + structMap := make(map[string]any) + structMap["subscription_id"] = s.SubscriptionId + structMap["mrr_amount_in_cents"] = s.MrrAmountInCents + if s.Breakouts != nil { + structMap["breakouts"] = s.Breakouts.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMRR. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMRR. // It customizes the JSON unmarshaling process for SubscriptionMRR objects. func (s *SubscriptionMRR) UnmarshalJSON(input []byte) error { - temp := &struct { - SubscriptionId int `json:"subscription_id"` - MrrAmountInCents int64 `json:"mrr_amount_in_cents"` - Breakouts *SubscriptionMRRBreakout `json:"breakouts,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.SubscriptionId = temp.SubscriptionId - s.MrrAmountInCents = temp.MrrAmountInCents - s.Breakouts = temp.Breakouts - return nil + var temp subscriptionMRR + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.SubscriptionId = *temp.SubscriptionId + s.MrrAmountInCents = *temp.MrrAmountInCents + s.Breakouts = temp.Breakouts + return nil +} + +// TODO +type subscriptionMRR struct { + SubscriptionId *int `json:"subscription_id"` + MrrAmountInCents *int64 `json:"mrr_amount_in_cents"` + Breakouts *SubscriptionMRRBreakout `json:"breakouts,omitempty"` +} + +func (s *subscriptionMRR) validate() error { + var errs []string + if s.SubscriptionId == nil { + errs = append(errs, "required field `subscription_id` is missing for type `Subscription MRR`") + } + if s.MrrAmountInCents == nil { + errs = append(errs, "required field `mrr_amount_in_cents` is missing for type `Subscription MRR`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_mrr_breakout.go b/models/subscription_mrr_breakout.go index b96f6f6e..d0d1ac8a 100644 --- a/models/subscription_mrr_breakout.go +++ b/models/subscription_mrr_breakout.go @@ -1,44 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionMRRBreakout represents a SubscriptionMRRBreakout struct. type SubscriptionMRRBreakout struct { - PlanAmountInCents int64 `json:"plan_amount_in_cents"` - UsageAmountInCents int64 `json:"usage_amount_in_cents"` + PlanAmountInCents int64 `json:"plan_amount_in_cents"` + UsageAmountInCents int64 `json:"usage_amount_in_cents"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionMRRBreakout. +// MarshalJSON implements the json.Marshaler interface for SubscriptionMRRBreakout. // It customizes the JSON marshaling process for SubscriptionMRRBreakout objects. func (s *SubscriptionMRRBreakout) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionMRRBreakout object to a map representation for JSON marshaling. func (s *SubscriptionMRRBreakout) toMap() map[string]any { - structMap := make(map[string]any) - structMap["plan_amount_in_cents"] = s.PlanAmountInCents - structMap["usage_amount_in_cents"] = s.UsageAmountInCents - return structMap + structMap := make(map[string]any) + structMap["plan_amount_in_cents"] = s.PlanAmountInCents + structMap["usage_amount_in_cents"] = s.UsageAmountInCents + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMRRBreakout. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMRRBreakout. // It customizes the JSON unmarshaling process for SubscriptionMRRBreakout objects. func (s *SubscriptionMRRBreakout) UnmarshalJSON(input []byte) error { - temp := &struct { - PlanAmountInCents int64 `json:"plan_amount_in_cents"` - UsageAmountInCents int64 `json:"usage_amount_in_cents"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.PlanAmountInCents = temp.PlanAmountInCents - s.UsageAmountInCents = temp.UsageAmountInCents - return nil + var temp subscriptionMRRBreakout + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.PlanAmountInCents = *temp.PlanAmountInCents + s.UsageAmountInCents = *temp.UsageAmountInCents + return nil +} + +// TODO +type subscriptionMRRBreakout struct { + PlanAmountInCents *int64 `json:"plan_amount_in_cents"` + UsageAmountInCents *int64 `json:"usage_amount_in_cents"` +} + +func (s *subscriptionMRRBreakout) validate() error { + var errs []string + if s.PlanAmountInCents == nil { + errs = append(errs, "required field `plan_amount_in_cents` is missing for type `Subscription MRR Breakout`") + } + if s.UsageAmountInCents == nil { + errs = append(errs, "required field `usage_amount_in_cents` is missing for type `Subscription MRR Breakout`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_mrr_response.go b/models/subscription_mrr_response.go index 8aaf444e..857cab77 100644 --- a/models/subscription_mrr_response.go +++ b/models/subscription_mrr_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionMRRResponse represents a SubscriptionMRRResponse struct. type SubscriptionMRRResponse struct { - SubscriptionsMrr []SubscriptionMRR `json:"subscriptions_mrr"` + SubscriptionsMrr []SubscriptionMRR `json:"subscriptions_mrr"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionMRRResponse. +// MarshalJSON implements the json.Marshaler interface for SubscriptionMRRResponse. // It customizes the JSON marshaling process for SubscriptionMRRResponse objects. func (s *SubscriptionMRRResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionMRRResponse object to a map representation for JSON marshaling. func (s *SubscriptionMRRResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscriptions_mrr"] = s.SubscriptionsMrr - return structMap + structMap := make(map[string]any) + structMap["subscriptions_mrr"] = s.SubscriptionsMrr + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMRRResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionMRRResponse. // It customizes the JSON unmarshaling process for SubscriptionMRRResponse objects. func (s *SubscriptionMRRResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - SubscriptionsMrr []SubscriptionMRR `json:"subscriptions_mrr"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.SubscriptionsMrr = temp.SubscriptionsMrr - return nil + var temp subscriptionMRRResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.SubscriptionsMrr = *temp.SubscriptionsMrr + return nil +} + +// TODO +type subscriptionMRRResponse struct { + SubscriptionsMrr *[]SubscriptionMRR `json:"subscriptions_mrr"` +} + +func (s *subscriptionMRRResponse) validate() error { + var errs []string + if s.SubscriptionsMrr == nil { + errs = append(errs, "required field `subscriptions_mrr` is missing for type `Subscription MRR Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_note.go b/models/subscription_note.go index 2daedf80..5d9e000f 100644 --- a/models/subscription_note.go +++ b/models/subscription_note.go @@ -1,86 +1,88 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // SubscriptionNote represents a SubscriptionNote struct. type SubscriptionNote struct { - Id *int `json:"id,omitempty"` - Body *string `json:"body,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - Sticky *bool `json:"sticky,omitempty"` + Id *int `json:"id,omitempty"` + Body *string `json:"body,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + Sticky *bool `json:"sticky,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionNote. +// MarshalJSON implements the json.Marshaler interface for SubscriptionNote. // It customizes the JSON marshaling process for SubscriptionNote objects. func (s *SubscriptionNote) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionNote object to a map representation for JSON marshaling. func (s *SubscriptionNote) toMap() map[string]any { - structMap := make(map[string]any) - if s.Id != nil { - structMap["id"] = s.Id - } - if s.Body != nil { - structMap["body"] = s.Body - } - if s.SubscriptionId != nil { - structMap["subscription_id"] = s.SubscriptionId - } - if s.CreatedAt != nil { - structMap["created_at"] = s.CreatedAt.Format(time.RFC3339) - } - if s.UpdatedAt != nil { - structMap["updated_at"] = s.UpdatedAt.Format(time.RFC3339) - } - if s.Sticky != nil { - structMap["sticky"] = s.Sticky - } - return structMap + structMap := make(map[string]any) + if s.Id != nil { + structMap["id"] = s.Id + } + if s.Body != nil { + structMap["body"] = s.Body + } + if s.SubscriptionId != nil { + structMap["subscription_id"] = s.SubscriptionId + } + if s.CreatedAt != nil { + structMap["created_at"] = s.CreatedAt.Format(time.RFC3339) + } + if s.UpdatedAt != nil { + structMap["updated_at"] = s.UpdatedAt.Format(time.RFC3339) + } + if s.Sticky != nil { + structMap["sticky"] = s.Sticky + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionNote. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionNote. // It customizes the JSON unmarshaling process for SubscriptionNote objects. func (s *SubscriptionNote) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - Body *string `json:"body,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - Sticky *bool `json:"sticky,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Id = temp.Id - s.Body = temp.Body - s.SubscriptionId = temp.SubscriptionId - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - s.CreatedAt = &CreatedAtVal - } - if temp.UpdatedAt != nil { - UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) - if err != nil { - log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) - } - s.UpdatedAt = &UpdatedAtVal - } - s.Sticky = temp.Sticky - return nil + var temp subscriptionNote + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Id = temp.Id + s.Body = temp.Body + s.SubscriptionId = temp.SubscriptionId + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + s.CreatedAt = &CreatedAtVal + } + if temp.UpdatedAt != nil { + UpdatedAtVal, err := time.Parse(time.RFC3339, *temp.UpdatedAt) + if err != nil { + log.Fatalf("Cannot Parse updated_at as % s format.", time.RFC3339) + } + s.UpdatedAt = &UpdatedAtVal + } + s.Sticky = temp.Sticky + return nil +} + +// TODO +type subscriptionNote struct { + Id *int `json:"id,omitempty"` + Body *string `json:"body,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + Sticky *bool `json:"sticky,omitempty"` } diff --git a/models/subscription_note_response.go b/models/subscription_note_response.go index c560a43d..95a9d8d3 100644 --- a/models/subscription_note_response.go +++ b/models/subscription_note_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionNoteResponse represents a SubscriptionNoteResponse struct. type SubscriptionNoteResponse struct { - Note SubscriptionNote `json:"note"` + Note SubscriptionNote `json:"note"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionNoteResponse. +// MarshalJSON implements the json.Marshaler interface for SubscriptionNoteResponse. // It customizes the JSON marshaling process for SubscriptionNoteResponse objects. func (s *SubscriptionNoteResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionNoteResponse object to a map representation for JSON marshaling. func (s *SubscriptionNoteResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["note"] = s.Note.toMap() - return structMap + structMap := make(map[string]any) + structMap["note"] = s.Note.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionNoteResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionNoteResponse. // It customizes the JSON unmarshaling process for SubscriptionNoteResponse objects. func (s *SubscriptionNoteResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Note SubscriptionNote `json:"note"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Note = temp.Note - return nil + var temp subscriptionNoteResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.Note = *temp.Note + return nil +} + +// TODO +type subscriptionNoteResponse struct { + Note *SubscriptionNote `json:"note"` +} + +func (s *subscriptionNoteResponse) validate() error { + var errs []string + if s.Note == nil { + errs = append(errs, "required field `note` is missing for type `Subscription Note Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_preview.go b/models/subscription_preview.go index 1904aad0..cb3b4a3a 100644 --- a/models/subscription_preview.go +++ b/models/subscription_preview.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionPreview represents a SubscriptionPreview struct. type SubscriptionPreview struct { - CurrentBillingManifest *BillingManifest `json:"current_billing_manifest,omitempty"` - NextBillingManifest *BillingManifest `json:"next_billing_manifest,omitempty"` + CurrentBillingManifest *BillingManifest `json:"current_billing_manifest,omitempty"` + NextBillingManifest *BillingManifest `json:"next_billing_manifest,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionPreview. +// MarshalJSON implements the json.Marshaler interface for SubscriptionPreview. // It customizes the JSON marshaling process for SubscriptionPreview objects. func (s *SubscriptionPreview) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionPreview object to a map representation for JSON marshaling. func (s *SubscriptionPreview) toMap() map[string]any { - structMap := make(map[string]any) - if s.CurrentBillingManifest != nil { - structMap["current_billing_manifest"] = s.CurrentBillingManifest.toMap() - } - if s.NextBillingManifest != nil { - structMap["next_billing_manifest"] = s.NextBillingManifest.toMap() - } - return structMap + structMap := make(map[string]any) + if s.CurrentBillingManifest != nil { + structMap["current_billing_manifest"] = s.CurrentBillingManifest.toMap() + } + if s.NextBillingManifest != nil { + structMap["next_billing_manifest"] = s.NextBillingManifest.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionPreview. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionPreview. // It customizes the JSON unmarshaling process for SubscriptionPreview objects. func (s *SubscriptionPreview) UnmarshalJSON(input []byte) error { - temp := &struct { - CurrentBillingManifest *BillingManifest `json:"current_billing_manifest,omitempty"` - NextBillingManifest *BillingManifest `json:"next_billing_manifest,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.CurrentBillingManifest = temp.CurrentBillingManifest - s.NextBillingManifest = temp.NextBillingManifest - return nil + var temp subscriptionPreview + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.CurrentBillingManifest = temp.CurrentBillingManifest + s.NextBillingManifest = temp.NextBillingManifest + return nil +} + +// TODO +type subscriptionPreview struct { + CurrentBillingManifest *BillingManifest `json:"current_billing_manifest,omitempty"` + NextBillingManifest *BillingManifest `json:"next_billing_manifest,omitempty"` } diff --git a/models/subscription_preview_response.go b/models/subscription_preview_response.go index 58619466..1bcd7b93 100644 --- a/models/subscription_preview_response.go +++ b/models/subscription_preview_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionPreviewResponse represents a SubscriptionPreviewResponse struct. type SubscriptionPreviewResponse struct { - SubscriptionPreview SubscriptionPreview `json:"subscription_preview"` + SubscriptionPreview SubscriptionPreview `json:"subscription_preview"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionPreviewResponse. +// MarshalJSON implements the json.Marshaler interface for SubscriptionPreviewResponse. // It customizes the JSON marshaling process for SubscriptionPreviewResponse objects. func (s *SubscriptionPreviewResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionPreviewResponse object to a map representation for JSON marshaling. func (s *SubscriptionPreviewResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscription_preview"] = s.SubscriptionPreview.toMap() - return structMap + structMap := make(map[string]any) + structMap["subscription_preview"] = s.SubscriptionPreview.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionPreviewResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionPreviewResponse. // It customizes the JSON unmarshaling process for SubscriptionPreviewResponse objects. func (s *SubscriptionPreviewResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - SubscriptionPreview SubscriptionPreview `json:"subscription_preview"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.SubscriptionPreview = temp.SubscriptionPreview - return nil + var temp subscriptionPreviewResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.SubscriptionPreview = *temp.SubscriptionPreview + return nil +} + +// TODO +type subscriptionPreviewResponse struct { + SubscriptionPreview *SubscriptionPreview `json:"subscription_preview"` +} + +func (s *subscriptionPreviewResponse) validate() error { + var errs []string + if s.SubscriptionPreview == nil { + errs = append(errs, "required field `subscription_preview` is missing for type `Subscription Preview Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_product_change.go b/models/subscription_product_change.go new file mode 100644 index 00000000..e67f74fa --- /dev/null +++ b/models/subscription_product_change.go @@ -0,0 +1,67 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionProductChange represents a SubscriptionProductChange struct. +type SubscriptionProductChange struct { + PreviousProductId int `json:"previous_product_id"` + NewProductId int `json:"new_product_id"` +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionProductChange. +// It customizes the JSON marshaling process for SubscriptionProductChange objects. +func (s *SubscriptionProductChange) MarshalJSON() ( + []byte, + error) { + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionProductChange object to a map representation for JSON marshaling. +func (s *SubscriptionProductChange) toMap() map[string]any { + structMap := make(map[string]any) + structMap["previous_product_id"] = s.PreviousProductId + structMap["new_product_id"] = s.NewProductId + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionProductChange. +// It customizes the JSON unmarshaling process for SubscriptionProductChange objects. +func (s *SubscriptionProductChange) UnmarshalJSON(input []byte) error { + var temp subscriptionProductChange + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.PreviousProductId = *temp.PreviousProductId + s.NewProductId = *temp.NewProductId + return nil +} + +// TODO +type subscriptionProductChange struct { + PreviousProductId *int `json:"previous_product_id"` + NewProductId *int `json:"new_product_id"` +} + +func (s *subscriptionProductChange) validate() error { + var errs []string + if s.PreviousProductId == nil { + errs = append(errs, "required field `previous_product_id` is missing for type `Subscription Product Change`") + } + if s.NewProductId == nil { + errs = append(errs, "required field `new_product_id` is missing for type `Subscription Product Change`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/subscription_product_migration.go b/models/subscription_product_migration.go index aceabd1d..4dfdf433 100644 --- a/models/subscription_product_migration.go +++ b/models/subscription_product_migration.go @@ -1,98 +1,100 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionProductMigration represents a SubscriptionProductMigration struct. type SubscriptionProductMigration struct { - // The ID of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. - ProductId *int `json:"product_id,omitempty"` - // The ID of the specified product's price point. This can be passed to migrate to a non-default price point. - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - // Whether to include the trial period configured for the product price point when starting a new billing period. Note that if preserve_period is set, then include_trial will be ignored. - IncludeTrial *bool `json:"include_trial,omitempty"` - // If `true` is sent initial charges will be assessed. - IncludeInitialCharge *bool `json:"include_initial_charge,omitempty"` - // If `true` is sent, any coupons associated with the subscription will be applied to the migration. If `false` is sent, coupons will not be applied. Note: When migrating to a new product family, the coupon cannot migrate. - IncludeCoupons *bool `json:"include_coupons,omitempty"` - // If `false` is sent, the subscription's billing period will be reset to today and the full price of the new product will be charged. If `true` is sent, the billing period will not change and a prorated charge will be issued for the new product. - PreservePeriod *bool `json:"preserve_period,omitempty"` - // The handle of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. - ProductHandle *string `json:"product_handle,omitempty"` - // The ID or handle of the specified product's price point. This can be passed to migrate to a non-default price point. - ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` - Proration *Proration `json:"proration,omitempty"` + // The ID of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. + ProductId *int `json:"product_id,omitempty"` + // The ID of the specified product's price point. This can be passed to migrate to a non-default price point. + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + // Whether to include the trial period configured for the product price point when starting a new billing period. Note that if preserve_period is set, then include_trial will be ignored. + IncludeTrial *bool `json:"include_trial,omitempty"` + // If `true` is sent initial charges will be assessed. + IncludeInitialCharge *bool `json:"include_initial_charge,omitempty"` + // If `true` is sent, any coupons associated with the subscription will be applied to the migration. If `false` is sent, coupons will not be applied. Note: When migrating to a new product family, the coupon cannot migrate. + IncludeCoupons *bool `json:"include_coupons,omitempty"` + // If `false` is sent, the subscription's billing period will be reset to today and the full price of the new product will be charged. If `true` is sent, the billing period will not change and a prorated charge will be issued for the new product. + PreservePeriod *bool `json:"preserve_period,omitempty"` + // The handle of the target Product. Either a product_id or product_handle must be present. A Subscription can be migrated to another product for both the current Product Family and another Product Family. Note: Going to another Product Family, components will not be migrated as well. + ProductHandle *string `json:"product_handle,omitempty"` + // The ID or handle of the specified product's price point. This can be passed to migrate to a non-default price point. + ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` + Proration *Proration `json:"proration,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionProductMigration. +// MarshalJSON implements the json.Marshaler interface for SubscriptionProductMigration. // It customizes the JSON marshaling process for SubscriptionProductMigration objects. func (s *SubscriptionProductMigration) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionProductMigration object to a map representation for JSON marshaling. func (s *SubscriptionProductMigration) toMap() map[string]any { - structMap := make(map[string]any) - if s.ProductId != nil { - structMap["product_id"] = s.ProductId - } - if s.ProductPricePointId != nil { - structMap["product_price_point_id"] = s.ProductPricePointId - } - if s.IncludeTrial != nil { - structMap["include_trial"] = s.IncludeTrial - } - if s.IncludeInitialCharge != nil { - structMap["include_initial_charge"] = s.IncludeInitialCharge - } - if s.IncludeCoupons != nil { - structMap["include_coupons"] = s.IncludeCoupons - } - if s.PreservePeriod != nil { - structMap["preserve_period"] = s.PreservePeriod - } - if s.ProductHandle != nil { - structMap["product_handle"] = s.ProductHandle - } - if s.ProductPricePointHandle != nil { - structMap["product_price_point_handle"] = s.ProductPricePointHandle - } - if s.Proration != nil { - structMap["proration"] = s.Proration.toMap() - } - return structMap + structMap := make(map[string]any) + if s.ProductId != nil { + structMap["product_id"] = s.ProductId + } + if s.ProductPricePointId != nil { + structMap["product_price_point_id"] = s.ProductPricePointId + } + if s.IncludeTrial != nil { + structMap["include_trial"] = s.IncludeTrial + } + if s.IncludeInitialCharge != nil { + structMap["include_initial_charge"] = s.IncludeInitialCharge + } + if s.IncludeCoupons != nil { + structMap["include_coupons"] = s.IncludeCoupons + } + if s.PreservePeriod != nil { + structMap["preserve_period"] = s.PreservePeriod + } + if s.ProductHandle != nil { + structMap["product_handle"] = s.ProductHandle + } + if s.ProductPricePointHandle != nil { + structMap["product_price_point_handle"] = s.ProductPricePointHandle + } + if s.Proration != nil { + structMap["proration"] = s.Proration.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionProductMigration. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionProductMigration. // It customizes the JSON unmarshaling process for SubscriptionProductMigration objects. func (s *SubscriptionProductMigration) UnmarshalJSON(input []byte) error { - temp := &struct { - ProductId *int `json:"product_id,omitempty"` - ProductPricePointId *int `json:"product_price_point_id,omitempty"` - IncludeTrial *bool `json:"include_trial,omitempty"` - IncludeInitialCharge *bool `json:"include_initial_charge,omitempty"` - IncludeCoupons *bool `json:"include_coupons,omitempty"` - PreservePeriod *bool `json:"preserve_period,omitempty"` - ProductHandle *string `json:"product_handle,omitempty"` - ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` - Proration *Proration `json:"proration,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.ProductId = temp.ProductId - s.ProductPricePointId = temp.ProductPricePointId - s.IncludeTrial = temp.IncludeTrial - s.IncludeInitialCharge = temp.IncludeInitialCharge - s.IncludeCoupons = temp.IncludeCoupons - s.PreservePeriod = temp.PreservePeriod - s.ProductHandle = temp.ProductHandle - s.ProductPricePointHandle = temp.ProductPricePointHandle - s.Proration = temp.Proration - return nil + var temp subscriptionProductMigration + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.ProductId = temp.ProductId + s.ProductPricePointId = temp.ProductPricePointId + s.IncludeTrial = temp.IncludeTrial + s.IncludeInitialCharge = temp.IncludeInitialCharge + s.IncludeCoupons = temp.IncludeCoupons + s.PreservePeriod = temp.PreservePeriod + s.ProductHandle = temp.ProductHandle + s.ProductPricePointHandle = temp.ProductPricePointHandle + s.Proration = temp.Proration + return nil +} + +// TODO +type subscriptionProductMigration struct { + ProductId *int `json:"product_id,omitempty"` + ProductPricePointId *int `json:"product_price_point_id,omitempty"` + IncludeTrial *bool `json:"include_trial,omitempty"` + IncludeInitialCharge *bool `json:"include_initial_charge,omitempty"` + IncludeCoupons *bool `json:"include_coupons,omitempty"` + PreservePeriod *bool `json:"preserve_period,omitempty"` + ProductHandle *string `json:"product_handle,omitempty"` + ProductPricePointHandle *string `json:"product_price_point_handle,omitempty"` + Proration *Proration `json:"proration,omitempty"` } diff --git a/models/subscription_product_migration_request.go b/models/subscription_product_migration_request.go index cc74bcdf..da87ffa4 100644 --- a/models/subscription_product_migration_request.go +++ b/models/subscription_product_migration_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // SubscriptionProductMigrationRequest represents a SubscriptionProductMigrationRequest struct. type SubscriptionProductMigrationRequest struct { - Migration SubscriptionProductMigration `json:"migration"` + Migration SubscriptionProductMigration `json:"migration"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionProductMigrationRequest. +// MarshalJSON implements the json.Marshaler interface for SubscriptionProductMigrationRequest. // It customizes the JSON marshaling process for SubscriptionProductMigrationRequest objects. func (s *SubscriptionProductMigrationRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionProductMigrationRequest object to a map representation for JSON marshaling. func (s *SubscriptionProductMigrationRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["migration"] = s.Migration.toMap() - return structMap + structMap := make(map[string]any) + structMap["migration"] = s.Migration.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionProductMigrationRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionProductMigrationRequest. // It customizes the JSON unmarshaling process for SubscriptionProductMigrationRequest objects. func (s *SubscriptionProductMigrationRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Migration SubscriptionProductMigration `json:"migration"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Migration = temp.Migration - return nil + var temp subscriptionProductMigrationRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.Migration = *temp.Migration + return nil +} + +// TODO +type subscriptionProductMigrationRequest struct { + Migration *SubscriptionProductMigration `json:"migration"` +} + +func (s *subscriptionProductMigrationRequest) validate() error { + var errs []string + if s.Migration == nil { + errs = append(errs, "required field `migration` is missing for type `Subscription Product Migration Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/subscription_response.go b/models/subscription_response.go index 220ea020..05ab6a1d 100644 --- a/models/subscription_response.go +++ b/models/subscription_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // SubscriptionResponse represents a SubscriptionResponse struct. type SubscriptionResponse struct { - Subscription *Subscription `json:"subscription,omitempty"` + Subscription *Subscription `json:"subscription,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for SubscriptionResponse. +// MarshalJSON implements the json.Marshaler interface for SubscriptionResponse. // It customizes the JSON marshaling process for SubscriptionResponse objects. func (s *SubscriptionResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(s.toMap()) + []byte, + error) { + return json.Marshal(s.toMap()) } // toMap converts the SubscriptionResponse object to a map representation for JSON marshaling. func (s *SubscriptionResponse) toMap() map[string]any { - structMap := make(map[string]any) - if s.Subscription != nil { - structMap["subscription"] = s.Subscription.toMap() - } - return structMap + structMap := make(map[string]any) + if s.Subscription != nil { + structMap["subscription"] = s.Subscription.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionResponse. // It customizes the JSON unmarshaling process for SubscriptionResponse objects. func (s *SubscriptionResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Subscription *Subscription `json:"subscription,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - s.Subscription = temp.Subscription - return nil + var temp subscriptionResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + s.Subscription = temp.Subscription + return nil +} + +// TODO +type subscriptionResponse struct { + Subscription *Subscription `json:"subscription,omitempty"` } diff --git a/models/subscription_state_change.go b/models/subscription_state_change.go new file mode 100644 index 00000000..4514e584 --- /dev/null +++ b/models/subscription_state_change.go @@ -0,0 +1,67 @@ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// SubscriptionStateChange represents a SubscriptionStateChange struct. +type SubscriptionStateChange struct { + PreviousSubscriptionState string `json:"previous_subscription_state"` + NewSubscriptionState string `json:"new_subscription_state"` +} + +// MarshalJSON implements the json.Marshaler interface for SubscriptionStateChange. +// It customizes the JSON marshaling process for SubscriptionStateChange objects. +func (s *SubscriptionStateChange) MarshalJSON() ( + []byte, + error) { + return json.Marshal(s.toMap()) +} + +// toMap converts the SubscriptionStateChange object to a map representation for JSON marshaling. +func (s *SubscriptionStateChange) toMap() map[string]any { + structMap := make(map[string]any) + structMap["previous_subscription_state"] = s.PreviousSubscriptionState + structMap["new_subscription_state"] = s.NewSubscriptionState + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for SubscriptionStateChange. +// It customizes the JSON unmarshaling process for SubscriptionStateChange objects. +func (s *SubscriptionStateChange) UnmarshalJSON(input []byte) error { + var temp subscriptionStateChange + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + s.PreviousSubscriptionState = *temp.PreviousSubscriptionState + s.NewSubscriptionState = *temp.NewSubscriptionState + return nil +} + +// TODO +type subscriptionStateChange struct { + PreviousSubscriptionState *string `json:"previous_subscription_state"` + NewSubscriptionState *string `json:"new_subscription_state"` +} + +func (s *subscriptionStateChange) validate() error { + var errs []string + if s.PreviousSubscriptionState == nil { + errs = append(errs, "required field `previous_subscription_state` is missing for type `Subscription State Change`") + } + if s.NewSubscriptionState == nil { + errs = append(errs, "required field `new_subscription_state` is missing for type `Subscription State Change`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/tax_configuration.go b/models/tax_configuration.go index aa06128e..496a0ffc 100644 --- a/models/tax_configuration.go +++ b/models/tax_configuration.go @@ -1,55 +1,57 @@ package models import ( - "encoding/json" + "encoding/json" ) // TaxConfiguration represents a TaxConfiguration struct. type TaxConfiguration struct { - Kind *TaxConfigurationKind `json:"kind,omitempty"` - DestinationAddress *TaxDestinationAddress `json:"destination_address,omitempty"` - // Returns `true` when Chargify has been properly configured to charge tax using the specified tax system. More details about taxes: https://maxio-chargify.zendesk.com/hc/en-us/articles/5405488905869-Taxes-Introduction - FullyConfigured *bool `json:"fully_configured,omitempty"` + Kind *TaxConfigurationKind `json:"kind,omitempty"` + DestinationAddress *TaxDestinationAddress `json:"destination_address,omitempty"` + // Returns `true` when Chargify has been properly configured to charge tax using the specified tax system. More details about taxes: https://maxio-chargify.zendesk.com/hc/en-us/articles/5405488905869-Taxes-Introduction + FullyConfigured *bool `json:"fully_configured,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for TaxConfiguration. +// MarshalJSON implements the json.Marshaler interface for TaxConfiguration. // It customizes the JSON marshaling process for TaxConfiguration objects. func (t *TaxConfiguration) MarshalJSON() ( - []byte, - error) { - return json.Marshal(t.toMap()) + []byte, + error) { + return json.Marshal(t.toMap()) } // toMap converts the TaxConfiguration object to a map representation for JSON marshaling. func (t *TaxConfiguration) toMap() map[string]any { - structMap := make(map[string]any) - if t.Kind != nil { - structMap["kind"] = t.Kind - } - if t.DestinationAddress != nil { - structMap["destination_address"] = t.DestinationAddress - } - if t.FullyConfigured != nil { - structMap["fully_configured"] = t.FullyConfigured - } - return structMap + structMap := make(map[string]any) + if t.Kind != nil { + structMap["kind"] = t.Kind + } + if t.DestinationAddress != nil { + structMap["destination_address"] = t.DestinationAddress + } + if t.FullyConfigured != nil { + structMap["fully_configured"] = t.FullyConfigured + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for TaxConfiguration. +// UnmarshalJSON implements the json.Unmarshaler interface for TaxConfiguration. // It customizes the JSON unmarshaling process for TaxConfiguration objects. func (t *TaxConfiguration) UnmarshalJSON(input []byte) error { - temp := &struct { - Kind *TaxConfigurationKind `json:"kind,omitempty"` - DestinationAddress *TaxDestinationAddress `json:"destination_address,omitempty"` - FullyConfigured *bool `json:"fully_configured,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - t.Kind = temp.Kind - t.DestinationAddress = temp.DestinationAddress - t.FullyConfigured = temp.FullyConfigured - return nil + var temp taxConfiguration + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + t.Kind = temp.Kind + t.DestinationAddress = temp.DestinationAddress + t.FullyConfigured = temp.FullyConfigured + return nil +} + +// TODO +type taxConfiguration struct { + Kind *TaxConfigurationKind `json:"kind,omitempty"` + DestinationAddress *TaxDestinationAddress `json:"destination_address,omitempty"` + FullyConfigured *bool `json:"fully_configured,omitempty"` } diff --git a/models/too_many_management_link_requests.go b/models/too_many_management_link_requests.go index 932b585a..33ad4733 100644 --- a/models/too_many_management_link_requests.go +++ b/models/too_many_management_link_requests.go @@ -1,50 +1,73 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "errors" + "log" + "strings" + "time" ) // TooManyManagementLinkRequests represents a TooManyManagementLinkRequests struct. type TooManyManagementLinkRequests struct { - Error string `json:"error"` - NewLinkAvailableAt time.Time `json:"new_link_available_at"` + Error string `json:"error"` + NewLinkAvailableAt time.Time `json:"new_link_available_at"` } -// MarshalJSON implements the json.Marshaler interface for TooManyManagementLinkRequests. +// MarshalJSON implements the json.Marshaler interface for TooManyManagementLinkRequests. // It customizes the JSON marshaling process for TooManyManagementLinkRequests objects. func (t *TooManyManagementLinkRequests) MarshalJSON() ( - []byte, - error) { - return json.Marshal(t.toMap()) + []byte, + error) { + return json.Marshal(t.toMap()) } // toMap converts the TooManyManagementLinkRequests object to a map representation for JSON marshaling. func (t *TooManyManagementLinkRequests) toMap() map[string]any { - structMap := make(map[string]any) - structMap["error"] = t.Error - structMap["new_link_available_at"] = t.NewLinkAvailableAt.Format(time.RFC3339) - return structMap + structMap := make(map[string]any) + structMap["error"] = t.Error + structMap["new_link_available_at"] = t.NewLinkAvailableAt.Format(time.RFC3339) + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for TooManyManagementLinkRequests. +// UnmarshalJSON implements the json.Unmarshaler interface for TooManyManagementLinkRequests. // It customizes the JSON unmarshaling process for TooManyManagementLinkRequests objects. func (t *TooManyManagementLinkRequests) UnmarshalJSON(input []byte) error { - temp := &struct { - Error string `json:"error"` - NewLinkAvailableAt string `json:"new_link_available_at"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - t.Error = temp.Error - NewLinkAvailableAtVal, err := time.Parse(time.RFC3339, temp.NewLinkAvailableAt) - if err != nil { - log.Fatalf("Cannot Parse new_link_available_at as % s format.", time.RFC3339) - } - t.NewLinkAvailableAt = NewLinkAvailableAtVal - return nil + var temp tooManyManagementLinkRequests + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + t.Error = *temp.Error + NewLinkAvailableAtVal, err := time.Parse(time.RFC3339, *temp.NewLinkAvailableAt) + if err != nil { + log.Fatalf("Cannot Parse new_link_available_at as % s format.", time.RFC3339) + } + t.NewLinkAvailableAt = NewLinkAvailableAtVal + return nil +} + +// TODO +type tooManyManagementLinkRequests struct { + Error *string `json:"error"` + NewLinkAvailableAt *string `json:"new_link_available_at"` +} + +func (t *tooManyManagementLinkRequests) validate() error { + var errs []string + if t.Error == nil { + errs = append(errs, "required field `error` is missing for type `Too Many Management Link Requests`") + } + if t.NewLinkAvailableAt == nil { + errs = append(errs, "required field `new_link_available_at` is missing for type `Too Many Management Link Requests`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_allocation_expiration_date.go b/models/update_allocation_expiration_date.go index b122de90..c4938a7a 100644 --- a/models/update_allocation_expiration_date.go +++ b/models/update_allocation_expiration_date.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateAllocationExpirationDate represents a UpdateAllocationExpirationDate struct. type UpdateAllocationExpirationDate struct { - Allocation *AllocationExpirationDate `json:"allocation,omitempty"` + Allocation *AllocationExpirationDate `json:"allocation,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdateAllocationExpirationDate. +// MarshalJSON implements the json.Marshaler interface for UpdateAllocationExpirationDate. // It customizes the JSON marshaling process for UpdateAllocationExpirationDate objects. func (u *UpdateAllocationExpirationDate) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateAllocationExpirationDate object to a map representation for JSON marshaling. func (u *UpdateAllocationExpirationDate) toMap() map[string]any { - structMap := make(map[string]any) - if u.Allocation != nil { - structMap["allocation"] = u.Allocation.toMap() - } - return structMap + structMap := make(map[string]any) + if u.Allocation != nil { + structMap["allocation"] = u.Allocation.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateAllocationExpirationDate. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateAllocationExpirationDate. // It customizes the JSON unmarshaling process for UpdateAllocationExpirationDate objects. func (u *UpdateAllocationExpirationDate) UnmarshalJSON(input []byte) error { - temp := &struct { - Allocation *AllocationExpirationDate `json:"allocation,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Allocation = temp.Allocation - return nil + var temp updateAllocationExpirationDate + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.Allocation = temp.Allocation + return nil +} + +// TODO +type updateAllocationExpirationDate struct { + Allocation *AllocationExpirationDate `json:"allocation,omitempty"` } diff --git a/models/update_component.go b/models/update_component.go index 8c6e2403..635db39c 100644 --- a/models/update_component.go +++ b/models/update_component.go @@ -1,97 +1,119 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateComponent represents a UpdateComponent struct. type UpdateComponent struct { - Handle *string `json:"handle,omitempty"` - // The name of the Component, suitable for display on statements. i.e. Text Messages. - Name *string `json:"name,omitempty"` - // The description of the component. - Description Optional[string] `json:"description"` - AccountingCode Optional[string] `json:"accounting_code"` - // Boolean flag describing whether a component is taxable or not. - Taxable *bool `json:"taxable,omitempty"` - // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. - TaxCode Optional[string] `json:"tax_code"` - // One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other - ItemCategory Optional[ItemCategory] `json:"item_category"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. - // Available values: `full`, `prorated`, `none`. - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` + Handle *string `json:"handle,omitempty"` + // The name of the Component, suitable for display on statements. i.e. Text Messages. + Name *string `json:"name,omitempty"` + // The description of the component. + Description Optional[string] `json:"description"` + AccountingCode Optional[string] `json:"accounting_code"` + // Boolean flag describing whether a component is taxable or not. + Taxable *bool `json:"taxable,omitempty"` + // A string representing the tax code related to the component type. This is especially important when using the Avalara service to tax based on locale. This attribute has a max length of 10 characters. + TaxCode Optional[string] `json:"tax_code"` + // One of the following: Business Software, Consumer Software, Digital Services, Physical Goods, Other + ItemCategory Optional[ItemCategory] `json:"item_category"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + // The type of credit to be created when upgrading/downgrading. Defaults to the component and then site setting if one is not provided. + // Available values: `full`, `prorated`, `none`. + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` } -// MarshalJSON implements the json.Marshaler interface for UpdateComponent. +// MarshalJSON implements the json.Marshaler interface for UpdateComponent. // It customizes the JSON marshaling process for UpdateComponent objects. func (u *UpdateComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateComponent object to a map representation for JSON marshaling. func (u *UpdateComponent) toMap() map[string]any { - structMap := make(map[string]any) - if u.Handle != nil { - structMap["handle"] = u.Handle - } - if u.Name != nil { - structMap["name"] = u.Name - } - if u.Description.IsValueSet() { - structMap["description"] = u.Description.Value() - } - if u.AccountingCode.IsValueSet() { - structMap["accounting_code"] = u.AccountingCode.Value() - } - if u.Taxable != nil { - structMap["taxable"] = u.Taxable - } - if u.TaxCode.IsValueSet() { - structMap["tax_code"] = u.TaxCode.Value() - } - if u.ItemCategory.IsValueSet() { - structMap["item_category"] = u.ItemCategory.Value() - } - if u.DisplayOnHostedPage != nil { - structMap["display_on_hosted_page"] = u.DisplayOnHostedPage - } - if u.UpgradeCharge.IsValueSet() { - structMap["upgrade_charge"] = u.UpgradeCharge.Value() - } - return structMap + structMap := make(map[string]any) + if u.Handle != nil { + structMap["handle"] = u.Handle + } + if u.Name != nil { + structMap["name"] = u.Name + } + if u.Description.IsValueSet() { + if u.Description.Value() != nil { + structMap["description"] = u.Description.Value() + } else { + structMap["description"] = nil + } + } + if u.AccountingCode.IsValueSet() { + if u.AccountingCode.Value() != nil { + structMap["accounting_code"] = u.AccountingCode.Value() + } else { + structMap["accounting_code"] = nil + } + } + if u.Taxable != nil { + structMap["taxable"] = u.Taxable + } + if u.TaxCode.IsValueSet() { + if u.TaxCode.Value() != nil { + structMap["tax_code"] = u.TaxCode.Value() + } else { + structMap["tax_code"] = nil + } + } + if u.ItemCategory.IsValueSet() { + if u.ItemCategory.Value() != nil { + structMap["item_category"] = u.ItemCategory.Value() + } else { + structMap["item_category"] = nil + } + } + if u.DisplayOnHostedPage != nil { + structMap["display_on_hosted_page"] = u.DisplayOnHostedPage + } + if u.UpgradeCharge.IsValueSet() { + if u.UpgradeCharge.Value() != nil { + structMap["upgrade_charge"] = u.UpgradeCharge.Value() + } else { + structMap["upgrade_charge"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateComponent. // It customizes the JSON unmarshaling process for UpdateComponent objects. func (u *UpdateComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - Handle *string `json:"handle,omitempty"` - Name *string `json:"name,omitempty"` - Description Optional[string] `json:"description"` - AccountingCode Optional[string] `json:"accounting_code"` - Taxable *bool `json:"taxable,omitempty"` - TaxCode Optional[string] `json:"tax_code"` - ItemCategory Optional[ItemCategory] `json:"item_category"` - DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` - UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Handle = temp.Handle - u.Name = temp.Name - u.Description = temp.Description - u.AccountingCode = temp.AccountingCode - u.Taxable = temp.Taxable - u.TaxCode = temp.TaxCode - u.ItemCategory = temp.ItemCategory - u.DisplayOnHostedPage = temp.DisplayOnHostedPage - u.UpgradeCharge = temp.UpgradeCharge - return nil + var temp updateComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.Handle = temp.Handle + u.Name = temp.Name + u.Description = temp.Description + u.AccountingCode = temp.AccountingCode + u.Taxable = temp.Taxable + u.TaxCode = temp.TaxCode + u.ItemCategory = temp.ItemCategory + u.DisplayOnHostedPage = temp.DisplayOnHostedPage + u.UpgradeCharge = temp.UpgradeCharge + return nil +} + +// TODO +type updateComponent struct { + Handle *string `json:"handle,omitempty"` + Name *string `json:"name,omitempty"` + Description Optional[string] `json:"description"` + AccountingCode Optional[string] `json:"accounting_code"` + Taxable *bool `json:"taxable,omitempty"` + TaxCode Optional[string] `json:"tax_code"` + ItemCategory Optional[ItemCategory] `json:"item_category"` + DisplayOnHostedPage *bool `json:"display_on_hosted_page,omitempty"` + UpgradeCharge Optional[CreditType] `json:"upgrade_charge"` } diff --git a/models/update_component_price_point.go b/models/update_component_price_point.go index 9a08b1c2..a1c9c132 100644 --- a/models/update_component_price_point.go +++ b/models/update_component_price_point.go @@ -1,89 +1,91 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateComponentPricePoint represents a UpdateComponentPricePoint struct. type UpdateComponentPricePoint struct { - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - // Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` - // Whether or not the price point includes tax - TaxIncluded *bool `json:"tax_included,omitempty"` - // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. - Interval *int `json:"interval,omitempty"` - // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - Prices []UpdatePrice `json:"prices,omitempty"` + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + // Whether to use the site level exchange rate or define your own prices for each currency if you have multiple currencies defined on the site. + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + // Whether or not the price point includes tax + TaxIncluded *bool `json:"tax_included,omitempty"` + // The numerical interval. i.e. an interval of ‘30’ coupled with an interval_unit of day would mean this component price point would renew every 30 days. This property is only available for sites with Multifrequency enabled. + Interval *int `json:"interval,omitempty"` + // A string representing the interval unit for this component price point, either month or day. This property is only available for sites with Multifrequency enabled. + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + Prices []UpdatePrice `json:"prices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdateComponentPricePoint. +// MarshalJSON implements the json.Marshaler interface for UpdateComponentPricePoint. // It customizes the JSON marshaling process for UpdateComponentPricePoint objects. func (u *UpdateComponentPricePoint) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateComponentPricePoint object to a map representation for JSON marshaling. func (u *UpdateComponentPricePoint) toMap() map[string]any { - structMap := make(map[string]any) - if u.Name != nil { - structMap["name"] = u.Name - } - if u.Handle != nil { - structMap["handle"] = u.Handle - } - if u.PricingScheme != nil { - structMap["pricing_scheme"] = u.PricingScheme - } - if u.UseSiteExchangeRate != nil { - structMap["use_site_exchange_rate"] = u.UseSiteExchangeRate - } - if u.TaxIncluded != nil { - structMap["tax_included"] = u.TaxIncluded - } - if u.Interval != nil { - structMap["interval"] = u.Interval - } - if u.IntervalUnit != nil { - structMap["interval_unit"] = u.IntervalUnit - } - if u.Prices != nil { - structMap["prices"] = u.Prices - } - return structMap + structMap := make(map[string]any) + if u.Name != nil { + structMap["name"] = u.Name + } + if u.Handle != nil { + structMap["handle"] = u.Handle + } + if u.PricingScheme != nil { + structMap["pricing_scheme"] = u.PricingScheme + } + if u.UseSiteExchangeRate != nil { + structMap["use_site_exchange_rate"] = u.UseSiteExchangeRate + } + if u.TaxIncluded != nil { + structMap["tax_included"] = u.TaxIncluded + } + if u.Interval != nil { + structMap["interval"] = u.Interval + } + if u.IntervalUnit != nil { + structMap["interval_unit"] = u.IntervalUnit + } + if u.Prices != nil { + structMap["prices"] = u.Prices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateComponentPricePoint. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateComponentPricePoint. // It customizes the JSON unmarshaling process for UpdateComponentPricePoint objects. func (u *UpdateComponentPricePoint) UnmarshalJSON(input []byte) error { - temp := &struct { - Name *string `json:"name,omitempty"` - Handle *string `json:"handle,omitempty"` - PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` - UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` - TaxIncluded *bool `json:"tax_included,omitempty"` - Interval *int `json:"interval,omitempty"` - IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` - Prices []UpdatePrice `json:"prices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Name = temp.Name - u.Handle = temp.Handle - u.PricingScheme = temp.PricingScheme - u.UseSiteExchangeRate = temp.UseSiteExchangeRate - u.TaxIncluded = temp.TaxIncluded - u.Interval = temp.Interval - u.IntervalUnit = temp.IntervalUnit - u.Prices = temp.Prices - return nil + var temp updateComponentPricePoint + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.Name = temp.Name + u.Handle = temp.Handle + u.PricingScheme = temp.PricingScheme + u.UseSiteExchangeRate = temp.UseSiteExchangeRate + u.TaxIncluded = temp.TaxIncluded + u.Interval = temp.Interval + u.IntervalUnit = temp.IntervalUnit + u.Prices = temp.Prices + return nil +} + +// TODO +type updateComponentPricePoint struct { + Name *string `json:"name,omitempty"` + Handle *string `json:"handle,omitempty"` + PricingScheme *PricingScheme `json:"pricing_scheme,omitempty"` + UseSiteExchangeRate *bool `json:"use_site_exchange_rate,omitempty"` + TaxIncluded *bool `json:"tax_included,omitempty"` + Interval *int `json:"interval,omitempty"` + IntervalUnit *IntervalUnit `json:"interval_unit,omitempty"` + Prices []UpdatePrice `json:"prices,omitempty"` } diff --git a/models/update_component_price_point_request.go b/models/update_component_price_point_request.go index f2d161c5..ed31c592 100644 --- a/models/update_component_price_point_request.go +++ b/models/update_component_price_point_request.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateComponentPricePointRequest represents a UpdateComponentPricePointRequest struct. type UpdateComponentPricePointRequest struct { - PricePoint *UpdateComponentPricePoint `json:"price_point,omitempty"` + PricePoint *UpdateComponentPricePoint `json:"price_point,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdateComponentPricePointRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateComponentPricePointRequest. // It customizes the JSON marshaling process for UpdateComponentPricePointRequest objects. func (u *UpdateComponentPricePointRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateComponentPricePointRequest object to a map representation for JSON marshaling. func (u *UpdateComponentPricePointRequest) toMap() map[string]any { - structMap := make(map[string]any) - if u.PricePoint != nil { - structMap["price_point"] = u.PricePoint.toMap() - } - return structMap + structMap := make(map[string]any) + if u.PricePoint != nil { + structMap["price_point"] = u.PricePoint.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateComponentPricePointRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateComponentPricePointRequest. // It customizes the JSON unmarshaling process for UpdateComponentPricePointRequest objects. func (u *UpdateComponentPricePointRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoint *UpdateComponentPricePoint `json:"price_point,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.PricePoint = temp.PricePoint - return nil + var temp updateComponentPricePointRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.PricePoint = temp.PricePoint + return nil +} + +// TODO +type updateComponentPricePointRequest struct { + PricePoint *UpdateComponentPricePoint `json:"price_point,omitempty"` } diff --git a/models/update_component_request.go b/models/update_component_request.go index fd7fe8f1..9eaf282c 100644 --- a/models/update_component_request.go +++ b/models/update_component_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdateComponentRequest represents a UpdateComponentRequest struct. type UpdateComponentRequest struct { - Component UpdateComponent `json:"component"` + Component UpdateComponent `json:"component"` } -// MarshalJSON implements the json.Marshaler interface for UpdateComponentRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateComponentRequest. // It customizes the JSON marshaling process for UpdateComponentRequest objects. func (u *UpdateComponentRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateComponentRequest object to a map representation for JSON marshaling. func (u *UpdateComponentRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["component"] = u.Component.toMap() - return structMap + structMap := make(map[string]any) + structMap["component"] = u.Component.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateComponentRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateComponentRequest. // It customizes the JSON unmarshaling process for UpdateComponentRequest objects. func (u *UpdateComponentRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Component UpdateComponent `json:"component"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Component = temp.Component - return nil + var temp updateComponentRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.Component = *temp.Component + return nil +} + +// TODO +type updateComponentRequest struct { + Component *UpdateComponent `json:"component"` +} + +func (u *updateComponentRequest) validate() error { + var errs []string + if u.Component == nil { + errs = append(errs, "required field `component` is missing for type `Update Component Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_coupon_currency.go b/models/update_coupon_currency.go index 794d7a11..e54b8bd5 100644 --- a/models/update_coupon_currency.go +++ b/models/update_coupon_currency.go @@ -1,46 +1,69 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdateCouponCurrency represents a UpdateCouponCurrency struct. type UpdateCouponCurrency struct { - // ISO code for the site defined currency. - Currency string `json:"currency"` - // Price for the given currency. - Price int `json:"price"` + // ISO code for the site defined currency. + Currency string `json:"currency"` + // Price for the given currency. + Price int `json:"price"` } -// MarshalJSON implements the json.Marshaler interface for UpdateCouponCurrency. +// MarshalJSON implements the json.Marshaler interface for UpdateCouponCurrency. // It customizes the JSON marshaling process for UpdateCouponCurrency objects. func (u *UpdateCouponCurrency) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateCouponCurrency object to a map representation for JSON marshaling. func (u *UpdateCouponCurrency) toMap() map[string]any { - structMap := make(map[string]any) - structMap["currency"] = u.Currency - structMap["price"] = u.Price - return structMap + structMap := make(map[string]any) + structMap["currency"] = u.Currency + structMap["price"] = u.Price + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateCouponCurrency. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateCouponCurrency. // It customizes the JSON unmarshaling process for UpdateCouponCurrency objects. func (u *UpdateCouponCurrency) UnmarshalJSON(input []byte) error { - temp := &struct { - Currency string `json:"currency"` - Price int `json:"price"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Currency = temp.Currency - u.Price = temp.Price - return nil + var temp updateCouponCurrency + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.Currency = *temp.Currency + u.Price = *temp.Price + return nil +} + +// TODO +type updateCouponCurrency struct { + Currency *string `json:"currency"` + Price *int `json:"price"` +} + +func (u *updateCouponCurrency) validate() error { + var errs []string + if u.Currency == nil { + errs = append(errs, "required field `currency` is missing for type `Update Coupon Currency`") + } + if u.Price == nil { + errs = append(errs, "required field `price` is missing for type `Update Coupon Currency`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_currency_price.go b/models/update_currency_price.go index c332576e..4a73254f 100644 --- a/models/update_currency_price.go +++ b/models/update_currency_price.go @@ -1,46 +1,69 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdateCurrencyPrice represents a UpdateCurrencyPrice struct. type UpdateCurrencyPrice struct { - // ID of the currency price record being updated - Id int `json:"id"` - // New price for the given currency - Price int `json:"price"` + // ID of the currency price record being updated + Id int `json:"id"` + // New price for the given currency + Price int `json:"price"` } -// MarshalJSON implements the json.Marshaler interface for UpdateCurrencyPrice. +// MarshalJSON implements the json.Marshaler interface for UpdateCurrencyPrice. // It customizes the JSON marshaling process for UpdateCurrencyPrice objects. func (u *UpdateCurrencyPrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateCurrencyPrice object to a map representation for JSON marshaling. func (u *UpdateCurrencyPrice) toMap() map[string]any { - structMap := make(map[string]any) - structMap["id"] = u.Id - structMap["price"] = u.Price - return structMap + structMap := make(map[string]any) + structMap["id"] = u.Id + structMap["price"] = u.Price + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateCurrencyPrice. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateCurrencyPrice. // It customizes the JSON unmarshaling process for UpdateCurrencyPrice objects. func (u *UpdateCurrencyPrice) UnmarshalJSON(input []byte) error { - temp := &struct { - Id int `json:"id"` - Price int `json:"price"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Id = temp.Id - u.Price = temp.Price - return nil + var temp updateCurrencyPrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.Id = *temp.Id + u.Price = *temp.Price + return nil +} + +// TODO +type updateCurrencyPrice struct { + Id *int `json:"id"` + Price *int `json:"price"` +} + +func (u *updateCurrencyPrice) validate() error { + var errs []string + if u.Id == nil { + errs = append(errs, "required field `id` is missing for type `Update Currency Price`") + } + if u.Price == nil { + errs = append(errs, "required field `price` is missing for type `Update Currency Price`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_currency_prices_request.go b/models/update_currency_prices_request.go index b2ca80cd..fd2e428e 100644 --- a/models/update_currency_prices_request.go +++ b/models/update_currency_prices_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdateCurrencyPricesRequest represents a UpdateCurrencyPricesRequest struct. type UpdateCurrencyPricesRequest struct { - CurrencyPrices []UpdateCurrencyPrice `json:"currency_prices"` + CurrencyPrices []UpdateCurrencyPrice `json:"currency_prices"` } -// MarshalJSON implements the json.Marshaler interface for UpdateCurrencyPricesRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateCurrencyPricesRequest. // It customizes the JSON marshaling process for UpdateCurrencyPricesRequest objects. func (u *UpdateCurrencyPricesRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateCurrencyPricesRequest object to a map representation for JSON marshaling. func (u *UpdateCurrencyPricesRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["currency_prices"] = u.CurrencyPrices - return structMap + structMap := make(map[string]any) + structMap["currency_prices"] = u.CurrencyPrices + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateCurrencyPricesRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateCurrencyPricesRequest. // It customizes the JSON unmarshaling process for UpdateCurrencyPricesRequest objects. func (u *UpdateCurrencyPricesRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - CurrencyPrices []UpdateCurrencyPrice `json:"currency_prices"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.CurrencyPrices = temp.CurrencyPrices - return nil + var temp updateCurrencyPricesRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.CurrencyPrices = *temp.CurrencyPrices + return nil +} + +// TODO +type updateCurrencyPricesRequest struct { + CurrencyPrices *[]UpdateCurrencyPrice `json:"currency_prices"` +} + +func (u *updateCurrencyPricesRequest) validate() error { + var errs []string + if u.CurrencyPrices == nil { + errs = append(errs, "required field `currency_prices` is missing for type `Update Currency Prices Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_customer.go b/models/update_customer.go index df34ce14..e16407bf 100644 --- a/models/update_customer.go +++ b/models/update_customer.go @@ -1,145 +1,151 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateCustomer represents a UpdateCustomer struct. type UpdateCustomer struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Email *string `json:"email,omitempty"` - CcEmails *string `json:"cc_emails,omitempty"` - Organization *string `json:"organization,omitempty"` - Reference *string `json:"reference,omitempty"` - Address *string `json:"address,omitempty"` - Address2 *string `json:"address_2,omitempty"` - City *string `json:"city,omitempty"` - State *string `json:"state,omitempty"` - Zip *string `json:"zip,omitempty"` - Country *string `json:"country,omitempty"` - Phone *string `json:"phone,omitempty"` - // Set a specific language on a customer record. - Locale *string `json:"locale,omitempty"` - VatNumber *string `json:"vat_number,omitempty"` - TaxExempt *bool `json:"tax_exempt,omitempty"` - TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` - ParentId Optional[int] `json:"parent_id"` + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Email *string `json:"email,omitempty"` + CcEmails *string `json:"cc_emails,omitempty"` + Organization *string `json:"organization,omitempty"` + Reference *string `json:"reference,omitempty"` + Address *string `json:"address,omitempty"` + Address2 *string `json:"address_2,omitempty"` + City *string `json:"city,omitempty"` + State *string `json:"state,omitempty"` + Zip *string `json:"zip,omitempty"` + Country *string `json:"country,omitempty"` + Phone *string `json:"phone,omitempty"` + // Set a specific language on a customer record. + Locale *string `json:"locale,omitempty"` + VatNumber *string `json:"vat_number,omitempty"` + TaxExempt *bool `json:"tax_exempt,omitempty"` + TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` + ParentId Optional[int] `json:"parent_id"` } -// MarshalJSON implements the json.Marshaler interface for UpdateCustomer. +// MarshalJSON implements the json.Marshaler interface for UpdateCustomer. // It customizes the JSON marshaling process for UpdateCustomer objects. func (u *UpdateCustomer) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateCustomer object to a map representation for JSON marshaling. func (u *UpdateCustomer) toMap() map[string]any { - structMap := make(map[string]any) - if u.FirstName != nil { - structMap["first_name"] = u.FirstName - } - if u.LastName != nil { - structMap["last_name"] = u.LastName - } - if u.Email != nil { - structMap["email"] = u.Email - } - if u.CcEmails != nil { - structMap["cc_emails"] = u.CcEmails - } - if u.Organization != nil { - structMap["organization"] = u.Organization - } - if u.Reference != nil { - structMap["reference"] = u.Reference - } - if u.Address != nil { - structMap["address"] = u.Address - } - if u.Address2 != nil { - structMap["address_2"] = u.Address2 - } - if u.City != nil { - structMap["city"] = u.City - } - if u.State != nil { - structMap["state"] = u.State - } - if u.Zip != nil { - structMap["zip"] = u.Zip - } - if u.Country != nil { - structMap["country"] = u.Country - } - if u.Phone != nil { - structMap["phone"] = u.Phone - } - if u.Locale != nil { - structMap["locale"] = u.Locale - } - if u.VatNumber != nil { - structMap["vat_number"] = u.VatNumber - } - if u.TaxExempt != nil { - structMap["tax_exempt"] = u.TaxExempt - } - if u.TaxExemptReason != nil { - structMap["tax_exempt_reason"] = u.TaxExemptReason - } - if u.ParentId.IsValueSet() { - structMap["parent_id"] = u.ParentId.Value() - } - return structMap + structMap := make(map[string]any) + if u.FirstName != nil { + structMap["first_name"] = u.FirstName + } + if u.LastName != nil { + structMap["last_name"] = u.LastName + } + if u.Email != nil { + structMap["email"] = u.Email + } + if u.CcEmails != nil { + structMap["cc_emails"] = u.CcEmails + } + if u.Organization != nil { + structMap["organization"] = u.Organization + } + if u.Reference != nil { + structMap["reference"] = u.Reference + } + if u.Address != nil { + structMap["address"] = u.Address + } + if u.Address2 != nil { + structMap["address_2"] = u.Address2 + } + if u.City != nil { + structMap["city"] = u.City + } + if u.State != nil { + structMap["state"] = u.State + } + if u.Zip != nil { + structMap["zip"] = u.Zip + } + if u.Country != nil { + structMap["country"] = u.Country + } + if u.Phone != nil { + structMap["phone"] = u.Phone + } + if u.Locale != nil { + structMap["locale"] = u.Locale + } + if u.VatNumber != nil { + structMap["vat_number"] = u.VatNumber + } + if u.TaxExempt != nil { + structMap["tax_exempt"] = u.TaxExempt + } + if u.TaxExemptReason != nil { + structMap["tax_exempt_reason"] = u.TaxExemptReason + } + if u.ParentId.IsValueSet() { + if u.ParentId.Value() != nil { + structMap["parent_id"] = u.ParentId.Value() + } else { + structMap["parent_id"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateCustomer. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateCustomer. // It customizes the JSON unmarshaling process for UpdateCustomer objects. func (u *UpdateCustomer) UnmarshalJSON(input []byte) error { - temp := &struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - Email *string `json:"email,omitempty"` - CcEmails *string `json:"cc_emails,omitempty"` - Organization *string `json:"organization,omitempty"` - Reference *string `json:"reference,omitempty"` - Address *string `json:"address,omitempty"` - Address2 *string `json:"address_2,omitempty"` - City *string `json:"city,omitempty"` - State *string `json:"state,omitempty"` - Zip *string `json:"zip,omitempty"` - Country *string `json:"country,omitempty"` - Phone *string `json:"phone,omitempty"` - Locale *string `json:"locale,omitempty"` - VatNumber *string `json:"vat_number,omitempty"` - TaxExempt *bool `json:"tax_exempt,omitempty"` - TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` - ParentId Optional[int] `json:"parent_id"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.FirstName = temp.FirstName - u.LastName = temp.LastName - u.Email = temp.Email - u.CcEmails = temp.CcEmails - u.Organization = temp.Organization - u.Reference = temp.Reference - u.Address = temp.Address - u.Address2 = temp.Address2 - u.City = temp.City - u.State = temp.State - u.Zip = temp.Zip - u.Country = temp.Country - u.Phone = temp.Phone - u.Locale = temp.Locale - u.VatNumber = temp.VatNumber - u.TaxExempt = temp.TaxExempt - u.TaxExemptReason = temp.TaxExemptReason - u.ParentId = temp.ParentId - return nil + var temp updateCustomer + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.FirstName = temp.FirstName + u.LastName = temp.LastName + u.Email = temp.Email + u.CcEmails = temp.CcEmails + u.Organization = temp.Organization + u.Reference = temp.Reference + u.Address = temp.Address + u.Address2 = temp.Address2 + u.City = temp.City + u.State = temp.State + u.Zip = temp.Zip + u.Country = temp.Country + u.Phone = temp.Phone + u.Locale = temp.Locale + u.VatNumber = temp.VatNumber + u.TaxExempt = temp.TaxExempt + u.TaxExemptReason = temp.TaxExemptReason + u.ParentId = temp.ParentId + return nil +} + +// TODO +type updateCustomer struct { + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + Email *string `json:"email,omitempty"` + CcEmails *string `json:"cc_emails,omitempty"` + Organization *string `json:"organization,omitempty"` + Reference *string `json:"reference,omitempty"` + Address *string `json:"address,omitempty"` + Address2 *string `json:"address_2,omitempty"` + City *string `json:"city,omitempty"` + State *string `json:"state,omitempty"` + Zip *string `json:"zip,omitempty"` + Country *string `json:"country,omitempty"` + Phone *string `json:"phone,omitempty"` + Locale *string `json:"locale,omitempty"` + VatNumber *string `json:"vat_number,omitempty"` + TaxExempt *bool `json:"tax_exempt,omitempty"` + TaxExemptReason *string `json:"tax_exempt_reason,omitempty"` + ParentId Optional[int] `json:"parent_id"` } diff --git a/models/update_customer_request.go b/models/update_customer_request.go index 9644675c..9b10c5b7 100644 --- a/models/update_customer_request.go +++ b/models/update_customer_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdateCustomerRequest represents a UpdateCustomerRequest struct. type UpdateCustomerRequest struct { - Customer UpdateCustomer `json:"customer"` + Customer UpdateCustomer `json:"customer"` } -// MarshalJSON implements the json.Marshaler interface for UpdateCustomerRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateCustomerRequest. // It customizes the JSON marshaling process for UpdateCustomerRequest objects. func (u *UpdateCustomerRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateCustomerRequest object to a map representation for JSON marshaling. func (u *UpdateCustomerRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["customer"] = u.Customer.toMap() - return structMap + structMap := make(map[string]any) + structMap["customer"] = u.Customer.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateCustomerRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateCustomerRequest. // It customizes the JSON unmarshaling process for UpdateCustomerRequest objects. func (u *UpdateCustomerRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Customer UpdateCustomer `json:"customer"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Customer = temp.Customer - return nil + var temp updateCustomerRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.Customer = *temp.Customer + return nil +} + +// TODO +type updateCustomerRequest struct { + Customer *UpdateCustomer `json:"customer"` +} + +func (u *updateCustomerRequest) validate() error { + var errs []string + if u.Customer == nil { + errs = append(errs, "required field `customer` is missing for type `Update Customer Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_metadata.go b/models/update_metadata.go index 8fc947fe..b9f7daf3 100644 --- a/models/update_metadata.go +++ b/models/update_metadata.go @@ -1,54 +1,56 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateMetadata represents a UpdateMetadata struct. type UpdateMetadata struct { - CurrentName *string `json:"current_name,omitempty"` - Name *string `json:"name,omitempty"` - Value *string `json:"value,omitempty"` + CurrentName *string `json:"current_name,omitempty"` + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdateMetadata. +// MarshalJSON implements the json.Marshaler interface for UpdateMetadata. // It customizes the JSON marshaling process for UpdateMetadata objects. func (u *UpdateMetadata) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateMetadata object to a map representation for JSON marshaling. func (u *UpdateMetadata) toMap() map[string]any { - structMap := make(map[string]any) - if u.CurrentName != nil { - structMap["current_name"] = u.CurrentName - } - if u.Name != nil { - structMap["name"] = u.Name - } - if u.Value != nil { - structMap["value"] = u.Value - } - return structMap + structMap := make(map[string]any) + if u.CurrentName != nil { + structMap["current_name"] = u.CurrentName + } + if u.Name != nil { + structMap["name"] = u.Name + } + if u.Value != nil { + structMap["value"] = u.Value + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateMetadata. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateMetadata. // It customizes the JSON unmarshaling process for UpdateMetadata objects. func (u *UpdateMetadata) UnmarshalJSON(input []byte) error { - temp := &struct { - CurrentName *string `json:"current_name,omitempty"` - Name *string `json:"name,omitempty"` - Value *string `json:"value,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.CurrentName = temp.CurrentName - u.Name = temp.Name - u.Value = temp.Value - return nil + var temp updateMetadata + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.CurrentName = temp.CurrentName + u.Name = temp.Name + u.Value = temp.Value + return nil +} + +// TODO +type updateMetadata struct { + CurrentName *string `json:"current_name,omitempty"` + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` } diff --git a/models/update_metadata_request.go b/models/update_metadata_request.go index ce18c844..531bfbf6 100644 --- a/models/update_metadata_request.go +++ b/models/update_metadata_request.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateMetadataRequest represents a UpdateMetadataRequest struct. type UpdateMetadataRequest struct { - Metadata *UpdateMetadata `json:"metadata,omitempty"` + Metadata *UpdateMetadata `json:"metadata,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdateMetadataRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateMetadataRequest. // It customizes the JSON marshaling process for UpdateMetadataRequest objects. func (u *UpdateMetadataRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateMetadataRequest object to a map representation for JSON marshaling. func (u *UpdateMetadataRequest) toMap() map[string]any { - structMap := make(map[string]any) - if u.Metadata != nil { - structMap["metadata"] = u.Metadata.toMap() - } - return structMap + structMap := make(map[string]any) + if u.Metadata != nil { + structMap["metadata"] = u.Metadata.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateMetadataRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateMetadataRequest. // It customizes the JSON unmarshaling process for UpdateMetadataRequest objects. func (u *UpdateMetadataRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Metadata *UpdateMetadata `json:"metadata,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Metadata = temp.Metadata - return nil + var temp updateMetadataRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.Metadata = temp.Metadata + return nil +} + +// TODO +type updateMetadataRequest struct { + Metadata *UpdateMetadata `json:"metadata,omitempty"` } diff --git a/models/update_metafield.go b/models/update_metafield.go new file mode 100644 index 00000000..32eb244a --- /dev/null +++ b/models/update_metafield.go @@ -0,0 +1,71 @@ +package models + +import ( + "encoding/json" +) + +// UpdateMetafield represents a UpdateMetafield struct. +type UpdateMetafield struct { + CurrentName *string `json:"current_name,omitempty"` + Name *string `json:"name,omitempty"` + // Warning: When updating a metafield's scope attribute, all scope attributes must be passed. Partially complete scope attributes will override the existing settings. + Scope *MetafieldScope `json:"scope,omitempty"` + // Indicates how data should be added to the metafield. For example, a text type is just a string, so a given metafield of this type can have any value attached. On the other hand, dropdown and radio have a set of allowed values that can be input, and appear differently on a Public Signup Page. Defaults to 'text' + InputType *MetafieldInput `json:"input_type,omitempty"` + // Only applicable when input_type is radio or dropdown + Enum []string `json:"enum,omitempty"` +} + +// MarshalJSON implements the json.Marshaler interface for UpdateMetafield. +// It customizes the JSON marshaling process for UpdateMetafield objects. +func (u *UpdateMetafield) MarshalJSON() ( + []byte, + error) { + return json.Marshal(u.toMap()) +} + +// toMap converts the UpdateMetafield object to a map representation for JSON marshaling. +func (u *UpdateMetafield) toMap() map[string]any { + structMap := make(map[string]any) + if u.CurrentName != nil { + structMap["current_name"] = u.CurrentName + } + if u.Name != nil { + structMap["name"] = u.Name + } + if u.Scope != nil { + structMap["scope"] = u.Scope.toMap() + } + if u.InputType != nil { + structMap["input_type"] = u.InputType + } + if u.Enum != nil { + structMap["enum"] = u.Enum + } + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateMetafield. +// It customizes the JSON unmarshaling process for UpdateMetafield objects. +func (u *UpdateMetafield) UnmarshalJSON(input []byte) error { + var temp updateMetafield + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.CurrentName = temp.CurrentName + u.Name = temp.Name + u.Scope = temp.Scope + u.InputType = temp.InputType + u.Enum = temp.Enum + return nil +} + +// TODO +type updateMetafield struct { + CurrentName *string `json:"current_name,omitempty"` + Name *string `json:"name,omitempty"` + Scope *MetafieldScope `json:"scope,omitempty"` + InputType *MetafieldInput `json:"input_type,omitempty"` + Enum []string `json:"enum,omitempty"` +} diff --git a/models/update_metafields_request.go b/models/update_metafields_request.go index a14ff8f7..7777e522 100644 --- a/models/update_metafields_request.go +++ b/models/update_metafields_request.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateMetafieldsRequest represents a UpdateMetafieldsRequest struct. type UpdateMetafieldsRequest struct { - Metafields *interface{} `json:"metafields,omitempty"` + Metafields *UpdateMetafieldsRequestMetafields `json:"metafields,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdateMetafieldsRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateMetafieldsRequest. // It customizes the JSON marshaling process for UpdateMetafieldsRequest objects. func (u *UpdateMetafieldsRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateMetafieldsRequest object to a map representation for JSON marshaling. func (u *UpdateMetafieldsRequest) toMap() map[string]any { - structMap := make(map[string]any) - if u.Metafields != nil { - structMap["metafields"] = u.Metafields - } - return structMap + structMap := make(map[string]any) + if u.Metafields != nil { + structMap["metafields"] = u.Metafields.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateMetafieldsRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateMetafieldsRequest. // It customizes the JSON unmarshaling process for UpdateMetafieldsRequest objects. func (u *UpdateMetafieldsRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Metafields *interface{} `json:"metafields,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Metafields = temp.Metafields - return nil + var temp updateMetafieldsRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.Metafields = temp.Metafields + return nil +} + +// TODO +type updateMetafieldsRequest struct { + Metafields *UpdateMetafieldsRequestMetafields `json:"metafields,omitempty"` } diff --git a/models/update_metafields_request_metafields.go b/models/update_metafields_request_metafields.go new file mode 100644 index 00000000..88588d4a --- /dev/null +++ b/models/update_metafields_request_metafields.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// UpdateMetafieldsRequestMetafields represents a UpdateMetafieldsRequestMetafields struct. +// This is a container for one-of cases. +type UpdateMetafieldsRequestMetafields struct { + value any + isUpdateMetafield bool + isArrayOfUpdateMetafield bool +} + +// String converts the UpdateMetafieldsRequestMetafields object to a string representation. +func (u UpdateMetafieldsRequestMetafields) String() string { + if bytes, err := json.Marshal(u.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for UpdateMetafieldsRequestMetafields. +// It customizes the JSON marshaling process for UpdateMetafieldsRequestMetafields objects. +func (u *UpdateMetafieldsRequestMetafields) MarshalJSON() ( + []byte, + error) { + if u.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.UpdateMetafieldsRequestMetafieldsContainer.From*` functions to initialize the UpdateMetafieldsRequestMetafields object.") + } + return json.Marshal(u.toMap()) +} + +// toMap converts the UpdateMetafieldsRequestMetafields object to a map representation for JSON marshaling. +func (u *UpdateMetafieldsRequestMetafields) toMap() any { + switch obj := u.value.(type) { + case *UpdateMetafield: + return obj.toMap() + case *[]UpdateMetafield: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateMetafieldsRequestMetafields. +// It customizes the JSON unmarshaling process for UpdateMetafieldsRequestMetafields objects. +func (u *UpdateMetafieldsRequestMetafields) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&UpdateMetafield{}, false, &u.isUpdateMetafield), + NewTypeHolder(&[]UpdateMetafield{}, false, &u.isArrayOfUpdateMetafield), + ) + + u.value = result + return err +} + +func (u *UpdateMetafieldsRequestMetafields) AsUpdateMetafield() ( + *UpdateMetafield, + bool) { + if !u.isUpdateMetafield { + return nil, false + } + return u.value.(*UpdateMetafield), true +} + +func (u *UpdateMetafieldsRequestMetafields) AsArrayOfUpdateMetafield() ( + *[]UpdateMetafield, + bool) { + if !u.isArrayOfUpdateMetafield { + return nil, false + } + return u.value.(*[]UpdateMetafield), true +} + +// internalUpdateMetafieldsRequestMetafields represents a updateMetafieldsRequestMetafields struct. +// This is a container for one-of cases. +type internalUpdateMetafieldsRequestMetafields struct{} + +var UpdateMetafieldsRequestMetafieldsContainer internalUpdateMetafieldsRequestMetafields + +func (u *internalUpdateMetafieldsRequestMetafields) FromUpdateMetafield(val UpdateMetafield) UpdateMetafieldsRequestMetafields { + return UpdateMetafieldsRequestMetafields{value: &val} +} + +func (u *internalUpdateMetafieldsRequestMetafields) FromArrayOfUpdateMetafield(val []UpdateMetafield) UpdateMetafieldsRequestMetafields { + return UpdateMetafieldsRequestMetafields{value: &val} +} diff --git a/models/update_payment_profile.go b/models/update_payment_profile.go index 28792e36..7b62b154 100644 --- a/models/update_payment_profile.go +++ b/models/update_payment_profile.go @@ -1,127 +1,133 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdatePaymentProfile represents a UpdatePaymentProfile struct. type UpdatePaymentProfile struct { - // The first name of the card holder. - FirstName *string `json:"first_name,omitempty"` - // The last name of the card holder. - LastName *string `json:"last_name,omitempty"` - // The full credit card number - FullNumber *string `json:"full_number,omitempty"` - // The type of card used. - CardType *CardType `json:"card_type,omitempty"` - // (Optional when performing an Import via vault_token, required otherwise) The 1- or 2-digit credit card expiration month, as an integer or string, i.e. 5 - ExpirationMonth *string `json:"expiration_month,omitempty"` - // (Optional when performing a Import via vault_token, required otherwise) The 4-digit credit card expiration year, as an integer or string, i.e. 2012 - ExpirationYear *string `json:"expiration_year,omitempty"` - // The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. - CurrentVault *CurrentVault `json:"current_vault,omitempty"` - // The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. - BillingAddress *string `json:"billing_address,omitempty"` - // The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. - BillingCity *string `json:"billing_city,omitempty"` - // The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. - BillingState *string `json:"billing_state,omitempty"` - // The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. - BillingZip *string `json:"billing_zip,omitempty"` - // The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. - BillingCountry *string `json:"billing_country,omitempty"` - // Second line of the customer’s billing address i.e. Apt. 100 - BillingAddress2 Optional[string] `json:"billing_address_2"` + // The first name of the card holder. + FirstName *string `json:"first_name,omitempty"` + // The last name of the card holder. + LastName *string `json:"last_name,omitempty"` + // The full credit card number + FullNumber *string `json:"full_number,omitempty"` + // The type of card used. + CardType *CardType `json:"card_type,omitempty"` + // (Optional when performing an Import via vault_token, required otherwise) The 1- or 2-digit credit card expiration month, as an integer or string, i.e. 5 + ExpirationMonth *string `json:"expiration_month,omitempty"` + // (Optional when performing a Import via vault_token, required otherwise) The 4-digit credit card expiration year, as an integer or string, i.e. 2012 + ExpirationYear *string `json:"expiration_year,omitempty"` + // The vault that stores the payment profile with the provided `vault_token`. Use `bogus` for testing. + CurrentVault *CurrentVault `json:"current_vault,omitempty"` + // The credit card or bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway. + BillingAddress *string `json:"billing_address,omitempty"` + // The credit card or bank account billing address city (i.e. “Boston”). This value is merely passed through to the payment gateway. + BillingCity *string `json:"billing_city,omitempty"` + // The credit card or bank account billing address state (i.e. MA). This value is merely passed through to the payment gateway. This must conform to the [ISO_3166-1](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) in order to be valid for tax locale purposes. + BillingState *string `json:"billing_state,omitempty"` + // The credit card or bank account billing address zip code (i.e. 12345). This value is merely passed through to the payment gateway. + BillingZip *string `json:"billing_zip,omitempty"` + // The credit card or bank account billing address country, required in [ISO_3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format (i.e. “US”). This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation. If creating an ACH subscription, only US is supported at this time. + BillingCountry *string `json:"billing_country,omitempty"` + // Second line of the customer’s billing address i.e. Apt. 100 + BillingAddress2 Optional[string] `json:"billing_address_2"` } -// MarshalJSON implements the json.Marshaler interface for UpdatePaymentProfile. +// MarshalJSON implements the json.Marshaler interface for UpdatePaymentProfile. // It customizes the JSON marshaling process for UpdatePaymentProfile objects. func (u *UpdatePaymentProfile) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdatePaymentProfile object to a map representation for JSON marshaling. func (u *UpdatePaymentProfile) toMap() map[string]any { - structMap := make(map[string]any) - if u.FirstName != nil { - structMap["first_name"] = u.FirstName - } - if u.LastName != nil { - structMap["last_name"] = u.LastName - } - if u.FullNumber != nil { - structMap["full_number"] = u.FullNumber - } - if u.CardType != nil { - structMap["card_type"] = u.CardType - } - if u.ExpirationMonth != nil { - structMap["expiration_month"] = u.ExpirationMonth - } - if u.ExpirationYear != nil { - structMap["expiration_year"] = u.ExpirationYear - } - if u.CurrentVault != nil { - structMap["current_vault"] = u.CurrentVault - } - if u.BillingAddress != nil { - structMap["billing_address"] = u.BillingAddress - } - if u.BillingCity != nil { - structMap["billing_city"] = u.BillingCity - } - if u.BillingState != nil { - structMap["billing_state"] = u.BillingState - } - if u.BillingZip != nil { - structMap["billing_zip"] = u.BillingZip - } - if u.BillingCountry != nil { - structMap["billing_country"] = u.BillingCountry - } - if u.BillingAddress2.IsValueSet() { - structMap["billing_address_2"] = u.BillingAddress2.Value() - } - return structMap + structMap := make(map[string]any) + if u.FirstName != nil { + structMap["first_name"] = u.FirstName + } + if u.LastName != nil { + structMap["last_name"] = u.LastName + } + if u.FullNumber != nil { + structMap["full_number"] = u.FullNumber + } + if u.CardType != nil { + structMap["card_type"] = u.CardType + } + if u.ExpirationMonth != nil { + structMap["expiration_month"] = u.ExpirationMonth + } + if u.ExpirationYear != nil { + structMap["expiration_year"] = u.ExpirationYear + } + if u.CurrentVault != nil { + structMap["current_vault"] = u.CurrentVault + } + if u.BillingAddress != nil { + structMap["billing_address"] = u.BillingAddress + } + if u.BillingCity != nil { + structMap["billing_city"] = u.BillingCity + } + if u.BillingState != nil { + structMap["billing_state"] = u.BillingState + } + if u.BillingZip != nil { + structMap["billing_zip"] = u.BillingZip + } + if u.BillingCountry != nil { + structMap["billing_country"] = u.BillingCountry + } + if u.BillingAddress2.IsValueSet() { + if u.BillingAddress2.Value() != nil { + structMap["billing_address_2"] = u.BillingAddress2.Value() + } else { + structMap["billing_address_2"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdatePaymentProfile. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdatePaymentProfile. // It customizes the JSON unmarshaling process for UpdatePaymentProfile objects. func (u *UpdatePaymentProfile) UnmarshalJSON(input []byte) error { - temp := &struct { - FirstName *string `json:"first_name,omitempty"` - LastName *string `json:"last_name,omitempty"` - FullNumber *string `json:"full_number,omitempty"` - CardType *CardType `json:"card_type,omitempty"` - ExpirationMonth *string `json:"expiration_month,omitempty"` - ExpirationYear *string `json:"expiration_year,omitempty"` - CurrentVault *CurrentVault `json:"current_vault,omitempty"` - BillingAddress *string `json:"billing_address,omitempty"` - BillingCity *string `json:"billing_city,omitempty"` - BillingState *string `json:"billing_state,omitempty"` - BillingZip *string `json:"billing_zip,omitempty"` - BillingCountry *string `json:"billing_country,omitempty"` - BillingAddress2 Optional[string] `json:"billing_address_2"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.FirstName = temp.FirstName - u.LastName = temp.LastName - u.FullNumber = temp.FullNumber - u.CardType = temp.CardType - u.ExpirationMonth = temp.ExpirationMonth - u.ExpirationYear = temp.ExpirationYear - u.CurrentVault = temp.CurrentVault - u.BillingAddress = temp.BillingAddress - u.BillingCity = temp.BillingCity - u.BillingState = temp.BillingState - u.BillingZip = temp.BillingZip - u.BillingCountry = temp.BillingCountry - u.BillingAddress2 = temp.BillingAddress2 - return nil + var temp updatePaymentProfile + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.FirstName = temp.FirstName + u.LastName = temp.LastName + u.FullNumber = temp.FullNumber + u.CardType = temp.CardType + u.ExpirationMonth = temp.ExpirationMonth + u.ExpirationYear = temp.ExpirationYear + u.CurrentVault = temp.CurrentVault + u.BillingAddress = temp.BillingAddress + u.BillingCity = temp.BillingCity + u.BillingState = temp.BillingState + u.BillingZip = temp.BillingZip + u.BillingCountry = temp.BillingCountry + u.BillingAddress2 = temp.BillingAddress2 + return nil +} + +// TODO +type updatePaymentProfile struct { + FirstName *string `json:"first_name,omitempty"` + LastName *string `json:"last_name,omitempty"` + FullNumber *string `json:"full_number,omitempty"` + CardType *CardType `json:"card_type,omitempty"` + ExpirationMonth *string `json:"expiration_month,omitempty"` + ExpirationYear *string `json:"expiration_year,omitempty"` + CurrentVault *CurrentVault `json:"current_vault,omitempty"` + BillingAddress *string `json:"billing_address,omitempty"` + BillingCity *string `json:"billing_city,omitempty"` + BillingState *string `json:"billing_state,omitempty"` + BillingZip *string `json:"billing_zip,omitempty"` + BillingCountry *string `json:"billing_country,omitempty"` + BillingAddress2 Optional[string] `json:"billing_address_2"` } diff --git a/models/update_payment_profile_request.go b/models/update_payment_profile_request.go index 53db14ff..1da807db 100644 --- a/models/update_payment_profile_request.go +++ b/models/update_payment_profile_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdatePaymentProfileRequest represents a UpdatePaymentProfileRequest struct. type UpdatePaymentProfileRequest struct { - PaymentProfile UpdatePaymentProfile `json:"payment_profile"` + PaymentProfile UpdatePaymentProfile `json:"payment_profile"` } -// MarshalJSON implements the json.Marshaler interface for UpdatePaymentProfileRequest. +// MarshalJSON implements the json.Marshaler interface for UpdatePaymentProfileRequest. // It customizes the JSON marshaling process for UpdatePaymentProfileRequest objects. func (u *UpdatePaymentProfileRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdatePaymentProfileRequest object to a map representation for JSON marshaling. func (u *UpdatePaymentProfileRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["payment_profile"] = u.PaymentProfile.toMap() - return structMap + structMap := make(map[string]any) + structMap["payment_profile"] = u.PaymentProfile.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdatePaymentProfileRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdatePaymentProfileRequest. // It customizes the JSON unmarshaling process for UpdatePaymentProfileRequest objects. func (u *UpdatePaymentProfileRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - PaymentProfile UpdatePaymentProfile `json:"payment_profile"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.PaymentProfile = temp.PaymentProfile - return nil + var temp updatePaymentProfileRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.PaymentProfile = *temp.PaymentProfile + return nil +} + +// TODO +type updatePaymentProfileRequest struct { + PaymentProfile *UpdatePaymentProfile `json:"payment_profile"` +} + +func (u *updatePaymentProfileRequest) validate() error { + var errs []string + if u.PaymentProfile == nil { + errs = append(errs, "required field `payment_profile` is missing for type `Update Payment Profile Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_price.go b/models/update_price.go index a69dfb36..de6b7812 100644 --- a/models/update_price.go +++ b/models/update_price.go @@ -1,67 +1,69 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdatePrice represents a UpdatePrice struct. type UpdatePrice struct { - Id *int `json:"id,omitempty"` - EndingQuantity *interface{} `json:"ending_quantity,omitempty"` - // The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 - UnitPrice *interface{} `json:"unit_price,omitempty"` - Destroy *bool `json:"_destroy,omitempty"` - StartingQuantity *interface{} `json:"starting_quantity,omitempty"` + Id *int `json:"id,omitempty"` + EndingQuantity *UpdatePriceEndingQuantity `json:"ending_quantity,omitempty"` + // The price can contain up to 8 decimal places. i.e. 1.00 or 0.0012 or 0.00000065 + UnitPrice *UpdatePriceUnitPrice `json:"unit_price,omitempty"` + Destroy *bool `json:"_destroy,omitempty"` + StartingQuantity *UpdatePriceStartingQuantity `json:"starting_quantity,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdatePrice. +// MarshalJSON implements the json.Marshaler interface for UpdatePrice. // It customizes the JSON marshaling process for UpdatePrice objects. func (u *UpdatePrice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdatePrice object to a map representation for JSON marshaling. func (u *UpdatePrice) toMap() map[string]any { - structMap := make(map[string]any) - if u.Id != nil { - structMap["id"] = u.Id - } - if u.EndingQuantity != nil { - structMap["ending_quantity"] = u.EndingQuantity - } - if u.UnitPrice != nil { - structMap["unit_price"] = u.UnitPrice - } - if u.Destroy != nil { - structMap["_destroy"] = u.Destroy - } - if u.StartingQuantity != nil { - structMap["starting_quantity"] = u.StartingQuantity - } - return structMap + structMap := make(map[string]any) + if u.Id != nil { + structMap["id"] = u.Id + } + if u.EndingQuantity != nil { + structMap["ending_quantity"] = u.EndingQuantity.toMap() + } + if u.UnitPrice != nil { + structMap["unit_price"] = u.UnitPrice.toMap() + } + if u.Destroy != nil { + structMap["_destroy"] = u.Destroy + } + if u.StartingQuantity != nil { + structMap["starting_quantity"] = u.StartingQuantity.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdatePrice. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdatePrice. // It customizes the JSON unmarshaling process for UpdatePrice objects. func (u *UpdatePrice) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int `json:"id,omitempty"` - EndingQuantity *interface{} `json:"ending_quantity,omitempty"` - UnitPrice *interface{} `json:"unit_price,omitempty"` - Destroy *bool `json:"_destroy,omitempty"` - StartingQuantity *interface{} `json:"starting_quantity,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Id = temp.Id - u.EndingQuantity = temp.EndingQuantity - u.UnitPrice = temp.UnitPrice - u.Destroy = temp.Destroy - u.StartingQuantity = temp.StartingQuantity - return nil + var temp updatePrice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.Id = temp.Id + u.EndingQuantity = temp.EndingQuantity + u.UnitPrice = temp.UnitPrice + u.Destroy = temp.Destroy + u.StartingQuantity = temp.StartingQuantity + return nil +} + +// TODO +type updatePrice struct { + Id *int `json:"id,omitempty"` + EndingQuantity *UpdatePriceEndingQuantity `json:"ending_quantity,omitempty"` + UnitPrice *UpdatePriceUnitPrice `json:"unit_price,omitempty"` + Destroy *bool `json:"_destroy,omitempty"` + StartingQuantity *UpdatePriceStartingQuantity `json:"starting_quantity,omitempty"` } diff --git a/models/update_price_ending_quantity.go b/models/update_price_ending_quantity.go new file mode 100644 index 00000000..8fa712db --- /dev/null +++ b/models/update_price_ending_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// UpdatePriceEndingQuantity represents a UpdatePriceEndingQuantity struct. +// This is a container for one-of cases. +type UpdatePriceEndingQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the UpdatePriceEndingQuantity object to a string representation. +func (u UpdatePriceEndingQuantity) String() string { + if bytes, err := json.Marshal(u.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for UpdatePriceEndingQuantity. +// It customizes the JSON marshaling process for UpdatePriceEndingQuantity objects. +func (u *UpdatePriceEndingQuantity) MarshalJSON() ( + []byte, + error) { + if u.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.UpdatePriceEndingQuantityContainer.From*` functions to initialize the UpdatePriceEndingQuantity object.") + } + return json.Marshal(u.toMap()) +} + +// toMap converts the UpdatePriceEndingQuantity object to a map representation for JSON marshaling. +func (u *UpdatePriceEndingQuantity) toMap() any { + switch obj := u.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for UpdatePriceEndingQuantity. +// It customizes the JSON unmarshaling process for UpdatePriceEndingQuantity objects. +func (u *UpdatePriceEndingQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &u.isNumber), + NewTypeHolder(new(string), false, &u.isString), + ) + + u.value = result + return err +} + +func (u *UpdatePriceEndingQuantity) AsNumber() ( + *int, + bool) { + if !u.isNumber { + return nil, false + } + return u.value.(*int), true +} + +func (u *UpdatePriceEndingQuantity) AsString() ( + *string, + bool) { + if !u.isString { + return nil, false + } + return u.value.(*string), true +} + +// internalUpdatePriceEndingQuantity represents a updatePriceEndingQuantity struct. +// This is a container for one-of cases. +type internalUpdatePriceEndingQuantity struct{} + +var UpdatePriceEndingQuantityContainer internalUpdatePriceEndingQuantity + +func (u *internalUpdatePriceEndingQuantity) FromNumber(val int) UpdatePriceEndingQuantity { + return UpdatePriceEndingQuantity{value: &val} +} + +func (u *internalUpdatePriceEndingQuantity) FromString(val string) UpdatePriceEndingQuantity { + return UpdatePriceEndingQuantity{value: &val} +} diff --git a/models/update_price_starting_quantity.go b/models/update_price_starting_quantity.go new file mode 100644 index 00000000..46f4d094 --- /dev/null +++ b/models/update_price_starting_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// UpdatePriceStartingQuantity represents a UpdatePriceStartingQuantity struct. +// This is a container for one-of cases. +type UpdatePriceStartingQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the UpdatePriceStartingQuantity object to a string representation. +func (u UpdatePriceStartingQuantity) String() string { + if bytes, err := json.Marshal(u.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for UpdatePriceStartingQuantity. +// It customizes the JSON marshaling process for UpdatePriceStartingQuantity objects. +func (u *UpdatePriceStartingQuantity) MarshalJSON() ( + []byte, + error) { + if u.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.UpdatePriceStartingQuantityContainer.From*` functions to initialize the UpdatePriceStartingQuantity object.") + } + return json.Marshal(u.toMap()) +} + +// toMap converts the UpdatePriceStartingQuantity object to a map representation for JSON marshaling. +func (u *UpdatePriceStartingQuantity) toMap() any { + switch obj := u.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for UpdatePriceStartingQuantity. +// It customizes the JSON unmarshaling process for UpdatePriceStartingQuantity objects. +func (u *UpdatePriceStartingQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &u.isNumber), + NewTypeHolder(new(string), false, &u.isString), + ) + + u.value = result + return err +} + +func (u *UpdatePriceStartingQuantity) AsNumber() ( + *int, + bool) { + if !u.isNumber { + return nil, false + } + return u.value.(*int), true +} + +func (u *UpdatePriceStartingQuantity) AsString() ( + *string, + bool) { + if !u.isString { + return nil, false + } + return u.value.(*string), true +} + +// internalUpdatePriceStartingQuantity represents a updatePriceStartingQuantity struct. +// This is a container for one-of cases. +type internalUpdatePriceStartingQuantity struct{} + +var UpdatePriceStartingQuantityContainer internalUpdatePriceStartingQuantity + +func (u *internalUpdatePriceStartingQuantity) FromNumber(val int) UpdatePriceStartingQuantity { + return UpdatePriceStartingQuantity{value: &val} +} + +func (u *internalUpdatePriceStartingQuantity) FromString(val string) UpdatePriceStartingQuantity { + return UpdatePriceStartingQuantity{value: &val} +} diff --git a/models/update_price_unit_price.go b/models/update_price_unit_price.go new file mode 100644 index 00000000..046bf012 --- /dev/null +++ b/models/update_price_unit_price.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// UpdatePriceUnitPrice represents a UpdatePriceUnitPrice struct. +// This is a container for one-of cases. +type UpdatePriceUnitPrice struct { + value any + isPrecision bool + isString bool +} + +// String converts the UpdatePriceUnitPrice object to a string representation. +func (u UpdatePriceUnitPrice) String() string { + if bytes, err := json.Marshal(u.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for UpdatePriceUnitPrice. +// It customizes the JSON marshaling process for UpdatePriceUnitPrice objects. +func (u *UpdatePriceUnitPrice) MarshalJSON() ( + []byte, + error) { + if u.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.UpdatePriceUnitPriceContainer.From*` functions to initialize the UpdatePriceUnitPrice object.") + } + return json.Marshal(u.toMap()) +} + +// toMap converts the UpdatePriceUnitPrice object to a map representation for JSON marshaling. +func (u *UpdatePriceUnitPrice) toMap() any { + switch obj := u.value.(type) { + case *float64: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for UpdatePriceUnitPrice. +// It customizes the JSON unmarshaling process for UpdatePriceUnitPrice objects. +func (u *UpdatePriceUnitPrice) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(float64), false, &u.isPrecision), + NewTypeHolder(new(string), false, &u.isString), + ) + + u.value = result + return err +} + +func (u *UpdatePriceUnitPrice) AsPrecision() ( + *float64, + bool) { + if !u.isPrecision { + return nil, false + } + return u.value.(*float64), true +} + +func (u *UpdatePriceUnitPrice) AsString() ( + *string, + bool) { + if !u.isString { + return nil, false + } + return u.value.(*string), true +} + +// internalUpdatePriceUnitPrice represents a updatePriceUnitPrice struct. +// This is a container for one-of cases. +type internalUpdatePriceUnitPrice struct{} + +var UpdatePriceUnitPriceContainer internalUpdatePriceUnitPrice + +func (u *internalUpdatePriceUnitPrice) FromPrecision(val float64) UpdatePriceUnitPrice { + return UpdatePriceUnitPrice{value: &val} +} + +func (u *internalUpdatePriceUnitPrice) FromString(val string) UpdatePriceUnitPrice { + return UpdatePriceUnitPrice{value: &val} +} diff --git a/models/update_product_price_point.go b/models/update_product_price_point.go index 93df2e9d..6ce0925e 100644 --- a/models/update_product_price_point.go +++ b/models/update_product_price_point.go @@ -1,48 +1,50 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateProductPricePoint represents a UpdateProductPricePoint struct. type UpdateProductPricePoint struct { - Handle *string `json:"handle,omitempty"` - PriceInCents *int64 `json:"price_in_cents,omitempty"` + Handle *string `json:"handle,omitempty"` + PriceInCents *int64 `json:"price_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdateProductPricePoint. +// MarshalJSON implements the json.Marshaler interface for UpdateProductPricePoint. // It customizes the JSON marshaling process for UpdateProductPricePoint objects. func (u *UpdateProductPricePoint) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateProductPricePoint object to a map representation for JSON marshaling. func (u *UpdateProductPricePoint) toMap() map[string]any { - structMap := make(map[string]any) - if u.Handle != nil { - structMap["handle"] = u.Handle - } - if u.PriceInCents != nil { - structMap["price_in_cents"] = u.PriceInCents - } - return structMap + structMap := make(map[string]any) + if u.Handle != nil { + structMap["handle"] = u.Handle + } + if u.PriceInCents != nil { + structMap["price_in_cents"] = u.PriceInCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateProductPricePoint. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateProductPricePoint. // It customizes the JSON unmarshaling process for UpdateProductPricePoint objects. func (u *UpdateProductPricePoint) UnmarshalJSON(input []byte) error { - temp := &struct { - Handle *string `json:"handle,omitempty"` - PriceInCents *int64 `json:"price_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Handle = temp.Handle - u.PriceInCents = temp.PriceInCents - return nil + var temp updateProductPricePoint + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.Handle = temp.Handle + u.PriceInCents = temp.PriceInCents + return nil +} + +// TODO +type updateProductPricePoint struct { + Handle *string `json:"handle,omitempty"` + PriceInCents *int64 `json:"price_in_cents,omitempty"` } diff --git a/models/update_product_price_point_price_point_id.go b/models/update_product_price_point_price_point_id.go new file mode 100644 index 00000000..43721fd5 --- /dev/null +++ b/models/update_product_price_point_price_point_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// UpdateProductPricePointPricePointId represents a UpdateProductPricePointPricePointId struct. +// This is a container for one-of cases. +type UpdateProductPricePointPricePointId struct { + value any + isNumber bool + isString bool +} + +// String converts the UpdateProductPricePointPricePointId object to a string representation. +func (u UpdateProductPricePointPricePointId) String() string { + if bytes, err := json.Marshal(u.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for UpdateProductPricePointPricePointId. +// It customizes the JSON marshaling process for UpdateProductPricePointPricePointId objects. +func (u *UpdateProductPricePointPricePointId) MarshalJSON() ( + []byte, + error) { + if u.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.UpdateProductPricePointPricePointIdContainer.From*` functions to initialize the UpdateProductPricePointPricePointId object.") + } + return json.Marshal(u.toMap()) +} + +// toMap converts the UpdateProductPricePointPricePointId object to a map representation for JSON marshaling. +func (u *UpdateProductPricePointPricePointId) toMap() any { + switch obj := u.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateProductPricePointPricePointId. +// It customizes the JSON unmarshaling process for UpdateProductPricePointPricePointId objects. +func (u *UpdateProductPricePointPricePointId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &u.isNumber), + NewTypeHolder(new(string), false, &u.isString), + ) + + u.value = result + return err +} + +func (u *UpdateProductPricePointPricePointId) AsNumber() ( + *int, + bool) { + if !u.isNumber { + return nil, false + } + return u.value.(*int), true +} + +func (u *UpdateProductPricePointPricePointId) AsString() ( + *string, + bool) { + if !u.isString { + return nil, false + } + return u.value.(*string), true +} + +// internalUpdateProductPricePointPricePointId represents a updateProductPricePointPricePointId struct. +// This is a container for one-of cases. +type internalUpdateProductPricePointPricePointId struct{} + +var UpdateProductPricePointPricePointIdContainer internalUpdateProductPricePointPricePointId + +func (u *internalUpdateProductPricePointPricePointId) FromNumber(val int) UpdateProductPricePointPricePointId { + return UpdateProductPricePointPricePointId{value: &val} +} + +func (u *internalUpdateProductPricePointPricePointId) FromString(val string) UpdateProductPricePointPricePointId { + return UpdateProductPricePointPricePointId{value: &val} +} diff --git a/models/update_product_price_point_product_id.go b/models/update_product_price_point_product_id.go new file mode 100644 index 00000000..b791861a --- /dev/null +++ b/models/update_product_price_point_product_id.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// UpdateProductPricePointProductId represents a UpdateProductPricePointProductId struct. +// This is a container for one-of cases. +type UpdateProductPricePointProductId struct { + value any + isNumber bool + isString bool +} + +// String converts the UpdateProductPricePointProductId object to a string representation. +func (u UpdateProductPricePointProductId) String() string { + if bytes, err := json.Marshal(u.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for UpdateProductPricePointProductId. +// It customizes the JSON marshaling process for UpdateProductPricePointProductId objects. +func (u *UpdateProductPricePointProductId) MarshalJSON() ( + []byte, + error) { + if u.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.UpdateProductPricePointProductIdContainer.From*` functions to initialize the UpdateProductPricePointProductId object.") + } + return json.Marshal(u.toMap()) +} + +// toMap converts the UpdateProductPricePointProductId object to a map representation for JSON marshaling. +func (u *UpdateProductPricePointProductId) toMap() any { + switch obj := u.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateProductPricePointProductId. +// It customizes the JSON unmarshaling process for UpdateProductPricePointProductId objects. +func (u *UpdateProductPricePointProductId) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &u.isNumber), + NewTypeHolder(new(string), false, &u.isString), + ) + + u.value = result + return err +} + +func (u *UpdateProductPricePointProductId) AsNumber() ( + *int, + bool) { + if !u.isNumber { + return nil, false + } + return u.value.(*int), true +} + +func (u *UpdateProductPricePointProductId) AsString() ( + *string, + bool) { + if !u.isString { + return nil, false + } + return u.value.(*string), true +} + +// internalUpdateProductPricePointProductId represents a updateProductPricePointProductId struct. +// This is a container for one-of cases. +type internalUpdateProductPricePointProductId struct{} + +var UpdateProductPricePointProductIdContainer internalUpdateProductPricePointProductId + +func (u *internalUpdateProductPricePointProductId) FromNumber(val int) UpdateProductPricePointProductId { + return UpdateProductPricePointProductId{value: &val} +} + +func (u *internalUpdateProductPricePointProductId) FromString(val string) UpdateProductPricePointProductId { + return UpdateProductPricePointProductId{value: &val} +} diff --git a/models/update_product_price_point_request.go b/models/update_product_price_point_request.go index 0afaae38..4fd8ce37 100644 --- a/models/update_product_price_point_request.go +++ b/models/update_product_price_point_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdateProductPricePointRequest represents a UpdateProductPricePointRequest struct. type UpdateProductPricePointRequest struct { - PricePoint UpdateProductPricePoint `json:"price_point"` + PricePoint UpdateProductPricePoint `json:"price_point"` } -// MarshalJSON implements the json.Marshaler interface for UpdateProductPricePointRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateProductPricePointRequest. // It customizes the JSON marshaling process for UpdateProductPricePointRequest objects. func (u *UpdateProductPricePointRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateProductPricePointRequest object to a map representation for JSON marshaling. func (u *UpdateProductPricePointRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["price_point"] = u.PricePoint.toMap() - return structMap + structMap := make(map[string]any) + structMap["price_point"] = u.PricePoint.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateProductPricePointRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateProductPricePointRequest. // It customizes the JSON unmarshaling process for UpdateProductPricePointRequest objects. func (u *UpdateProductPricePointRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - PricePoint UpdateProductPricePoint `json:"price_point"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.PricePoint = temp.PricePoint - return nil + var temp updateProductPricePointRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.PricePoint = *temp.PricePoint + return nil +} + +// TODO +type updateProductPricePointRequest struct { + PricePoint *UpdateProductPricePoint `json:"price_point"` +} + +func (u *updateProductPricePointRequest) validate() error { + var errs []string + if u.PricePoint == nil { + errs = append(errs, "required field `price_point` is missing for type `Update Product Price Point Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_reason_code.go b/models/update_reason_code.go index 6c8200a1..5176a4d0 100644 --- a/models/update_reason_code.go +++ b/models/update_reason_code.go @@ -1,57 +1,59 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateReasonCode represents a UpdateReasonCode struct. type UpdateReasonCode struct { - // The unique identifier for the ReasonCode - Code *string `json:"code,omitempty"` - // The friendly summary of what the code signifies - Description *string `json:"description,omitempty"` - // The order that code appears in lists - Position *int `json:"position,omitempty"` + // The unique identifier for the ReasonCode + Code *string `json:"code,omitempty"` + // The friendly summary of what the code signifies + Description *string `json:"description,omitempty"` + // The order that code appears in lists + Position *int `json:"position,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdateReasonCode. +// MarshalJSON implements the json.Marshaler interface for UpdateReasonCode. // It customizes the JSON marshaling process for UpdateReasonCode objects. func (u *UpdateReasonCode) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateReasonCode object to a map representation for JSON marshaling. func (u *UpdateReasonCode) toMap() map[string]any { - structMap := make(map[string]any) - if u.Code != nil { - structMap["code"] = u.Code - } - if u.Description != nil { - structMap["description"] = u.Description - } - if u.Position != nil { - structMap["position"] = u.Position - } - return structMap + structMap := make(map[string]any) + if u.Code != nil { + structMap["code"] = u.Code + } + if u.Description != nil { + structMap["description"] = u.Description + } + if u.Position != nil { + structMap["position"] = u.Position + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateReasonCode. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateReasonCode. // It customizes the JSON unmarshaling process for UpdateReasonCode objects. func (u *UpdateReasonCode) UnmarshalJSON(input []byte) error { - temp := &struct { - Code *string `json:"code,omitempty"` - Description *string `json:"description,omitempty"` - Position *int `json:"position,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Code = temp.Code - u.Description = temp.Description - u.Position = temp.Position - return nil + var temp updateReasonCode + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.Code = temp.Code + u.Description = temp.Description + u.Position = temp.Position + return nil +} + +// TODO +type updateReasonCode struct { + Code *string `json:"code,omitempty"` + Description *string `json:"description,omitempty"` + Position *int `json:"position,omitempty"` } diff --git a/models/update_reason_code_request.go b/models/update_reason_code_request.go index 4fd881c5..c39ef3a0 100644 --- a/models/update_reason_code_request.go +++ b/models/update_reason_code_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdateReasonCodeRequest represents a UpdateReasonCodeRequest struct. type UpdateReasonCodeRequest struct { - ReasonCode UpdateReasonCode `json:"reason_code"` + ReasonCode UpdateReasonCode `json:"reason_code"` } -// MarshalJSON implements the json.Marshaler interface for UpdateReasonCodeRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateReasonCodeRequest. // It customizes the JSON marshaling process for UpdateReasonCodeRequest objects. func (u *UpdateReasonCodeRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateReasonCodeRequest object to a map representation for JSON marshaling. func (u *UpdateReasonCodeRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["reason_code"] = u.ReasonCode.toMap() - return structMap + structMap := make(map[string]any) + structMap["reason_code"] = u.ReasonCode.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateReasonCodeRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateReasonCodeRequest. // It customizes the JSON unmarshaling process for UpdateReasonCodeRequest objects. func (u *UpdateReasonCodeRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - ReasonCode UpdateReasonCode `json:"reason_code"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.ReasonCode = temp.ReasonCode - return nil + var temp updateReasonCodeRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.ReasonCode = *temp.ReasonCode + return nil +} + +// TODO +type updateReasonCodeRequest struct { + ReasonCode *UpdateReasonCode `json:"reason_code"` +} + +func (u *updateReasonCodeRequest) validate() error { + var errs []string + if u.ReasonCode == nil { + errs = append(errs, "required field `reason_code` is missing for type `Update Reason Code Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_segment.go b/models/update_segment.go index 8d448913..7314898d 100644 --- a/models/update_segment.go +++ b/models/update_segment.go @@ -1,47 +1,67 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdateSegment represents a UpdateSegment struct. type UpdateSegment struct { - // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. - PricingScheme PricingScheme `json:"pricing_scheme"` - Prices []CreateOrUpdateSegmentPrice `json:"prices,omitempty"` + // The identifier for the pricing scheme. See [Product Components](https://help.chargify.com/products/product-components.html) for an overview of pricing schemes. + PricingScheme PricingScheme `json:"pricing_scheme"` + Prices []CreateOrUpdateSegmentPrice `json:"prices,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdateSegment. +// MarshalJSON implements the json.Marshaler interface for UpdateSegment. // It customizes the JSON marshaling process for UpdateSegment objects. func (u *UpdateSegment) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateSegment object to a map representation for JSON marshaling. func (u *UpdateSegment) toMap() map[string]any { - structMap := make(map[string]any) - structMap["pricing_scheme"] = u.PricingScheme - if u.Prices != nil { - structMap["prices"] = u.Prices - } - return structMap + structMap := make(map[string]any) + structMap["pricing_scheme"] = u.PricingScheme + if u.Prices != nil { + structMap["prices"] = u.Prices + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSegment. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSegment. // It customizes the JSON unmarshaling process for UpdateSegment objects. func (u *UpdateSegment) UnmarshalJSON(input []byte) error { - temp := &struct { - PricingScheme PricingScheme `json:"pricing_scheme"` - Prices []CreateOrUpdateSegmentPrice `json:"prices,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.PricingScheme = temp.PricingScheme - u.Prices = temp.Prices - return nil + var temp updateSegment + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.PricingScheme = *temp.PricingScheme + u.Prices = temp.Prices + return nil +} + +// TODO +type updateSegment struct { + PricingScheme *PricingScheme `json:"pricing_scheme"` + Prices []CreateOrUpdateSegmentPrice `json:"prices,omitempty"` +} + +func (u *updateSegment) validate() error { + var errs []string + if u.PricingScheme == nil { + errs = append(errs, "required field `pricing_scheme` is missing for type `Update Segment`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_segment_request.go b/models/update_segment_request.go index 208553bf..667ffa34 100644 --- a/models/update_segment_request.go +++ b/models/update_segment_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdateSegmentRequest represents a UpdateSegmentRequest struct. type UpdateSegmentRequest struct { - Segment UpdateSegment `json:"segment"` + Segment UpdateSegment `json:"segment"` } -// MarshalJSON implements the json.Marshaler interface for UpdateSegmentRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateSegmentRequest. // It customizes the JSON marshaling process for UpdateSegmentRequest objects. func (u *UpdateSegmentRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateSegmentRequest object to a map representation for JSON marshaling. func (u *UpdateSegmentRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["segment"] = u.Segment.toMap() - return structMap + structMap := make(map[string]any) + structMap["segment"] = u.Segment.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSegmentRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSegmentRequest. // It customizes the JSON unmarshaling process for UpdateSegmentRequest objects. func (u *UpdateSegmentRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Segment UpdateSegment `json:"segment"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Segment = temp.Segment - return nil + var temp updateSegmentRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.Segment = *temp.Segment + return nil +} + +// TODO +type updateSegmentRequest struct { + Segment *UpdateSegment `json:"segment"` +} + +func (u *updateSegmentRequest) validate() error { + var errs []string + if u.Segment == nil { + errs = append(errs, "required field `segment` is missing for type `Update Segment Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_subscription.go b/models/update_subscription.go index 2526f869..f2ca0c2f 100644 --- a/models/update_subscription.go +++ b/models/update_subscription.go @@ -1,154 +1,164 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // UpdateSubscription represents a UpdateSubscription struct. type UpdateSubscription struct { - CreditCardAttributes *CreditCardAttributes `json:"credit_card_attributes,omitempty"` - // Set to the handle of a different product to change the subscription's product - ProductHandle *string `json:"product_handle,omitempty"` - // Set to the id of a different product to change the subscription's product - ProductId *int `json:"product_id,omitempty"` - ProductChangeDelayed *bool `json:"product_change_delayed,omitempty"` - // Set to an empty string to cancel a delayed product change. - NextProductId *string `json:"next_product_id,omitempty"` - NextProductPricePointId *string `json:"next_product_price_point_id,omitempty"` - // Use for subscriptions with product eligible for calendar billing only. Value can be 1-28 or 'end'. - SnapDay *interface{} `json:"snap_day,omitempty"` - NextBillingAt *time.Time `json:"next_billing_at,omitempty"` - PaymentCollectionMethod *string `json:"payment_collection_method,omitempty"` - ReceivesInvoiceEmails *bool `json:"receives_invoice_emails,omitempty"` - NetTerms *interface{} `json:"net_terms,omitempty"` - StoredCredentialTransactionId *int `json:"stored_credential_transaction_id,omitempty"` - Reference *string `json:"reference,omitempty"` - // (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription - CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` - // (Optional) An array of component ids and custom prices to be added to the subscription. - Components []UpdateSubscriptionComponent `json:"components,omitempty"` - // Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute. - DunningCommunicationDelayEnabled Optional[bool] `json:"dunning_communication_delay_enabled"` - // Time zone for the Dunning Communication Delay feature. - DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` + CreditCardAttributes *CreditCardAttributes `json:"credit_card_attributes,omitempty"` + // Set to the handle of a different product to change the subscription's product + ProductHandle *string `json:"product_handle,omitempty"` + // Set to the id of a different product to change the subscription's product + ProductId *int `json:"product_id,omitempty"` + ProductChangeDelayed *bool `json:"product_change_delayed,omitempty"` + // Set to an empty string to cancel a delayed product change. + NextProductId *string `json:"next_product_id,omitempty"` + NextProductPricePointId *string `json:"next_product_price_point_id,omitempty"` + // Use for subscriptions with product eligible for calendar billing only. Value can be 1-28 or 'end'. + SnapDay *UpdateSubscriptionSnapDay `json:"snap_day,omitempty"` + NextBillingAt *time.Time `json:"next_billing_at,omitempty"` + PaymentCollectionMethod *string `json:"payment_collection_method,omitempty"` + ReceivesInvoiceEmails *bool `json:"receives_invoice_emails,omitempty"` + NetTerms *UpdateSubscriptionNetTerms `json:"net_terms,omitempty"` + StoredCredentialTransactionId *int `json:"stored_credential_transaction_id,omitempty"` + Reference *string `json:"reference,omitempty"` + // (Optional) Used in place of `product_price_point_id` to define a custom price point unique to the subscription + CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` + // (Optional) An array of component ids and custom prices to be added to the subscription. + Components []UpdateSubscriptionComponent `json:"components,omitempty"` + // Enable Communication Delay feature, making sure no communication (email or SMS) is sent to the Customer between 9PM and 8AM in time zone set by the `dunning_communication_delay_time_zone` attribute. + DunningCommunicationDelayEnabled Optional[bool] `json:"dunning_communication_delay_enabled"` + // Time zone for the Dunning Communication Delay feature. + DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` } -// MarshalJSON implements the json.Marshaler interface for UpdateSubscription. +// MarshalJSON implements the json.Marshaler interface for UpdateSubscription. // It customizes the JSON marshaling process for UpdateSubscription objects. func (u *UpdateSubscription) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateSubscription object to a map representation for JSON marshaling. func (u *UpdateSubscription) toMap() map[string]any { - structMap := make(map[string]any) - if u.CreditCardAttributes != nil { - structMap["credit_card_attributes"] = u.CreditCardAttributes.toMap() - } - if u.ProductHandle != nil { - structMap["product_handle"] = u.ProductHandle - } - if u.ProductId != nil { - structMap["product_id"] = u.ProductId - } - if u.ProductChangeDelayed != nil { - structMap["product_change_delayed"] = u.ProductChangeDelayed - } - if u.NextProductId != nil { - structMap["next_product_id"] = u.NextProductId - } - if u.NextProductPricePointId != nil { - structMap["next_product_price_point_id"] = u.NextProductPricePointId - } - if u.SnapDay != nil { - structMap["snap_day"] = u.SnapDay - } - if u.NextBillingAt != nil { - structMap["next_billing_at"] = u.NextBillingAt.Format(time.RFC3339) - } - if u.PaymentCollectionMethod != nil { - structMap["payment_collection_method"] = u.PaymentCollectionMethod - } - if u.ReceivesInvoiceEmails != nil { - structMap["receives_invoice_emails"] = u.ReceivesInvoiceEmails - } - if u.NetTerms != nil { - structMap["net_terms"] = u.NetTerms - } - if u.StoredCredentialTransactionId != nil { - structMap["stored_credential_transaction_id"] = u.StoredCredentialTransactionId - } - if u.Reference != nil { - structMap["reference"] = u.Reference - } - if u.CustomPrice != nil { - structMap["custom_price"] = u.CustomPrice.toMap() - } - if u.Components != nil { - structMap["components"] = u.Components - } - if u.DunningCommunicationDelayEnabled.IsValueSet() { - structMap["dunning_communication_delay_enabled"] = u.DunningCommunicationDelayEnabled.Value() - } - if u.DunningCommunicationDelayTimeZone.IsValueSet() { - structMap["dunning_communication_delay_time_zone"] = u.DunningCommunicationDelayTimeZone.Value() - } - return structMap + structMap := make(map[string]any) + if u.CreditCardAttributes != nil { + structMap["credit_card_attributes"] = u.CreditCardAttributes.toMap() + } + if u.ProductHandle != nil { + structMap["product_handle"] = u.ProductHandle + } + if u.ProductId != nil { + structMap["product_id"] = u.ProductId + } + if u.ProductChangeDelayed != nil { + structMap["product_change_delayed"] = u.ProductChangeDelayed + } + if u.NextProductId != nil { + structMap["next_product_id"] = u.NextProductId + } + if u.NextProductPricePointId != nil { + structMap["next_product_price_point_id"] = u.NextProductPricePointId + } + if u.SnapDay != nil { + structMap["snap_day"] = u.SnapDay.toMap() + } + if u.NextBillingAt != nil { + structMap["next_billing_at"] = u.NextBillingAt.Format(time.RFC3339) + } + if u.PaymentCollectionMethod != nil { + structMap["payment_collection_method"] = u.PaymentCollectionMethod + } + if u.ReceivesInvoiceEmails != nil { + structMap["receives_invoice_emails"] = u.ReceivesInvoiceEmails + } + if u.NetTerms != nil { + structMap["net_terms"] = u.NetTerms.toMap() + } + if u.StoredCredentialTransactionId != nil { + structMap["stored_credential_transaction_id"] = u.StoredCredentialTransactionId + } + if u.Reference != nil { + structMap["reference"] = u.Reference + } + if u.CustomPrice != nil { + structMap["custom_price"] = u.CustomPrice.toMap() + } + if u.Components != nil { + structMap["components"] = u.Components + } + if u.DunningCommunicationDelayEnabled.IsValueSet() { + if u.DunningCommunicationDelayEnabled.Value() != nil { + structMap["dunning_communication_delay_enabled"] = u.DunningCommunicationDelayEnabled.Value() + } else { + structMap["dunning_communication_delay_enabled"] = nil + } + } + if u.DunningCommunicationDelayTimeZone.IsValueSet() { + if u.DunningCommunicationDelayTimeZone.Value() != nil { + structMap["dunning_communication_delay_time_zone"] = u.DunningCommunicationDelayTimeZone.Value() + } else { + structMap["dunning_communication_delay_time_zone"] = nil + } + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscription. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscription. // It customizes the JSON unmarshaling process for UpdateSubscription objects. func (u *UpdateSubscription) UnmarshalJSON(input []byte) error { - temp := &struct { - CreditCardAttributes *CreditCardAttributes `json:"credit_card_attributes,omitempty"` - ProductHandle *string `json:"product_handle,omitempty"` - ProductId *int `json:"product_id,omitempty"` - ProductChangeDelayed *bool `json:"product_change_delayed,omitempty"` - NextProductId *string `json:"next_product_id,omitempty"` - NextProductPricePointId *string `json:"next_product_price_point_id,omitempty"` - SnapDay *interface{} `json:"snap_day,omitempty"` - NextBillingAt *string `json:"next_billing_at,omitempty"` - PaymentCollectionMethod *string `json:"payment_collection_method,omitempty"` - ReceivesInvoiceEmails *bool `json:"receives_invoice_emails,omitempty"` - NetTerms *interface{} `json:"net_terms,omitempty"` - StoredCredentialTransactionId *int `json:"stored_credential_transaction_id,omitempty"` - Reference *string `json:"reference,omitempty"` - CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` - Components []UpdateSubscriptionComponent `json:"components,omitempty"` - DunningCommunicationDelayEnabled Optional[bool] `json:"dunning_communication_delay_enabled"` - DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.CreditCardAttributes = temp.CreditCardAttributes - u.ProductHandle = temp.ProductHandle - u.ProductId = temp.ProductId - u.ProductChangeDelayed = temp.ProductChangeDelayed - u.NextProductId = temp.NextProductId - u.NextProductPricePointId = temp.NextProductPricePointId - u.SnapDay = temp.SnapDay - if temp.NextBillingAt != nil { - NextBillingAtVal, err := time.Parse(time.RFC3339, *temp.NextBillingAt) - if err != nil { - log.Fatalf("Cannot Parse next_billing_at as % s format.", time.RFC3339) - } - u.NextBillingAt = &NextBillingAtVal - } - u.PaymentCollectionMethod = temp.PaymentCollectionMethod - u.ReceivesInvoiceEmails = temp.ReceivesInvoiceEmails - u.NetTerms = temp.NetTerms - u.StoredCredentialTransactionId = temp.StoredCredentialTransactionId - u.Reference = temp.Reference - u.CustomPrice = temp.CustomPrice - u.Components = temp.Components - u.DunningCommunicationDelayEnabled = temp.DunningCommunicationDelayEnabled - u.DunningCommunicationDelayTimeZone = temp.DunningCommunicationDelayTimeZone - return nil + var temp updateSubscription + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.CreditCardAttributes = temp.CreditCardAttributes + u.ProductHandle = temp.ProductHandle + u.ProductId = temp.ProductId + u.ProductChangeDelayed = temp.ProductChangeDelayed + u.NextProductId = temp.NextProductId + u.NextProductPricePointId = temp.NextProductPricePointId + u.SnapDay = temp.SnapDay + if temp.NextBillingAt != nil { + NextBillingAtVal, err := time.Parse(time.RFC3339, *temp.NextBillingAt) + if err != nil { + log.Fatalf("Cannot Parse next_billing_at as % s format.", time.RFC3339) + } + u.NextBillingAt = &NextBillingAtVal + } + u.PaymentCollectionMethod = temp.PaymentCollectionMethod + u.ReceivesInvoiceEmails = temp.ReceivesInvoiceEmails + u.NetTerms = temp.NetTerms + u.StoredCredentialTransactionId = temp.StoredCredentialTransactionId + u.Reference = temp.Reference + u.CustomPrice = temp.CustomPrice + u.Components = temp.Components + u.DunningCommunicationDelayEnabled = temp.DunningCommunicationDelayEnabled + u.DunningCommunicationDelayTimeZone = temp.DunningCommunicationDelayTimeZone + return nil +} + +// TODO +type updateSubscription struct { + CreditCardAttributes *CreditCardAttributes `json:"credit_card_attributes,omitempty"` + ProductHandle *string `json:"product_handle,omitempty"` + ProductId *int `json:"product_id,omitempty"` + ProductChangeDelayed *bool `json:"product_change_delayed,omitempty"` + NextProductId *string `json:"next_product_id,omitempty"` + NextProductPricePointId *string `json:"next_product_price_point_id,omitempty"` + SnapDay *UpdateSubscriptionSnapDay `json:"snap_day,omitempty"` + NextBillingAt *string `json:"next_billing_at,omitempty"` + PaymentCollectionMethod *string `json:"payment_collection_method,omitempty"` + ReceivesInvoiceEmails *bool `json:"receives_invoice_emails,omitempty"` + NetTerms *UpdateSubscriptionNetTerms `json:"net_terms,omitempty"` + StoredCredentialTransactionId *int `json:"stored_credential_transaction_id,omitempty"` + Reference *string `json:"reference,omitempty"` + CustomPrice *SubscriptionCustomPrice `json:"custom_price,omitempty"` + Components []UpdateSubscriptionComponent `json:"components,omitempty"` + DunningCommunicationDelayEnabled Optional[bool] `json:"dunning_communication_delay_enabled"` + DunningCommunicationDelayTimeZone Optional[string] `json:"dunning_communication_delay_time_zone"` } diff --git a/models/update_subscription_component.go b/models/update_subscription_component.go index 5c98132c..94822f86 100644 --- a/models/update_subscription_component.go +++ b/models/update_subscription_component.go @@ -1,49 +1,51 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateSubscriptionComponent represents a UpdateSubscriptionComponent struct. type UpdateSubscriptionComponent struct { - ComponentId *int `json:"component_id,omitempty"` - // Create or update custom pricing unique to the subscription. Used in place of `price_point_id`. - CustomPrice *ComponentCustomPrice `json:"custom_price,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + // Create or update custom pricing unique to the subscription. Used in place of `price_point_id`. + CustomPrice *ComponentCustomPrice `json:"custom_price,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionComponent. +// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionComponent. // It customizes the JSON marshaling process for UpdateSubscriptionComponent objects. func (u *UpdateSubscriptionComponent) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateSubscriptionComponent object to a map representation for JSON marshaling. func (u *UpdateSubscriptionComponent) toMap() map[string]any { - structMap := make(map[string]any) - if u.ComponentId != nil { - structMap["component_id"] = u.ComponentId - } - if u.CustomPrice != nil { - structMap["custom_price"] = u.CustomPrice.toMap() - } - return structMap + structMap := make(map[string]any) + if u.ComponentId != nil { + structMap["component_id"] = u.ComponentId + } + if u.CustomPrice != nil { + structMap["custom_price"] = u.CustomPrice.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionComponent. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionComponent. // It customizes the JSON unmarshaling process for UpdateSubscriptionComponent objects. func (u *UpdateSubscriptionComponent) UnmarshalJSON(input []byte) error { - temp := &struct { - ComponentId *int `json:"component_id,omitempty"` - CustomPrice *ComponentCustomPrice `json:"custom_price,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.ComponentId = temp.ComponentId - u.CustomPrice = temp.CustomPrice - return nil + var temp updateSubscriptionComponent + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.ComponentId = temp.ComponentId + u.CustomPrice = temp.CustomPrice + return nil +} + +// TODO +type updateSubscriptionComponent struct { + ComponentId *int `json:"component_id,omitempty"` + CustomPrice *ComponentCustomPrice `json:"custom_price,omitempty"` } diff --git a/models/update_subscription_group.go b/models/update_subscription_group.go index 9d9ebd1d..fc48d739 100644 --- a/models/update_subscription_group.go +++ b/models/update_subscription_group.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpdateSubscriptionGroup represents a UpdateSubscriptionGroup struct. type UpdateSubscriptionGroup struct { - MemberIds []int `json:"member_ids,omitempty"` + MemberIds []int `json:"member_ids,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionGroup. +// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionGroup. // It customizes the JSON marshaling process for UpdateSubscriptionGroup objects. func (u *UpdateSubscriptionGroup) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateSubscriptionGroup object to a map representation for JSON marshaling. func (u *UpdateSubscriptionGroup) toMap() map[string]any { - structMap := make(map[string]any) - if u.MemberIds != nil { - structMap["member_ids"] = u.MemberIds - } - return structMap + structMap := make(map[string]any) + if u.MemberIds != nil { + structMap["member_ids"] = u.MemberIds + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionGroup. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionGroup. // It customizes the JSON unmarshaling process for UpdateSubscriptionGroup objects. func (u *UpdateSubscriptionGroup) UnmarshalJSON(input []byte) error { - temp := &struct { - MemberIds []int `json:"member_ids,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.MemberIds = temp.MemberIds - return nil + var temp updateSubscriptionGroup + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.MemberIds = temp.MemberIds + return nil +} + +// TODO +type updateSubscriptionGroup struct { + MemberIds []int `json:"member_ids,omitempty"` } diff --git a/models/update_subscription_group_request.go b/models/update_subscription_group_request.go index 0860e92e..76a21a6c 100644 --- a/models/update_subscription_group_request.go +++ b/models/update_subscription_group_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdateSubscriptionGroupRequest represents a UpdateSubscriptionGroupRequest struct. type UpdateSubscriptionGroupRequest struct { - SubscriptionGroup UpdateSubscriptionGroup `json:"subscription_group"` + SubscriptionGroup UpdateSubscriptionGroup `json:"subscription_group"` } -// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionGroupRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionGroupRequest. // It customizes the JSON marshaling process for UpdateSubscriptionGroupRequest objects. func (u *UpdateSubscriptionGroupRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateSubscriptionGroupRequest object to a map representation for JSON marshaling. func (u *UpdateSubscriptionGroupRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscription_group"] = u.SubscriptionGroup.toMap() - return structMap + structMap := make(map[string]any) + structMap["subscription_group"] = u.SubscriptionGroup.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionGroupRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionGroupRequest. // It customizes the JSON unmarshaling process for UpdateSubscriptionGroupRequest objects. func (u *UpdateSubscriptionGroupRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - SubscriptionGroup UpdateSubscriptionGroup `json:"subscription_group"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.SubscriptionGroup = temp.SubscriptionGroup - return nil + var temp updateSubscriptionGroupRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.SubscriptionGroup = *temp.SubscriptionGroup + return nil +} + +// TODO +type updateSubscriptionGroupRequest struct { + SubscriptionGroup *UpdateSubscriptionGroup `json:"subscription_group"` +} + +func (u *updateSubscriptionGroupRequest) validate() error { + var errs []string + if u.SubscriptionGroup == nil { + errs = append(errs, "required field `subscription_group` is missing for type `Update Subscription Group Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_subscription_net_terms.go b/models/update_subscription_net_terms.go new file mode 100644 index 00000000..bd71a913 --- /dev/null +++ b/models/update_subscription_net_terms.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// UpdateSubscriptionNetTerms represents a UpdateSubscriptionNetTerms struct. +// This is a container for one-of cases. +type UpdateSubscriptionNetTerms struct { + value any + isString bool + isNumber bool +} + +// String converts the UpdateSubscriptionNetTerms object to a string representation. +func (u UpdateSubscriptionNetTerms) String() string { + if bytes, err := json.Marshal(u.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionNetTerms. +// It customizes the JSON marshaling process for UpdateSubscriptionNetTerms objects. +func (u *UpdateSubscriptionNetTerms) MarshalJSON() ( + []byte, + error) { + if u.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.UpdateSubscriptionNetTermsContainer.From*` functions to initialize the UpdateSubscriptionNetTerms object.") + } + return json.Marshal(u.toMap()) +} + +// toMap converts the UpdateSubscriptionNetTerms object to a map representation for JSON marshaling. +func (u *UpdateSubscriptionNetTerms) toMap() any { + switch obj := u.value.(type) { + case *string: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionNetTerms. +// It customizes the JSON unmarshaling process for UpdateSubscriptionNetTerms objects. +func (u *UpdateSubscriptionNetTerms) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(string), false, &u.isString), + NewTypeHolder(new(int), false, &u.isNumber), + ) + + u.value = result + return err +} + +func (u *UpdateSubscriptionNetTerms) AsString() ( + *string, + bool) { + if !u.isString { + return nil, false + } + return u.value.(*string), true +} + +func (u *UpdateSubscriptionNetTerms) AsNumber() ( + *int, + bool) { + if !u.isNumber { + return nil, false + } + return u.value.(*int), true +} + +// internalUpdateSubscriptionNetTerms represents a updateSubscriptionNetTerms struct. +// This is a container for one-of cases. +type internalUpdateSubscriptionNetTerms struct{} + +var UpdateSubscriptionNetTermsContainer internalUpdateSubscriptionNetTerms + +func (u *internalUpdateSubscriptionNetTerms) FromString(val string) UpdateSubscriptionNetTerms { + return UpdateSubscriptionNetTerms{value: &val} +} + +func (u *internalUpdateSubscriptionNetTerms) FromNumber(val int) UpdateSubscriptionNetTerms { + return UpdateSubscriptionNetTerms{value: &val} +} diff --git a/models/update_subscription_note.go b/models/update_subscription_note.go index a7865fdb..d446757a 100644 --- a/models/update_subscription_note.go +++ b/models/update_subscription_note.go @@ -1,45 +1,68 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) -// UpdateSubscriptionNote represents a UpdateSubscriptionNote struct. +// UpdateSubscriptionNote represents a UpdateSubscriptionNote struct. // Updatable fields for Subscription Note type UpdateSubscriptionNote struct { - Body string `json:"body"` - Sticky bool `json:"sticky"` + Body string `json:"body"` + Sticky bool `json:"sticky"` } -// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionNote. +// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionNote. // It customizes the JSON marshaling process for UpdateSubscriptionNote objects. func (u *UpdateSubscriptionNote) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateSubscriptionNote object to a map representation for JSON marshaling. func (u *UpdateSubscriptionNote) toMap() map[string]any { - structMap := make(map[string]any) - structMap["body"] = u.Body - structMap["sticky"] = u.Sticky - return structMap + structMap := make(map[string]any) + structMap["body"] = u.Body + structMap["sticky"] = u.Sticky + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionNote. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionNote. // It customizes the JSON unmarshaling process for UpdateSubscriptionNote objects. func (u *UpdateSubscriptionNote) UnmarshalJSON(input []byte) error { - temp := &struct { - Body string `json:"body"` - Sticky bool `json:"sticky"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Body = temp.Body - u.Sticky = temp.Sticky - return nil + var temp updateSubscriptionNote + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.Body = *temp.Body + u.Sticky = *temp.Sticky + return nil +} + +// TODO +type updateSubscriptionNote struct { + Body *string `json:"body"` + Sticky *bool `json:"sticky"` +} + +func (u *updateSubscriptionNote) validate() error { + var errs []string + if u.Body == nil { + errs = append(errs, "required field `body` is missing for type `Update Subscription Note`") + } + if u.Sticky == nil { + errs = append(errs, "required field `sticky` is missing for type `Update Subscription Note`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_subscription_note_request.go b/models/update_subscription_note_request.go index 83ea2eb5..30801979 100644 --- a/models/update_subscription_note_request.go +++ b/models/update_subscription_note_request.go @@ -1,42 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) -// UpdateSubscriptionNoteRequest represents a UpdateSubscriptionNoteRequest struct. +// UpdateSubscriptionNoteRequest represents a UpdateSubscriptionNoteRequest struct. // Updatable fields for Subscription Note type UpdateSubscriptionNoteRequest struct { - // Updatable fields for Subscription Note - Note UpdateSubscriptionNote `json:"note"` + // Updatable fields for Subscription Note + Note UpdateSubscriptionNote `json:"note"` } -// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionNoteRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionNoteRequest. // It customizes the JSON marshaling process for UpdateSubscriptionNoteRequest objects. func (u *UpdateSubscriptionNoteRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateSubscriptionNoteRequest object to a map representation for JSON marshaling. func (u *UpdateSubscriptionNoteRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["note"] = u.Note.toMap() - return structMap + structMap := make(map[string]any) + structMap["note"] = u.Note.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionNoteRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionNoteRequest. // It customizes the JSON unmarshaling process for UpdateSubscriptionNoteRequest objects. func (u *UpdateSubscriptionNoteRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Note UpdateSubscriptionNote `json:"note"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Note = temp.Note - return nil + var temp updateSubscriptionNoteRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.Note = *temp.Note + return nil +} + +// TODO +type updateSubscriptionNoteRequest struct { + Note *UpdateSubscriptionNote `json:"note"` +} + +func (u *updateSubscriptionNoteRequest) validate() error { + var errs []string + if u.Note == nil { + errs = append(errs, "required field `note` is missing for type `Update Subscription Note Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_subscription_request.go b/models/update_subscription_request.go index a35bb9f8..b7bfd1ed 100644 --- a/models/update_subscription_request.go +++ b/models/update_subscription_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpdateSubscriptionRequest represents a UpdateSubscriptionRequest struct. type UpdateSubscriptionRequest struct { - Subscription UpdateSubscription `json:"subscription"` + Subscription UpdateSubscription `json:"subscription"` } -// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionRequest. +// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionRequest. // It customizes the JSON marshaling process for UpdateSubscriptionRequest objects. func (u *UpdateSubscriptionRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpdateSubscriptionRequest object to a map representation for JSON marshaling. func (u *UpdateSubscriptionRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["subscription"] = u.Subscription.toMap() - return structMap + structMap := make(map[string]any) + structMap["subscription"] = u.Subscription.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionRequest. // It customizes the JSON unmarshaling process for UpdateSubscriptionRequest objects. func (u *UpdateSubscriptionRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Subscription UpdateSubscription `json:"subscription"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Subscription = temp.Subscription - return nil + var temp updateSubscriptionRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.Subscription = *temp.Subscription + return nil +} + +// TODO +type updateSubscriptionRequest struct { + Subscription *UpdateSubscription `json:"subscription"` +} + +func (u *updateSubscriptionRequest) validate() error { + var errs []string + if u.Subscription == nil { + errs = append(errs, "required field `subscription` is missing for type `Update Subscription Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/update_subscription_snap_day.go b/models/update_subscription_snap_day.go new file mode 100644 index 00000000..6267237d --- /dev/null +++ b/models/update_subscription_snap_day.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// UpdateSubscriptionSnapDay represents a UpdateSubscriptionSnapDay struct. +// This is a container for one-of cases. +type UpdateSubscriptionSnapDay struct { + value any + isSnapDay bool + isNumber bool +} + +// String converts the UpdateSubscriptionSnapDay object to a string representation. +func (u UpdateSubscriptionSnapDay) String() string { + if bytes, err := json.Marshal(u.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for UpdateSubscriptionSnapDay. +// It customizes the JSON marshaling process for UpdateSubscriptionSnapDay objects. +func (u *UpdateSubscriptionSnapDay) MarshalJSON() ( + []byte, + error) { + if u.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.UpdateSubscriptionSnapDayContainer.From*` functions to initialize the UpdateSubscriptionSnapDay object.") + } + return json.Marshal(u.toMap()) +} + +// toMap converts the UpdateSubscriptionSnapDay object to a map representation for JSON marshaling. +func (u *UpdateSubscriptionSnapDay) toMap() any { + switch obj := u.value.(type) { + case *SnapDay: + return *obj + case *int: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for UpdateSubscriptionSnapDay. +// It customizes the JSON unmarshaling process for UpdateSubscriptionSnapDay objects. +func (u *UpdateSubscriptionSnapDay) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(SnapDay), false, &u.isSnapDay), + NewTypeHolder(new(int), false, &u.isNumber), + ) + + u.value = result + return err +} + +func (u *UpdateSubscriptionSnapDay) AsSnapDay() ( + *SnapDay, + bool) { + if !u.isSnapDay { + return nil, false + } + return u.value.(*SnapDay), true +} + +func (u *UpdateSubscriptionSnapDay) AsNumber() ( + *int, + bool) { + if !u.isNumber { + return nil, false + } + return u.value.(*int), true +} + +// internalUpdateSubscriptionSnapDay represents a updateSubscriptionSnapDay struct. +// This is a container for one-of cases. +type internalUpdateSubscriptionSnapDay struct{} + +var UpdateSubscriptionSnapDayContainer internalUpdateSubscriptionSnapDay + +func (u *internalUpdateSubscriptionSnapDay) FromSnapDay(val SnapDay) UpdateSubscriptionSnapDay { + return UpdateSubscriptionSnapDay{value: &val} +} + +func (u *internalUpdateSubscriptionSnapDay) FromNumber(val int) UpdateSubscriptionSnapDay { + return UpdateSubscriptionSnapDay{value: &val} +} diff --git a/models/upsert_prepaid_configuration.go b/models/upsert_prepaid_configuration.go index 848644e1..b22d8ea6 100644 --- a/models/upsert_prepaid_configuration.go +++ b/models/upsert_prepaid_configuration.go @@ -1,60 +1,62 @@ package models import ( - "encoding/json" + "encoding/json" ) // UpsertPrepaidConfiguration represents a UpsertPrepaidConfiguration struct. type UpsertPrepaidConfiguration struct { - InitialFundingAmountInCents *int64 `json:"initial_funding_amount_in_cents,omitempty"` - ReplenishToAmountInCents *int64 `json:"replenish_to_amount_in_cents,omitempty"` - AutoReplenish *bool `json:"auto_replenish,omitempty"` - ReplenishThresholdAmountInCents *int64 `json:"replenish_threshold_amount_in_cents,omitempty"` + InitialFundingAmountInCents *int64 `json:"initial_funding_amount_in_cents,omitempty"` + ReplenishToAmountInCents *int64 `json:"replenish_to_amount_in_cents,omitempty"` + AutoReplenish *bool `json:"auto_replenish,omitempty"` + ReplenishThresholdAmountInCents *int64 `json:"replenish_threshold_amount_in_cents,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for UpsertPrepaidConfiguration. +// MarshalJSON implements the json.Marshaler interface for UpsertPrepaidConfiguration. // It customizes the JSON marshaling process for UpsertPrepaidConfiguration objects. func (u *UpsertPrepaidConfiguration) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpsertPrepaidConfiguration object to a map representation for JSON marshaling. func (u *UpsertPrepaidConfiguration) toMap() map[string]any { - structMap := make(map[string]any) - if u.InitialFundingAmountInCents != nil { - structMap["initial_funding_amount_in_cents"] = u.InitialFundingAmountInCents - } - if u.ReplenishToAmountInCents != nil { - structMap["replenish_to_amount_in_cents"] = u.ReplenishToAmountInCents - } - if u.AutoReplenish != nil { - structMap["auto_replenish"] = u.AutoReplenish - } - if u.ReplenishThresholdAmountInCents != nil { - structMap["replenish_threshold_amount_in_cents"] = u.ReplenishThresholdAmountInCents - } - return structMap + structMap := make(map[string]any) + if u.InitialFundingAmountInCents != nil { + structMap["initial_funding_amount_in_cents"] = u.InitialFundingAmountInCents + } + if u.ReplenishToAmountInCents != nil { + structMap["replenish_to_amount_in_cents"] = u.ReplenishToAmountInCents + } + if u.AutoReplenish != nil { + structMap["auto_replenish"] = u.AutoReplenish + } + if u.ReplenishThresholdAmountInCents != nil { + structMap["replenish_threshold_amount_in_cents"] = u.ReplenishThresholdAmountInCents + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpsertPrepaidConfiguration. +// UnmarshalJSON implements the json.Unmarshaler interface for UpsertPrepaidConfiguration. // It customizes the JSON unmarshaling process for UpsertPrepaidConfiguration objects. func (u *UpsertPrepaidConfiguration) UnmarshalJSON(input []byte) error { - temp := &struct { - InitialFundingAmountInCents *int64 `json:"initial_funding_amount_in_cents,omitempty"` - ReplenishToAmountInCents *int64 `json:"replenish_to_amount_in_cents,omitempty"` - AutoReplenish *bool `json:"auto_replenish,omitempty"` - ReplenishThresholdAmountInCents *int64 `json:"replenish_threshold_amount_in_cents,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.InitialFundingAmountInCents = temp.InitialFundingAmountInCents - u.ReplenishToAmountInCents = temp.ReplenishToAmountInCents - u.AutoReplenish = temp.AutoReplenish - u.ReplenishThresholdAmountInCents = temp.ReplenishThresholdAmountInCents - return nil + var temp upsertPrepaidConfiguration + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.InitialFundingAmountInCents = temp.InitialFundingAmountInCents + u.ReplenishToAmountInCents = temp.ReplenishToAmountInCents + u.AutoReplenish = temp.AutoReplenish + u.ReplenishThresholdAmountInCents = temp.ReplenishThresholdAmountInCents + return nil +} + +// TODO +type upsertPrepaidConfiguration struct { + InitialFundingAmountInCents *int64 `json:"initial_funding_amount_in_cents,omitempty"` + ReplenishToAmountInCents *int64 `json:"replenish_to_amount_in_cents,omitempty"` + AutoReplenish *bool `json:"auto_replenish,omitempty"` + ReplenishThresholdAmountInCents *int64 `json:"replenish_threshold_amount_in_cents,omitempty"` } diff --git a/models/upsert_prepaid_configuration_request.go b/models/upsert_prepaid_configuration_request.go index 15abf5f2..d214ebe2 100644 --- a/models/upsert_prepaid_configuration_request.go +++ b/models/upsert_prepaid_configuration_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UpsertPrepaidConfigurationRequest represents a UpsertPrepaidConfigurationRequest struct. type UpsertPrepaidConfigurationRequest struct { - PrepaidConfiguration UpsertPrepaidConfiguration `json:"prepaid_configuration"` + PrepaidConfiguration UpsertPrepaidConfiguration `json:"prepaid_configuration"` } -// MarshalJSON implements the json.Marshaler interface for UpsertPrepaidConfigurationRequest. +// MarshalJSON implements the json.Marshaler interface for UpsertPrepaidConfigurationRequest. // It customizes the JSON marshaling process for UpsertPrepaidConfigurationRequest objects. func (u *UpsertPrepaidConfigurationRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UpsertPrepaidConfigurationRequest object to a map representation for JSON marshaling. func (u *UpsertPrepaidConfigurationRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["prepaid_configuration"] = u.PrepaidConfiguration.toMap() - return structMap + structMap := make(map[string]any) + structMap["prepaid_configuration"] = u.PrepaidConfiguration.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UpsertPrepaidConfigurationRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for UpsertPrepaidConfigurationRequest. // It customizes the JSON unmarshaling process for UpsertPrepaidConfigurationRequest objects. func (u *UpsertPrepaidConfigurationRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - PrepaidConfiguration UpsertPrepaidConfiguration `json:"prepaid_configuration"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.PrepaidConfiguration = temp.PrepaidConfiguration - return nil + var temp upsertPrepaidConfigurationRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.PrepaidConfiguration = *temp.PrepaidConfiguration + return nil +} + +// TODO +type upsertPrepaidConfigurationRequest struct { + PrepaidConfiguration *UpsertPrepaidConfiguration `json:"prepaid_configuration"` +} + +func (u *upsertPrepaidConfigurationRequest) validate() error { + var errs []string + if u.PrepaidConfiguration == nil { + errs = append(errs, "required field `prepaid_configuration` is missing for type `Upsert Prepaid Configuration Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/usage.go b/models/usage.go index 73a2fef3..9c889a40 100644 --- a/models/usage.go +++ b/models/usage.go @@ -1,98 +1,100 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Usage represents a Usage struct. type Usage struct { - Id *int64 `json:"id,omitempty"` - Memo *string `json:"memo,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - Quantity *interface{} `json:"quantity,omitempty"` - OverageQuantity *int `json:"overage_quantity,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - ComponentHandle *string `json:"component_handle,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` + Id *int64 `json:"id,omitempty"` + Memo *string `json:"memo,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + Quantity *UsageQuantity `json:"quantity,omitempty"` + OverageQuantity *int `json:"overage_quantity,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + ComponentHandle *string `json:"component_handle,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Usage. +// MarshalJSON implements the json.Marshaler interface for Usage. // It customizes the JSON marshaling process for Usage objects. func (u *Usage) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the Usage object to a map representation for JSON marshaling. func (u *Usage) toMap() map[string]any { - structMap := make(map[string]any) - if u.Id != nil { - structMap["id"] = u.Id - } - if u.Memo != nil { - structMap["memo"] = u.Memo - } - if u.CreatedAt != nil { - structMap["created_at"] = u.CreatedAt.Format(time.RFC3339) - } - if u.PricePointId != nil { - structMap["price_point_id"] = u.PricePointId - } - if u.Quantity != nil { - structMap["quantity"] = u.Quantity - } - if u.OverageQuantity != nil { - structMap["overage_quantity"] = u.OverageQuantity - } - if u.ComponentId != nil { - structMap["component_id"] = u.ComponentId - } - if u.ComponentHandle != nil { - structMap["component_handle"] = u.ComponentHandle - } - if u.SubscriptionId != nil { - structMap["subscription_id"] = u.SubscriptionId - } - return structMap + structMap := make(map[string]any) + if u.Id != nil { + structMap["id"] = u.Id + } + if u.Memo != nil { + structMap["memo"] = u.Memo + } + if u.CreatedAt != nil { + structMap["created_at"] = u.CreatedAt.Format(time.RFC3339) + } + if u.PricePointId != nil { + structMap["price_point_id"] = u.PricePointId + } + if u.Quantity != nil { + structMap["quantity"] = u.Quantity.toMap() + } + if u.OverageQuantity != nil { + structMap["overage_quantity"] = u.OverageQuantity + } + if u.ComponentId != nil { + structMap["component_id"] = u.ComponentId + } + if u.ComponentHandle != nil { + structMap["component_handle"] = u.ComponentHandle + } + if u.SubscriptionId != nil { + structMap["subscription_id"] = u.SubscriptionId + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Usage. +// UnmarshalJSON implements the json.Unmarshaler interface for Usage. // It customizes the JSON unmarshaling process for Usage objects. func (u *Usage) UnmarshalJSON(input []byte) error { - temp := &struct { - Id *int64 `json:"id,omitempty"` - Memo *string `json:"memo,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - PricePointId *int `json:"price_point_id,omitempty"` - Quantity *interface{} `json:"quantity,omitempty"` - OverageQuantity *int `json:"overage_quantity,omitempty"` - ComponentId *int `json:"component_id,omitempty"` - ComponentHandle *string `json:"component_handle,omitempty"` - SubscriptionId *int `json:"subscription_id,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Id = temp.Id - u.Memo = temp.Memo - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - u.CreatedAt = &CreatedAtVal - } - u.PricePointId = temp.PricePointId - u.Quantity = temp.Quantity - u.OverageQuantity = temp.OverageQuantity - u.ComponentId = temp.ComponentId - u.ComponentHandle = temp.ComponentHandle - u.SubscriptionId = temp.SubscriptionId - return nil + var temp usage + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + u.Id = temp.Id + u.Memo = temp.Memo + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + u.CreatedAt = &CreatedAtVal + } + u.PricePointId = temp.PricePointId + u.Quantity = temp.Quantity + u.OverageQuantity = temp.OverageQuantity + u.ComponentId = temp.ComponentId + u.ComponentHandle = temp.ComponentHandle + u.SubscriptionId = temp.SubscriptionId + return nil +} + +// TODO +type usage struct { + Id *int64 `json:"id,omitempty"` + Memo *string `json:"memo,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + PricePointId *int `json:"price_point_id,omitempty"` + Quantity *UsageQuantity `json:"quantity,omitempty"` + OverageQuantity *int `json:"overage_quantity,omitempty"` + ComponentId *int `json:"component_id,omitempty"` + ComponentHandle *string `json:"component_handle,omitempty"` + SubscriptionId *int `json:"subscription_id,omitempty"` } diff --git a/models/usage_quantity.go b/models/usage_quantity.go new file mode 100644 index 00000000..a0cc745d --- /dev/null +++ b/models/usage_quantity.go @@ -0,0 +1,94 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// UsageQuantity represents a UsageQuantity struct. +// This is a container for one-of cases. +type UsageQuantity struct { + value any + isNumber bool + isString bool +} + +// String converts the UsageQuantity object to a string representation. +func (u UsageQuantity) String() string { + if bytes, err := json.Marshal(u.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for UsageQuantity. +// It customizes the JSON marshaling process for UsageQuantity objects. +func (u *UsageQuantity) MarshalJSON() ( + []byte, + error) { + if u.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.UsageQuantityContainer.From*` functions to initialize the UsageQuantity object.") + } + return json.Marshal(u.toMap()) +} + +// toMap converts the UsageQuantity object to a map representation for JSON marshaling. +func (u *UsageQuantity) toMap() any { + switch obj := u.value.(type) { + case *int: + return *obj + case *string: + return *obj + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for UsageQuantity. +// It customizes the JSON unmarshaling process for UsageQuantity objects. +func (u *UsageQuantity) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(new(int), false, &u.isNumber), + NewTypeHolder(new(string), false, &u.isString), + ) + + u.value = result + return err +} + +func (u *UsageQuantity) AsNumber() ( + *int, + bool) { + if !u.isNumber { + return nil, false + } + return u.value.(*int), true +} + +func (u *UsageQuantity) AsString() ( + *string, + bool) { + if !u.isString { + return nil, false + } + return u.value.(*string), true +} + +// internalUsageQuantity represents a usageQuantity struct. +// This is a container for one-of cases. +type internalUsageQuantity struct{} + +var UsageQuantityContainer internalUsageQuantity + +func (u *internalUsageQuantity) FromNumber(val int) UsageQuantity { + return UsageQuantity{value: &val} +} + +func (u *internalUsageQuantity) FromString(val string) UsageQuantity { + return UsageQuantity{value: &val} +} diff --git a/models/usage_response.go b/models/usage_response.go index 2405f3eb..2efbaa11 100644 --- a/models/usage_response.go +++ b/models/usage_response.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // UsageResponse represents a UsageResponse struct. type UsageResponse struct { - Usage Usage `json:"usage"` + Usage Usage `json:"usage"` } -// MarshalJSON implements the json.Marshaler interface for UsageResponse. +// MarshalJSON implements the json.Marshaler interface for UsageResponse. // It customizes the JSON marshaling process for UsageResponse objects. func (u *UsageResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(u.toMap()) + []byte, + error) { + return json.Marshal(u.toMap()) } // toMap converts the UsageResponse object to a map representation for JSON marshaling. func (u *UsageResponse) toMap() map[string]any { - structMap := make(map[string]any) - structMap["usage"] = u.Usage.toMap() - return structMap + structMap := make(map[string]any) + structMap["usage"] = u.Usage.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for UsageResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for UsageResponse. // It customizes the JSON unmarshaling process for UsageResponse objects. func (u *UsageResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Usage Usage `json:"usage"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - u.Usage = temp.Usage - return nil + var temp usageResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + u.Usage = *temp.Usage + return nil +} + +// TODO +type usageResponse struct { + Usage *Usage `json:"usage"` +} + +func (u *usageResponse) validate() error { + var errs []string + if u.Usage == nil { + errs = append(errs, "required field `usage` is missing for type `Usage Response`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/utilities.go b/models/utilities.go index 67e83797..c648807c 100644 --- a/models/utilities.go +++ b/models/utilities.go @@ -1,90 +1,115 @@ -/* -Package advancedbilling - -This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). */ package models import ( - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/types" - "github.com/apimatic/go-core-runtime/utilities" - "net/http" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/types" + "github.com/apimatic/go-core-runtime/utilities" + "net/http" ) func ToPointer[T any](value T) *T { - return &value + return &value } -// FileWrapper is a struct that represents a file along with its metadata such as the +// FileWrapper is a struct that represents a file along with its metadata such as the // file content, file name, and file headers. type FileWrapper = https.FileWrapper -// GetFile retrieves a file from the given fileUrl and returns it as a FileWrapper. +// GetFile retrieves a file from the given fileUrl and returns it as a FileWrapper. // It makes an HTTP GET request to the fileUrl to fetch the file's content and metadata. -var GetFile = https.GetFile +var GetFile = https.GetFile -// Optional is a generic struct that allows any type to be used as optional and nullable. +// Optional is a generic struct that allows any type to be used as optional and nullable. // Optional.set is true when Optional.value is to be used. type Optional[T any] struct { - types.Optional[T] + types.Optional[T] } // NewOptional creates and returns an Optional instance with the given value set. func NewOptional[T any](value *T) Optional[T] { - return Optional[T]{ - Optional: types.NewOptional(value), - } + return Optional[T]{ + Optional: types.NewOptional(value), + } +} + +// EmptyOptional creates and returns an Optional instance with empty value. +func EmptyOptional[T any]() Optional[T] { + return Optional[T]{ + Optional: types.EmptyOptional[T](), + } } // Value returns the value stored in the Optional. It returns nil if no value is set. func (o *Optional[T]) Value() *T { - return o.Optional.Value() + return o.Optional.Value() } // SetValue sets the value of the Optional. func (o *Optional[T]) SetValue(value *T) { - o.Optional.SetValue(value) + o.Optional.SetValue(value) } // IsValueSet returns true if a value is set in the Optional, false otherwise. func (o *Optional[T]) IsValueSet() bool { - return o.Optional.IsValueSet() + return o.Optional.IsValueSet() } // ShouldSetValue sets whether the value should be used or not. func (o *Optional[T]) ShouldSetValue(set bool) { - o.Optional.ShouldSetValue(set) + o.Optional.ShouldSetValue(set) } -// ApiResponse is a generic struct that represents an API response containing data and the HTTP response. -// The `Data` field holds the data of any type `T` returned by the API. +// ApiResponse is a generic struct that represents an API response containing data and the HTTP response. +// The `Data` field holds the data of any type `T` returned by the API. // The `Response` field contains the underlying HTTP response associated with the API call. type ApiResponse[T any] struct { - https.ApiResponse[T] + https.ApiResponse[T] } -// NewApiResponse creates a new instance of ApiResponse. +// NewApiResponse creates a new instance of ApiResponse. // It takes the `data` of type `T` and the `response` as parameters, and returns an ApiResponse[T] struct. func NewApiResponse[T any]( - data T, - response *http.Response) ApiResponse[T] { - return ApiResponse[T]{ - ApiResponse: https.NewApiResponse(data, response), - } + data T, + response *http.Response) ApiResponse[T] { + return ApiResponse[T]{ + ApiResponse: https.NewApiResponse(data, response), + } } // DEFAULT_DATE is a utility. -var DEFAULT_DATE = utilities.DEFAULT_DATE +var DEFAULT_DATE = utilities.DEFAULT_DATE // TimeToStringMap is a utility. -var TimeToStringMap = utilities.TimeToStringMap +var TimeToStringMap = utilities.TimeToStringMap // TimeToStringSlice is a utility. -var TimeToStringSlice = utilities.TimeToStringSlice +var TimeToStringSlice = utilities.TimeToStringSlice // ToTimeSlice is a utility. -var ToTimeSlice = utilities.ToTimeSlice +var ToTimeSlice = utilities.ToTimeSlice // ToTimeMap is a utility. -var ToTimeMap = utilities.ToTimeMap +var ToTimeMap = utilities.ToTimeMap + +// NewTypeHolder is a utility. +var NewTypeHolder = utilities.NewTypeHolder + +// NewTypeHolderDiscriminator is a utility. +var NewTypeHolderDiscriminator = utilities.NewTypeHolderDiscriminator + +// UnmarshallOneOf is a utility. +var UnmarshallOneOf = utilities.UnmarshallOneOf + +// UnmarshallOneOfWithDiscriminator is a utility. +var UnmarshallOneOfWithDiscriminator = utilities.UnmarshallOneOfWithDiscriminator + +// UnmarshallAnyOf is a utility. +var UnmarshallAnyOf = utilities.UnmarshallAnyOf + +// UnmarshallAnyOfWithDiscriminator is a utility. +var UnmarshallAnyOfWithDiscriminator = utilities.UnmarshallAnyOfWithDiscriminator diff --git a/models/void_invoice.go b/models/void_invoice.go index e307a6b4..04ce757e 100644 --- a/models/void_invoice.go +++ b/models/void_invoice.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // VoidInvoice represents a VoidInvoice struct. type VoidInvoice struct { - Reason string `json:"reason"` + Reason string `json:"reason"` } -// MarshalJSON implements the json.Marshaler interface for VoidInvoice. +// MarshalJSON implements the json.Marshaler interface for VoidInvoice. // It customizes the JSON marshaling process for VoidInvoice objects. func (v *VoidInvoice) MarshalJSON() ( - []byte, - error) { - return json.Marshal(v.toMap()) + []byte, + error) { + return json.Marshal(v.toMap()) } // toMap converts the VoidInvoice object to a map representation for JSON marshaling. func (v *VoidInvoice) toMap() map[string]any { - structMap := make(map[string]any) - structMap["reason"] = v.Reason - return structMap + structMap := make(map[string]any) + structMap["reason"] = v.Reason + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for VoidInvoice. +// UnmarshalJSON implements the json.Unmarshaler interface for VoidInvoice. // It customizes the JSON unmarshaling process for VoidInvoice objects. func (v *VoidInvoice) UnmarshalJSON(input []byte) error { - temp := &struct { - Reason string `json:"reason"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - v.Reason = temp.Reason - return nil + var temp voidInvoice + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + v.Reason = *temp.Reason + return nil +} + +// TODO +type voidInvoice struct { + Reason *string `json:"reason"` +} + +func (v *voidInvoice) validate() error { + var errs []string + if v.Reason == nil { + errs = append(errs, "required field `reason` is missing for type `Void Invoice`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/void_invoice_event_data.go b/models/void_invoice_event_data.go new file mode 100644 index 00000000..efe540ab --- /dev/null +++ b/models/void_invoice_event_data.go @@ -0,0 +1,113 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// VoidInvoiceEventData represents a VoidInvoiceEventData struct. +// Example schema for an `void_invoice` event +type VoidInvoiceEventData struct { + CreditNoteAttributes *VoidInvoiceEventDataCreditNoteAttributes `json:"credit_note_attributes"` + // The memo provided during invoice voiding. + Memo *string `json:"memo"` + // The amount of the void. + AppliedAmount *string `json:"applied_amount"` + // The time the refund was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" + TransactionTime *time.Time `json:"transaction_time"` + // If true, the invoice is an advance invoice. + IsAdvanceInvoice bool `json:"is_advance_invoice"` + // The reason for the void. + Reason string `json:"reason"` +} + +// MarshalJSON implements the json.Marshaler interface for VoidInvoiceEventData. +// It customizes the JSON marshaling process for VoidInvoiceEventData objects. +func (v *VoidInvoiceEventData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(v.toMap()) +} + +// toMap converts the VoidInvoiceEventData object to a map representation for JSON marshaling. +func (v *VoidInvoiceEventData) toMap() map[string]any { + structMap := make(map[string]any) + if v.CreditNoteAttributes != nil { + structMap["credit_note_attributes"] = v.CreditNoteAttributes.toMap() + } else { + structMap["credit_note_attributes"] = nil + } + if v.Memo != nil { + structMap["memo"] = v.Memo + } else { + structMap["memo"] = nil + } + if v.AppliedAmount != nil { + structMap["applied_amount"] = v.AppliedAmount + } else { + structMap["applied_amount"] = nil + } + if v.TransactionTime != nil { + structMap["transaction_time"] = v.TransactionTime.Format(time.RFC3339) + } else { + structMap["transaction_time"] = nil + } + structMap["is_advance_invoice"] = v.IsAdvanceInvoice + structMap["reason"] = v.Reason + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for VoidInvoiceEventData. +// It customizes the JSON unmarshaling process for VoidInvoiceEventData objects. +func (v *VoidInvoiceEventData) UnmarshalJSON(input []byte) error { + var temp voidInvoiceEventData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + v.CreditNoteAttributes = temp.CreditNoteAttributes + v.Memo = temp.Memo + v.AppliedAmount = temp.AppliedAmount + if temp.TransactionTime != nil { + TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) + if err != nil { + log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) + } + v.TransactionTime = &TransactionTimeVal + } + v.IsAdvanceInvoice = *temp.IsAdvanceInvoice + v.Reason = *temp.Reason + return nil +} + +// TODO +type voidInvoiceEventData struct { + CreditNoteAttributes *VoidInvoiceEventDataCreditNoteAttributes `json:"credit_note_attributes"` + Memo *string `json:"memo"` + AppliedAmount *string `json:"applied_amount"` + TransactionTime *string `json:"transaction_time"` + IsAdvanceInvoice *bool `json:"is_advance_invoice"` + Reason *string `json:"reason"` +} + +func (v *voidInvoiceEventData) validate() error { + var errs []string + if v.IsAdvanceInvoice == nil { + errs = append(errs, "required field `is_advance_invoice` is missing for type `Void Invoice Event Data`") + } + if v.Reason == nil { + errs = append(errs, "required field `reason` is missing for type `Void Invoice Event Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/void_invoice_event_data_credit_note_attributes.go b/models/void_invoice_event_data_credit_note_attributes.go new file mode 100644 index 00000000..0ca061b4 --- /dev/null +++ b/models/void_invoice_event_data_credit_note_attributes.go @@ -0,0 +1,77 @@ +/* +Package advancedbilling + +This file was automatically generated for Maxio by APIMATIC v3.0 ( https://www.apimatic.io ). +*/ +package models + +import ( + "encoding/json" + "errors" + "strings" +) + +// VoidInvoiceEventDataCreditNoteAttributes represents a VoidInvoiceEventDataCreditNoteAttributes struct. +// This is a container for one-of cases. +type VoidInvoiceEventDataCreditNoteAttributes struct { + value any + isCreditNote bool +} + +// String converts the VoidInvoiceEventDataCreditNoteAttributes object to a string representation. +func (v VoidInvoiceEventDataCreditNoteAttributes) String() string { + if bytes, err := json.Marshal(v.value); err == nil { + return strings.Trim(string(bytes), "\"") + } + return "" +} + +// MarshalJSON implements the json.Marshaler interface for VoidInvoiceEventDataCreditNoteAttributes. +// It customizes the JSON marshaling process for VoidInvoiceEventDataCreditNoteAttributes objects. +func (v *VoidInvoiceEventDataCreditNoteAttributes) MarshalJSON() ( + []byte, + error) { + if v.value == nil { + return nil, errors.New("No underlying type is set. Please use any of the `models.VoidInvoiceEventDataCreditNoteAttributesContainer.From*` functions to initialize the VoidInvoiceEventDataCreditNoteAttributes object.") + } + return json.Marshal(v.toMap()) +} + +// toMap converts the VoidInvoiceEventDataCreditNoteAttributes object to a map representation for JSON marshaling. +func (v *VoidInvoiceEventDataCreditNoteAttributes) toMap() any { + switch obj := v.value.(type) { + case *CreditNote: + return obj.toMap() + } + return nil +} + +// UnmarshalJSON implements the json.Unmarshaler interface for VoidInvoiceEventDataCreditNoteAttributes. +// It customizes the JSON unmarshaling process for VoidInvoiceEventDataCreditNoteAttributes objects. +func (v *VoidInvoiceEventDataCreditNoteAttributes) UnmarshalJSON(input []byte) error { + result, err := UnmarshallOneOf(input, + NewTypeHolder(&CreditNote{}, false, &v.isCreditNote), + ) + + v.value = result + return err +} + +func (v *VoidInvoiceEventDataCreditNoteAttributes) AsCreditNote() ( + *CreditNote, + bool) { + if !v.isCreditNote { + return nil, false + } + return v.value.(*CreditNote), true +} + +// internalVoidInvoiceEventDataCreditNoteAttributes represents a voidInvoiceEventDataCreditNoteAttributes struct. +// This is a container for one-of cases. +type internalVoidInvoiceEventDataCreditNoteAttributes struct{} + +var VoidInvoiceEventDataCreditNoteAttributesContainer internalVoidInvoiceEventDataCreditNoteAttributes + +func (v *internalVoidInvoiceEventDataCreditNoteAttributes) FromCreditNote(val CreditNote) VoidInvoiceEventDataCreditNoteAttributes { + return VoidInvoiceEventDataCreditNoteAttributes{value: &val} +} diff --git a/models/void_invoice_request.go b/models/void_invoice_request.go index 57f6b132..6e8a1064 100644 --- a/models/void_invoice_request.go +++ b/models/void_invoice_request.go @@ -1,40 +1,60 @@ package models import ( - "encoding/json" + "encoding/json" + "errors" + "strings" ) // VoidInvoiceRequest represents a VoidInvoiceRequest struct. type VoidInvoiceRequest struct { - Void VoidInvoice `json:"void"` + Void VoidInvoice `json:"void"` } -// MarshalJSON implements the json.Marshaler interface for VoidInvoiceRequest. +// MarshalJSON implements the json.Marshaler interface for VoidInvoiceRequest. // It customizes the JSON marshaling process for VoidInvoiceRequest objects. func (v *VoidInvoiceRequest) MarshalJSON() ( - []byte, - error) { - return json.Marshal(v.toMap()) + []byte, + error) { + return json.Marshal(v.toMap()) } // toMap converts the VoidInvoiceRequest object to a map representation for JSON marshaling. func (v *VoidInvoiceRequest) toMap() map[string]any { - structMap := make(map[string]any) - structMap["void"] = v.Void.toMap() - return structMap + structMap := make(map[string]any) + structMap["void"] = v.Void.toMap() + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for VoidInvoiceRequest. +// UnmarshalJSON implements the json.Unmarshaler interface for VoidInvoiceRequest. // It customizes the JSON unmarshaling process for VoidInvoiceRequest objects. func (v *VoidInvoiceRequest) UnmarshalJSON(input []byte) error { - temp := &struct { - Void VoidInvoice `json:"void"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - v.Void = temp.Void - return nil + var temp voidInvoiceRequest + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + v.Void = *temp.Void + return nil +} + +// TODO +type voidInvoiceRequest struct { + Void *VoidInvoice `json:"void"` +} + +func (v *voidInvoiceRequest) validate() error { + var errs []string + if v.Void == nil { + errs = append(errs, "required field `void` is missing for type `Void Invoice Request`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) } diff --git a/models/void_remainder_event_data.go b/models/void_remainder_event_data.go new file mode 100644 index 00000000..5c2807b9 --- /dev/null +++ b/models/void_remainder_event_data.go @@ -0,0 +1,91 @@ +package models + +import ( + "encoding/json" + "errors" + "log" + "strings" + "time" +) + +// VoidRemainderEventData represents a VoidRemainderEventData struct. +// Example schema for an `void_remainder` event +type VoidRemainderEventData struct { + CreditNoteAttributes CreditNote `json:"credit_note_attributes"` + // The memo provided during invoice remainder voiding. + Memo string `json:"memo"` + // The amount of the void. + AppliedAmount string `json:"applied_amount"` + // The time the refund was applied, in ISO 8601 format, i.e. "2019-06-07T17:20:06Z" + TransactionTime time.Time `json:"transaction_time"` +} + +// MarshalJSON implements the json.Marshaler interface for VoidRemainderEventData. +// It customizes the JSON marshaling process for VoidRemainderEventData objects. +func (v *VoidRemainderEventData) MarshalJSON() ( + []byte, + error) { + return json.Marshal(v.toMap()) +} + +// toMap converts the VoidRemainderEventData object to a map representation for JSON marshaling. +func (v *VoidRemainderEventData) toMap() map[string]any { + structMap := make(map[string]any) + structMap["credit_note_attributes"] = v.CreditNoteAttributes.toMap() + structMap["memo"] = v.Memo + structMap["applied_amount"] = v.AppliedAmount + structMap["transaction_time"] = v.TransactionTime.Format(time.RFC3339) + return structMap +} + +// UnmarshalJSON implements the json.Unmarshaler interface for VoidRemainderEventData. +// It customizes the JSON unmarshaling process for VoidRemainderEventData objects. +func (v *VoidRemainderEventData) UnmarshalJSON(input []byte) error { + var temp voidRemainderEventData + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + err = temp.validate() + if err != nil { + return err + } + + v.CreditNoteAttributes = *temp.CreditNoteAttributes + v.Memo = *temp.Memo + v.AppliedAmount = *temp.AppliedAmount + TransactionTimeVal, err := time.Parse(time.RFC3339, *temp.TransactionTime) + if err != nil { + log.Fatalf("Cannot Parse transaction_time as % s format.", time.RFC3339) + } + v.TransactionTime = TransactionTimeVal + return nil +} + +// TODO +type voidRemainderEventData struct { + CreditNoteAttributes *CreditNote `json:"credit_note_attributes"` + Memo *string `json:"memo"` + AppliedAmount *string `json:"applied_amount"` + TransactionTime *string `json:"transaction_time"` +} + +func (v *voidRemainderEventData) validate() error { + var errs []string + if v.CreditNoteAttributes == nil { + errs = append(errs, "required field `credit_note_attributes` is missing for type `Void Remainder Event Data`") + } + if v.Memo == nil { + errs = append(errs, "required field `memo` is missing for type `Void Remainder Event Data`") + } + if v.AppliedAmount == nil { + errs = append(errs, "required field `applied_amount` is missing for type `Void Remainder Event Data`") + } + if v.TransactionTime == nil { + errs = append(errs, "required field `transaction_time` is missing for type `Void Remainder Event Data`") + } + if len(errs) == 0 { + return nil + } + return errors.New(strings.Join(errs, "\n")) +} diff --git a/models/webhook.go b/models/webhook.go index c5f5201a..28c4d44c 100644 --- a/models/webhook.go +++ b/models/webhook.go @@ -1,152 +1,158 @@ package models import ( - "encoding/json" - "log" - "time" + "encoding/json" + "log" + "time" ) // Webhook represents a Webhook struct. type Webhook struct { - // A string describing which event type produced the given webhook - Event *string `json:"event,omitempty"` - // The unique identifier for the webhooks (unique across all of Chargify). This is not changed on a retry/replay of the same webhook, so it may be used to avoid duplicate action for the same event. - Id *int64 `json:"id,omitempty"` - // Timestamp indicating when the webhook was created - CreatedAt *time.Time `json:"created_at,omitempty"` - // Text describing the status code and/or error from the last failed attempt to send the Webhook. When a webhook is retried and accepted, this field will be cleared. - LastError *string `json:"last_error,omitempty"` - // Timestamp indicating when the last non-acceptance occurred. If a webhook is later resent and accepted, this field will be cleared. - LastErrorAt *time.Time `json:"last_error_at,omitempty"` - // Timestamp indicating when the webhook was accepted by the merchant endpoint. When a webhook is explicitly replayed by the merchant, this value will be cleared until it is accepted again. - AcceptedAt Optional[time.Time] `json:"accepted_at"` - // Timestamp indicating when the most recent attempt was made to send the webhook - LastSentAt *time.Time `json:"last_sent_at,omitempty"` - // The url that the endpoint was last sent to. - LastSentUrl *string `json:"last_sent_url,omitempty"` - // A boolean flag describing whether the webhook was accepted by the webhook endpoint for the most recent attempt. (Acceptance is defined by receiving a “200 OK” HTTP response within a reasonable timeframe, i.e. 15 seconds) - Successful *bool `json:"successful,omitempty"` - // The data sent within the webhook post - Body *string `json:"body,omitempty"` - // The calculated webhook signature - Signature *string `json:"signature,omitempty"` - // The calculated HMAC-SHA-256 webhook signature - SignatureHmacSha256 *string `json:"signature_hmac_sha_256,omitempty"` + // A string describing which event type produced the given webhook + Event *string `json:"event,omitempty"` + // The unique identifier for the webhooks (unique across all of Chargify). This is not changed on a retry/replay of the same webhook, so it may be used to avoid duplicate action for the same event. + Id *int64 `json:"id,omitempty"` + // Timestamp indicating when the webhook was created + CreatedAt *time.Time `json:"created_at,omitempty"` + // Text describing the status code and/or error from the last failed attempt to send the Webhook. When a webhook is retried and accepted, this field will be cleared. + LastError *string `json:"last_error,omitempty"` + // Timestamp indicating when the last non-acceptance occurred. If a webhook is later resent and accepted, this field will be cleared. + LastErrorAt *time.Time `json:"last_error_at,omitempty"` + // Timestamp indicating when the webhook was accepted by the merchant endpoint. When a webhook is explicitly replayed by the merchant, this value will be cleared until it is accepted again. + AcceptedAt Optional[time.Time] `json:"accepted_at"` + // Timestamp indicating when the most recent attempt was made to send the webhook + LastSentAt *time.Time `json:"last_sent_at,omitempty"` + // The url that the endpoint was last sent to. + LastSentUrl *string `json:"last_sent_url,omitempty"` + // A boolean flag describing whether the webhook was accepted by the webhook endpoint for the most recent attempt. (Acceptance is defined by receiving a “200 OK” HTTP response within a reasonable timeframe, i.e. 15 seconds) + Successful *bool `json:"successful,omitempty"` + // The data sent within the webhook post + Body *string `json:"body,omitempty"` + // The calculated webhook signature + Signature *string `json:"signature,omitempty"` + // The calculated HMAC-SHA-256 webhook signature + SignatureHmacSha256 *string `json:"signature_hmac_sha_256,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for Webhook. +// MarshalJSON implements the json.Marshaler interface for Webhook. // It customizes the JSON marshaling process for Webhook objects. func (w *Webhook) MarshalJSON() ( - []byte, - error) { - return json.Marshal(w.toMap()) + []byte, + error) { + return json.Marshal(w.toMap()) } // toMap converts the Webhook object to a map representation for JSON marshaling. func (w *Webhook) toMap() map[string]any { - structMap := make(map[string]any) - if w.Event != nil { - structMap["event"] = w.Event - } - if w.Id != nil { - structMap["id"] = w.Id - } - if w.CreatedAt != nil { - structMap["created_at"] = w.CreatedAt.Format(time.RFC3339) - } - if w.LastError != nil { - structMap["last_error"] = w.LastError - } - if w.LastErrorAt != nil { - structMap["last_error_at"] = w.LastErrorAt.Format(time.RFC3339) - } - if w.AcceptedAt.IsValueSet() { - var AcceptedAtVal *string = nil - if w.AcceptedAt.Value() != nil { - val := w.AcceptedAt.Value().Format(time.RFC3339) - AcceptedAtVal = &val - } - structMap["accepted_at"] = AcceptedAtVal - } - if w.LastSentAt != nil { - structMap["last_sent_at"] = w.LastSentAt.Format(time.RFC3339) - } - if w.LastSentUrl != nil { - structMap["last_sent_url"] = w.LastSentUrl - } - if w.Successful != nil { - structMap["successful"] = w.Successful - } - if w.Body != nil { - structMap["body"] = w.Body - } - if w.Signature != nil { - structMap["signature"] = w.Signature - } - if w.SignatureHmacSha256 != nil { - structMap["signature_hmac_sha_256"] = w.SignatureHmacSha256 - } - return structMap + structMap := make(map[string]any) + if w.Event != nil { + structMap["event"] = w.Event + } + if w.Id != nil { + structMap["id"] = w.Id + } + if w.CreatedAt != nil { + structMap["created_at"] = w.CreatedAt.Format(time.RFC3339) + } + if w.LastError != nil { + structMap["last_error"] = w.LastError + } + if w.LastErrorAt != nil { + structMap["last_error_at"] = w.LastErrorAt.Format(time.RFC3339) + } + if w.AcceptedAt.IsValueSet() { + var AcceptedAtVal *string = nil + if w.AcceptedAt.Value() != nil { + val := w.AcceptedAt.Value().Format(time.RFC3339) + AcceptedAtVal = &val + } + if w.AcceptedAt.Value() != nil { + structMap["accepted_at"] = AcceptedAtVal + } else { + structMap["accepted_at"] = nil + } + } + if w.LastSentAt != nil { + structMap["last_sent_at"] = w.LastSentAt.Format(time.RFC3339) + } + if w.LastSentUrl != nil { + structMap["last_sent_url"] = w.LastSentUrl + } + if w.Successful != nil { + structMap["successful"] = w.Successful + } + if w.Body != nil { + structMap["body"] = w.Body + } + if w.Signature != nil { + structMap["signature"] = w.Signature + } + if w.SignatureHmacSha256 != nil { + structMap["signature_hmac_sha_256"] = w.SignatureHmacSha256 + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for Webhook. +// UnmarshalJSON implements the json.Unmarshaler interface for Webhook. // It customizes the JSON unmarshaling process for Webhook objects. func (w *Webhook) UnmarshalJSON(input []byte) error { - temp := &struct { - Event *string `json:"event,omitempty"` - Id *int64 `json:"id,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - LastError *string `json:"last_error,omitempty"` - LastErrorAt *string `json:"last_error_at,omitempty"` - AcceptedAt Optional[string] `json:"accepted_at"` - LastSentAt *string `json:"last_sent_at,omitempty"` - LastSentUrl *string `json:"last_sent_url,omitempty"` - Successful *bool `json:"successful,omitempty"` - Body *string `json:"body,omitempty"` - Signature *string `json:"signature,omitempty"` - SignatureHmacSha256 *string `json:"signature_hmac_sha_256,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - w.Event = temp.Event - w.Id = temp.Id - if temp.CreatedAt != nil { - CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) - if err != nil { - log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) - } - w.CreatedAt = &CreatedAtVal - } - w.LastError = temp.LastError - if temp.LastErrorAt != nil { - LastErrorAtVal, err := time.Parse(time.RFC3339, *temp.LastErrorAt) - if err != nil { - log.Fatalf("Cannot Parse last_error_at as % s format.", time.RFC3339) - } - w.LastErrorAt = &LastErrorAtVal - } - w.AcceptedAt.ShouldSetValue(temp.AcceptedAt.IsValueSet()) - if temp.AcceptedAt.Value() != nil { - AcceptedAtVal, err := time.Parse(time.RFC3339, (*temp.AcceptedAt.Value())) - if err != nil { - log.Fatalf("Cannot Parse accepted_at as % s format.", time.RFC3339) - } - w.AcceptedAt.SetValue(&AcceptedAtVal) - } - if temp.LastSentAt != nil { - LastSentAtVal, err := time.Parse(time.RFC3339, *temp.LastSentAt) - if err != nil { - log.Fatalf("Cannot Parse last_sent_at as % s format.", time.RFC3339) - } - w.LastSentAt = &LastSentAtVal - } - w.LastSentUrl = temp.LastSentUrl - w.Successful = temp.Successful - w.Body = temp.Body - w.Signature = temp.Signature - w.SignatureHmacSha256 = temp.SignatureHmacSha256 - return nil + var temp webhook + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + w.Event = temp.Event + w.Id = temp.Id + if temp.CreatedAt != nil { + CreatedAtVal, err := time.Parse(time.RFC3339, *temp.CreatedAt) + if err != nil { + log.Fatalf("Cannot Parse created_at as % s format.", time.RFC3339) + } + w.CreatedAt = &CreatedAtVal + } + w.LastError = temp.LastError + if temp.LastErrorAt != nil { + LastErrorAtVal, err := time.Parse(time.RFC3339, *temp.LastErrorAt) + if err != nil { + log.Fatalf("Cannot Parse last_error_at as % s format.", time.RFC3339) + } + w.LastErrorAt = &LastErrorAtVal + } + w.AcceptedAt.ShouldSetValue(temp.AcceptedAt.IsValueSet()) + if temp.AcceptedAt.Value() != nil { + AcceptedAtVal, err := time.Parse(time.RFC3339, (*temp.AcceptedAt.Value())) + if err != nil { + log.Fatalf("Cannot Parse accepted_at as % s format.", time.RFC3339) + } + w.AcceptedAt.SetValue(&AcceptedAtVal) + } + if temp.LastSentAt != nil { + LastSentAtVal, err := time.Parse(time.RFC3339, *temp.LastSentAt) + if err != nil { + log.Fatalf("Cannot Parse last_sent_at as % s format.", time.RFC3339) + } + w.LastSentAt = &LastSentAtVal + } + w.LastSentUrl = temp.LastSentUrl + w.Successful = temp.Successful + w.Body = temp.Body + w.Signature = temp.Signature + w.SignatureHmacSha256 = temp.SignatureHmacSha256 + return nil +} + +// TODO +type webhook struct { + Event *string `json:"event,omitempty"` + Id *int64 `json:"id,omitempty"` + CreatedAt *string `json:"created_at,omitempty"` + LastError *string `json:"last_error,omitempty"` + LastErrorAt *string `json:"last_error_at,omitempty"` + AcceptedAt Optional[string] `json:"accepted_at"` + LastSentAt *string `json:"last_sent_at,omitempty"` + LastSentUrl *string `json:"last_sent_url,omitempty"` + Successful *bool `json:"successful,omitempty"` + Body *string `json:"body,omitempty"` + Signature *string `json:"signature,omitempty"` + SignatureHmacSha256 *string `json:"signature_hmac_sha_256,omitempty"` } diff --git a/models/webhook_response.go b/models/webhook_response.go index 577d358f..9f5312b2 100644 --- a/models/webhook_response.go +++ b/models/webhook_response.go @@ -1,42 +1,44 @@ package models import ( - "encoding/json" + "encoding/json" ) // WebhookResponse represents a WebhookResponse struct. type WebhookResponse struct { - Webhook *Webhook `json:"webhook,omitempty"` + Webhook *Webhook `json:"webhook,omitempty"` } -// MarshalJSON implements the json.Marshaler interface for WebhookResponse. +// MarshalJSON implements the json.Marshaler interface for WebhookResponse. // It customizes the JSON marshaling process for WebhookResponse objects. func (w *WebhookResponse) MarshalJSON() ( - []byte, - error) { - return json.Marshal(w.toMap()) + []byte, + error) { + return json.Marshal(w.toMap()) } // toMap converts the WebhookResponse object to a map representation for JSON marshaling. func (w *WebhookResponse) toMap() map[string]any { - structMap := make(map[string]any) - if w.Webhook != nil { - structMap["webhook"] = w.Webhook.toMap() - } - return structMap + structMap := make(map[string]any) + if w.Webhook != nil { + structMap["webhook"] = w.Webhook.toMap() + } + return structMap } -// UnmarshalJSON implements the json.Unmarshaler interface for WebhookResponse. +// UnmarshalJSON implements the json.Unmarshaler interface for WebhookResponse. // It customizes the JSON unmarshaling process for WebhookResponse objects. func (w *WebhookResponse) UnmarshalJSON(input []byte) error { - temp := &struct { - Webhook *Webhook `json:"webhook,omitempty"` - }{} - err := json.Unmarshal(input, &temp) - if err != nil { - return err - } - - w.Webhook = temp.Webhook - return nil + var temp webhookResponse + err := json.Unmarshal(input, &temp) + if err != nil { + return err + } + w.Webhook = temp.Webhook + return nil +} + +// TODO +type webhookResponse struct { + Webhook *Webhook `json:"webhook,omitempty"` } diff --git a/offers_controller.go b/offers_controller.go index d86f959e..09b840ab 100644 --- a/offers_controller.go +++ b/offers_controller.go @@ -1,157 +1,167 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" ) // OffersController represents a controller struct. type OffersController struct { - baseController + baseController } -// NewOffersController creates a new instance of OffersController. +// NewOffersController creates a new instance of OffersController. // It takes a baseController as a parameter and returns a pointer to the OffersController. func NewOffersController(baseController baseController) *OffersController { - offersController := OffersController{baseController: baseController} - return &offersController + offersController := OffersController{baseController: baseController} + return &offersController } -// CreateOffer takes context, body as parameters and -// returns an models.ApiResponse with models.OfferResponse data and -// an error if there was an issue with the request or response. -// Create an offer within your Chargify site by sending a POST request. -// ## Documentation -// Offers allow you to package complicated combinations of products, components and coupons into a convenient package which can then be subscribed to just like products. -// Once an offer is defined it can be used as an alternative to the product when creating subscriptions. -// Full documentation on how to use offers in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407753852059). -// ## Using a Product Price Point +// CreateOffer takes context, body as parameters and +// returns an models.ApiResponse with models.OfferResponse data and +// an error if there was an issue with the request or response. +// Create an offer within your Chargify site by sending a POST request. +// ## Documentation +// Offers allow you to package complicated combinations of products, components and coupons into a convenient package which can then be subscribed to just like products. +// Once an offer is defined it can be used as an alternative to the product when creating subscriptions. +// Full documentation on how to use offers in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407753852059). +// ## Using a Product Price Point // You can optionally pass in a `product_price_point_id` that corresponds with the `product_id` and the offer will use that price point. If a `product_price_point_id` is not passed in, the product's default price point will be used. func (o *OffersController) CreateOffer( - ctx context.Context, - body *models.CreateOfferRequest) ( - models.ApiResponse[models.OfferResponse], - error) { - req := o.prepareRequest(ctx, "POST", "/offers.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.OfferResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.OfferResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.CreateOfferRequest) ( + models.ApiResponse[models.OfferResponse], + error) { + req := o.prepareRequest(ctx, "POST", "/offers.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.OfferResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.OfferResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListOffersInput represents the input of the ListOffers endpoint. +type ListOffersInput struct { + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // Include archived products. Use in query: `include_archived=true`. + IncludeArchived *bool } -// ListOffers takes context, page, perPage, includeArchived as parameters and -// returns an models.ApiResponse with models.ListOffersResponse data and -// an error if there was an issue with the request or response. +// ListOffers takes context, page, perPage, includeArchived as parameters and +// returns an models.ApiResponse with models.ListOffersResponse data and +// an error if there was an issue with the request or response. // This endpoint will list offers for a site. func (o *OffersController) ListOffers( - ctx context.Context, - page *int, - perPage *int, - includeArchived *bool) ( - models.ApiResponse[models.ListOffersResponse], - error) { - req := o.prepareRequest(ctx, "GET", "/offers.json") - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if includeArchived != nil { - req.QueryParam("include_archived", *includeArchived) - } - var result models.ListOffersResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListOffersResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListOffersInput) ( + models.ApiResponse[models.ListOffersResponse], + error) { + req := o.prepareRequest(ctx, "GET", "/offers.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.IncludeArchived != nil { + req.QueryParam("include_archived", *input.IncludeArchived) + } + var result models.ListOffersResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListOffersResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadOffer takes context, offerId as parameters and -// returns an models.ApiResponse with models.OfferResponse data and -// an error if there was an issue with the request or response. +// ReadOffer takes context, offerId as parameters and +// returns an models.ApiResponse with models.OfferResponse data and +// an error if there was an issue with the request or response. // This method allows you to list a specific offer's attributes. This is different than list all offers for a site, as it requires an `offer_id`. func (o *OffersController) ReadOffer( - ctx context.Context, - offerId int) ( - models.ApiResponse[models.OfferResponse], - error) { - req := o.prepareRequest(ctx, "GET", fmt.Sprintf("/offers/%v.json", offerId)) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.OfferResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.OfferResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + offerId int) ( + models.ApiResponse[models.OfferResponse], + error) { + req := o.prepareRequest(ctx, "GET", fmt.Sprintf("/offers/%v.json", offerId)) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.OfferResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.OfferResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ArchiveOffer takes context, offerId as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. +// ArchiveOffer takes context, offerId as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. // Archive an existing offer. Please provide an `offer_id` in order to archive the correct item. func (o *OffersController) ArchiveOffer( - ctx context.Context, - offerId int) ( - *http.Response, - error) { - req := o.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/offers/%v/archive.json", offerId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + offerId int) ( + *http.Response, + error) { + req := o.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/offers/%v/archive.json", offerId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// UnarchiveOffer takes context, offerId as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. +// UnarchiveOffer takes context, offerId as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. // Unarchive a previously archived offer. Please provide an `offer_id` in order to un-archive the correct item. func (o *OffersController) UnarchiveOffer( - ctx context.Context, - offerId int) ( - *http.Response, - error) { - req := o.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/offers/%v/unarchive.json", offerId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + offerId int) ( + *http.Response, + error) { + req := o.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/offers/%v/unarchive.json", offerId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } diff --git a/payment_profiles_controller.go b/payment_profiles_controller.go index 71f1c52f..2c253c31 100644 --- a/payment_profiles_controller.go +++ b/payment_profiles_controller.go @@ -1,623 +1,633 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" ) // PaymentProfilesController represents a controller struct. type PaymentProfilesController struct { - baseController + baseController } -// NewPaymentProfilesController creates a new instance of PaymentProfilesController. +// NewPaymentProfilesController creates a new instance of PaymentProfilesController. // It takes a baseController as a parameter and returns a pointer to the PaymentProfilesController. func NewPaymentProfilesController(baseController baseController) *PaymentProfilesController { - paymentProfilesController := PaymentProfilesController{baseController: baseController} - return &paymentProfilesController + paymentProfilesController := PaymentProfilesController{baseController: baseController} + return &paymentProfilesController } -// CreatePaymentProfile takes context, body as parameters and -// returns an models.ApiResponse with models.PaymentProfileResponse data and -// an error if there was an issue with the request or response. -// Use this endpoint to create a payment profile for a customer. -// Payment Profiles house the credit card, ACH (Authorize.Net or Stripe only,) or PayPal (Braintree only,) data for a customer. The payment information is attached to the customer within Chargify, as opposed to the Subscription itself. -// You must include a customer_id so that Chargify will attach it to the customer entry. If no customer_id is included the API will return a 404. -// ## Create a Payment Profile for ACH usage -// If you would like to create a payment method that is a Bank Account applicable for ACH payments use the following: -// ```json -// { -// "payment_profile": { -// "customer_id": [Valid-Customer-ID], -// "bank_name": "Best Bank", -// "bank_routing_number": "021000089", -// "bank_account_number": "111111111111", -// "bank_account_type": "checking", -// "bank_account_holder_type": "business", -// "payment_type": "bank_account" -// } -// } -// ``` -// ## Taxable Subscriptions -// If your subscriber pays taxes on their purchased product, and you are attempting to create or update the `payment_profile`, complete address information is required. For information on required address formatting to allow your subscriber to be taxed, please see our documentation [here](https://developers.chargify.com/docs/developer-docs/d2e9e34db740e-signups#taxes) -// ## Payment Profile Documentation -// Full documentation on how Payment Profiles operate within Chargify can be located under the following links: -// + [Subscriber Payment Details](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405212558349-Customers-Reference#customers-reference-0-0) -// + [Self Service Pages](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404759627021) (Allows credit card updates by Subscriber) -// + [Public Signup Pages payment settings](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405267754381-Individual-Page-Settings#credit-card-settings) -// ## Create a Payment Profile with a Chargify.js token -// ```json -// { -// "payment_profile": { -// "customer_id": 1036, -// "chargify_token": "tok_w68qcpnftyv53jk33jv6wk3w" -// } -// } -// ``` -// ## Active Payment Methods -// Creating a new payment profile for a Customer via the API will not make that Payment Profile current for any of the Customer’s Subscriptions. In order to utilize the payment profile as the default, it must be set as the default payment profile for the subscription or subscription group. -// ## Requirements -// Either the full_number, expiration_month, and expiration_year or if you have an existing vault_token from your gateway, that vault_token and the current_vault are required. -// Passing in the vault_token and current_vault are only allowed when creating a new payment profile. -// ### Taxable Subscriptions -// If your subscriber pays taxes on their purchased product, and you are attempting to create or update the `payment_profile`, complete address information is required. For information on required address formatting to allow your subscriber to be taxed, please see our documentation [here](https://developers.chargify.com/docs/developer-docs/d2e9e34db740e-signups#taxes) -// ## BraintreeBlue -// Some merchants use Braintree JavaScript libraries directly and then pass `payment_method_nonce` and/or `paypal_email` to create a payment profile. This implementation is deprecated and does not handle 3D Secure. Instead, we have provided [Chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview) which is continuously improved and supports Credit Cards (along with 3D Secure), PayPal and ApplePay payment types. -// ## GoCardless -// For more information on GoCardless, please view the following resources: -// + [Full documentation on GoCardless](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404501889677) -// + [Using Chargify.js with GoCardless - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-direct-debit-gocardless-gateway) -// + [Using Chargify.js with GoCardless - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-direct-debit-gocardless-gateway) -// ### GoCardless with Local Bank Details -// Following examples create customer, bank account and mandate in GoCardless: -// ```json -// { -// "payment_profile": { -// "customer_id": "Valid-Customer-ID", -// "bank_name": "Royal Bank of France", -// "bank_account_number": "0000000", -// "bank_routing_number": "0003", -// "bank_branch_code": "00006", -// "payment_type": "bank_account", -// "billing_address": "20 Place de la Gare", -// "billing_city": "Colombes", -// "billing_state": "Île-de-France", -// "billing_zip": "92700", -// "billing_country": "FR" -// } -// } -// ``` -// ### GoCardless with IBAN -// ```json -// { -// "payment_profile": { -// "customer_id": "24907598", -// "bank_name": "French Bank", -// "bank_iban": "FR1420041010050500013M02606", -// "payment_type": "bank_account", -// "billing_address": "20 Place de la Gare", -// "billing_city": "Colombes", -// "billing_state": "Île-de-France", -// "billing_zip": "92700", -// "billing_country": "FR" -// } -// } -// ``` -// ### Importing GoCardless -// If the customer, bank account, and mandate already exist in GoCardless, a payment profile can be created by using the IDs. In order to create masked versions of `bank_account_number` and `bank_routing_number` that are used to display within Chargify Admin UI, you can pass the last four digits for this fields which then will be saved in this form `XXXX[four-provided-digits]`. -// ```json -// { -// "payment_profile": { -// "customer_id": "24907598", -// "customer_vault_token": [Existing GoCardless Customer ID] -// "vault_token": [Existing GoCardless Mandate ID], -// "current_vault": "gocardless", -// "bank_name": "French Bank", -// "bank_account_number": [Last Four Of The Existing Account Number or IBAN if applicable], -// "bank_routing_number": [Last Four Of The Existing Routing Number], -// "payment_type": "bank_account", -// "billing_address": "20 Place de la Gare", -// "billing_city": "Colombes", -// "billing_state": "Île-de-France", -// "billing_zip": "92700", -// "billing_country": "FR" -// } -// } -// ``` -// ## SEPA Direct Debit -// For more information on Stripe SEPA Direct Debit, please view the following resources: -// + [Full documentation on Stripe SEPA Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) -// + [Using Chargify.js with Stripe Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) -// + [Using Chargify.js with Stripe Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-sepa-direct-debit-stripe-gateway) -// ### Stripe SEPA Direct Debit Payment Profiles -// The following example creates a customer, bank account and mandate in Stripe: -// ```json -// { -// "payment_profile": { -// "customer_id": "24907598", -// "bank_name": "Deutsche bank", -// "bank_iban": "DE89370400440532013000", -// "payment_type": "bank_account", -// "billing_address": "Test", -// "billing_city": "Berlin", -// "billing_state": "Brandenburg", -// "billing_zip": "12345", -// "billing_country": "DE" -// } -// } -// ``` -// ## Stripe BECS Direct Debit -// For more information on Stripe BECS Direct Debit, please view the following resources: -// + [Full documentation on Stripe BECS Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) -// + [Using Chargify.js with Stripe BECS Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) -// + [Using Chargify.js with Stripe BECS Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-sepa-direct-debit-stripe-gateway) -// ### Stripe BECS Direct Debit Payment Profiles -// The following example creates a customer, bank account and mandate in Stripe: -// ```json -// { -// "payment_profile": { -// "customer_id": "24907598", -// "bank_name": "Australian bank", -// "bank_branch_code": "000000", -// "bank_account_number": "000123456" -// "payment_type": "bank_account", -// "billing_address": "Test", -// "billing_city": "Stony Rise", -// "billing_state": "Tasmania", -// "billing_zip": "12345", -// "billing_country": "AU" -// } -// } -// ``` -// ## 3D Secure - Checkout -// It may happen that a payment needs 3D Secure Authentication when the payment profile is created; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: -// ```json -// { -// "jsonapi": { -// "version": "1.0" -// }, -// "errors": [ -// { -// "title": "This card requires 3DSecure verification.", -// "detail": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://checkout-test.chargifypay.test/3d-secure/checkout/pay_uerzhsxd5uhkbodx5jhvkg6yeu?one_time_token_id=93&callback_url=http://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after credit card is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", -// "links": { -// "action_link": "https://checkout-test.chargifypay.test/3d-secure/checkout/pay_uerzhsxd5uhkbodx5jhvkg6yeu?one_time_token_id=93" -// } -// } -// ] -// } -// ``` -// To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. -// Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: -// - whether the authentication was successful (`success`) -// - the payment profile ID (`payment_profile_id`) -// Lastly, you can also specify a `redirect_url` parameter within the `action_link` URL if you’d like to redirect a customer back to your site. -// It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. -// The final URL that you send a customer to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://checkout-test.chargifypay.test/3d-secure/checkout/pay_uerzhsxd5uhkbodx5jhvkg6yeu?one_time_token_id=93&callback_url=http://localhost:4000&redirect_url=https://yourpage.com` -// ### Example Redirect Flow -// You may wish to redirect customers to different pages depending on whether their SCA was performed successfully. Here's an example flow to use as a reference: -// 1. Create a payment profile via API; it requires 3DS -// 2. You receive a `action_link` in the response. -// 3. Use this `action_link` to, for example, connect with your internal resources or generate a session_id -// 4. Include 1 of those attributes inside the `callback_url` and `redirect_url` to be aware which “session” this applies to -// 5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied -// 6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. -// 7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known +// CreatePaymentProfile takes context, body as parameters and +// returns an models.ApiResponse with models.PaymentProfileResponse data and +// an error if there was an issue with the request or response. +// Use this endpoint to create a payment profile for a customer. +// Payment Profiles house the credit card, ACH (Authorize.Net or Stripe only,) or PayPal (Braintree only,) data for a customer. The payment information is attached to the customer within Chargify, as opposed to the Subscription itself. +// You must include a customer_id so that Chargify will attach it to the customer entry. If no customer_id is included the API will return a 404. +// ## Create a Payment Profile for ACH usage +// If you would like to create a payment method that is a Bank Account applicable for ACH payments use the following: +// ```json +// { +// "payment_profile": { +// "customer_id": [Valid-Customer-ID], +// "bank_name": "Best Bank", +// "bank_routing_number": "021000089", +// "bank_account_number": "111111111111", +// "bank_account_type": "checking", +// "bank_account_holder_type": "business", +// "payment_type": "bank_account" +// } +// } +// ``` +// ## Taxable Subscriptions +// If your subscriber pays taxes on their purchased product, and you are attempting to create or update the `payment_profile`, complete address information is required. For information on required address formatting to allow your subscriber to be taxed, please see our documentation [here](https://developers.chargify.com/docs/developer-docs/d2e9e34db740e-signups#taxes) +// ## Payment Profile Documentation +// Full documentation on how Payment Profiles operate within Chargify can be located under the following links: +// + [Subscriber Payment Details](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405212558349-Customers-Reference#customers-reference-0-0) +// + [Self Service Pages](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404759627021) (Allows credit card updates by Subscriber) +// + [Public Signup Pages payment settings](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405267754381-Individual-Page-Settings#credit-card-settings) +// ## Create a Payment Profile with a Chargify.js token +// ```json +// { +// "payment_profile": { +// "customer_id": 1036, +// "chargify_token": "tok_w68qcpnftyv53jk33jv6wk3w" +// } +// } +// ``` +// ## Active Payment Methods +// Creating a new payment profile for a Customer via the API will not make that Payment Profile current for any of the Customer’s Subscriptions. In order to utilize the payment profile as the default, it must be set as the default payment profile for the subscription or subscription group. +// ## Requirements +// Either the full_number, expiration_month, and expiration_year or if you have an existing vault_token from your gateway, that vault_token and the current_vault are required. +// Passing in the vault_token and current_vault are only allowed when creating a new payment profile. +// ### Taxable Subscriptions +// If your subscriber pays taxes on their purchased product, and you are attempting to create or update the `payment_profile`, complete address information is required. For information on required address formatting to allow your subscriber to be taxed, please see our documentation [here](https://developers.chargify.com/docs/developer-docs/d2e9e34db740e-signups#taxes) +// ## BraintreeBlue +// Some merchants use Braintree JavaScript libraries directly and then pass `payment_method_nonce` and/or `paypal_email` to create a payment profile. This implementation is deprecated and does not handle 3D Secure. Instead, we have provided [Chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview) which is continuously improved and supports Credit Cards (along with 3D Secure), PayPal and ApplePay payment types. +// ## GoCardless +// For more information on GoCardless, please view the following resources: +// + [Full documentation on GoCardless](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404501889677) +// + [Using Chargify.js with GoCardless - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-direct-debit-gocardless-gateway) +// + [Using Chargify.js with GoCardless - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-direct-debit-gocardless-gateway) +// ### GoCardless with Local Bank Details +// Following examples create customer, bank account and mandate in GoCardless: +// ```json +// { +// "payment_profile": { +// "customer_id": "Valid-Customer-ID", +// "bank_name": "Royal Bank of France", +// "bank_account_number": "0000000", +// "bank_routing_number": "0003", +// "bank_branch_code": "00006", +// "payment_type": "bank_account", +// "billing_address": "20 Place de la Gare", +// "billing_city": "Colombes", +// "billing_state": "Île-de-France", +// "billing_zip": "92700", +// "billing_country": "FR" +// } +// } +// ``` +// ### GoCardless with IBAN +// ```json +// { +// "payment_profile": { +// "customer_id": "24907598", +// "bank_name": "French Bank", +// "bank_iban": "FR1420041010050500013M02606", +// "payment_type": "bank_account", +// "billing_address": "20 Place de la Gare", +// "billing_city": "Colombes", +// "billing_state": "Île-de-France", +// "billing_zip": "92700", +// "billing_country": "FR" +// } +// } +// ``` +// ### Importing GoCardless +// If the customer, bank account, and mandate already exist in GoCardless, a payment profile can be created by using the IDs. In order to create masked versions of `bank_account_number` and `bank_routing_number` that are used to display within Chargify Admin UI, you can pass the last four digits for this fields which then will be saved in this form `XXXX[four-provided-digits]`. +// ```json +// { +// "payment_profile": { +// "customer_id": "24907598", +// "customer_vault_token": [Existing GoCardless Customer ID] +// "vault_token": [Existing GoCardless Mandate ID], +// "current_vault": "gocardless", +// "bank_name": "French Bank", +// "bank_account_number": [Last Four Of The Existing Account Number or IBAN if applicable], +// "bank_routing_number": [Last Four Of The Existing Routing Number], +// "payment_type": "bank_account", +// "billing_address": "20 Place de la Gare", +// "billing_city": "Colombes", +// "billing_state": "Île-de-France", +// "billing_zip": "92700", +// "billing_country": "FR" +// } +// } +// ``` +// ## SEPA Direct Debit +// For more information on Stripe SEPA Direct Debit, please view the following resources: +// + [Full documentation on Stripe SEPA Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) +// + [Using Chargify.js with Stripe Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) +// + [Using Chargify.js with Stripe Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-sepa-direct-debit-stripe-gateway) +// ### Stripe SEPA Direct Debit Payment Profiles +// The following example creates a customer, bank account and mandate in Stripe: +// ```json +// { +// "payment_profile": { +// "customer_id": "24907598", +// "bank_name": "Deutsche bank", +// "bank_iban": "DE89370400440532013000", +// "payment_type": "bank_account", +// "billing_address": "Test", +// "billing_city": "Berlin", +// "billing_state": "Brandenburg", +// "billing_zip": "12345", +// "billing_country": "DE" +// } +// } +// ``` +// ## Stripe BECS Direct Debit +// For more information on Stripe BECS Direct Debit, please view the following resources: +// + [Full documentation on Stripe BECS Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) +// + [Using Chargify.js with Stripe BECS Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) +// + [Using Chargify.js with Stripe BECS Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-sepa-direct-debit-stripe-gateway) +// ### Stripe BECS Direct Debit Payment Profiles +// The following example creates a customer, bank account and mandate in Stripe: +// ```json +// { +// "payment_profile": { +// "customer_id": "24907598", +// "bank_name": "Australian bank", +// "bank_branch_code": "000000", +// "bank_account_number": "000123456" +// "payment_type": "bank_account", +// "billing_address": "Test", +// "billing_city": "Stony Rise", +// "billing_state": "Tasmania", +// "billing_zip": "12345", +// "billing_country": "AU" +// } +// } +// ``` +// ## 3D Secure - Checkout +// It may happen that a payment needs 3D Secure Authentication when the payment profile is created; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: +// ```json +// { +// "jsonapi": { +// "version": "1.0" +// }, +// "errors": [ +// { +// "title": "This card requires 3DSecure verification.", +// "detail": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://checkout-test.chargifypay.test/3d-secure/checkout/pay_uerzhsxd5uhkbodx5jhvkg6yeu?one_time_token_id=93&callback_url=http://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after credit card is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", +// "links": { +// "action_link": "https://checkout-test.chargifypay.test/3d-secure/checkout/pay_uerzhsxd5uhkbodx5jhvkg6yeu?one_time_token_id=93" +// } +// } +// ] +// } +// ``` +// To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. +// Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: +// - whether the authentication was successful (`success`) +// - the payment profile ID (`payment_profile_id`) +// Lastly, you can also specify a `redirect_url` parameter within the `action_link` URL if you’d like to redirect a customer back to your site. +// It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. +// The final URL that you send a customer to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://checkout-test.chargifypay.test/3d-secure/checkout/pay_uerzhsxd5uhkbodx5jhvkg6yeu?one_time_token_id=93&callback_url=http://localhost:4000&redirect_url=https://yourpage.com` +// ### Example Redirect Flow +// You may wish to redirect customers to different pages depending on whether their SCA was performed successfully. Here's an example flow to use as a reference: +// 1. Create a payment profile via API; it requires 3DS +// 2. You receive a `action_link` in the response. +// 3. Use this `action_link` to, for example, connect with your internal resources or generate a session_id +// 4. Include 1 of those attributes inside the `callback_url` and `redirect_url` to be aware which “session” this applies to +// 5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied +// 6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. +// 7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known // 8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not func (p *PaymentProfilesController) CreatePaymentProfile( - ctx context.Context, - body *models.CreatePaymentProfileRequest) ( - models.ApiResponse[models.PaymentProfileResponse], - error) { - req := p.prepareRequest(ctx, "POST", "/payment_profiles.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.PaymentProfileResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.PaymentProfileResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.CreatePaymentProfileRequest) ( + models.ApiResponse[models.PaymentProfileResponse], + error) { + req := p.prepareRequest(ctx, "POST", "/payment_profiles.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.PaymentProfileResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.PaymentProfileResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListPaymentProfilesInput represents the input of the ListPaymentProfiles endpoint. +type ListPaymentProfilesInput struct { + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The ID of the customer for which you wish to list payment profiles + CustomerId *int } -// ListPaymentProfiles takes context, page, perPage, customerId as parameters and -// returns an models.ApiResponse with []models.PaymentProfileResponse data and -// an error if there was an issue with the request or response. +// ListPaymentProfiles takes context, page, perPage, customerId as parameters and +// returns an models.ApiResponse with []models.PaymentProfileResponse data and +// an error if there was an issue with the request or response. // This method will return all of the active `payment_profiles` for a Site, or for one Customer within a site. If no payment profiles are found, this endpoint will return an empty array, not a 404. func (p *PaymentProfilesController) ListPaymentProfiles( - ctx context.Context, - page *int, - perPage *int, - customerId *int) ( - models.ApiResponse[[]models.PaymentProfileResponse], - error) { - req := p.prepareRequest(ctx, "GET", "/payment_profiles.json") - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if customerId != nil { - req.QueryParam("customer_id", *customerId) - } - var result []models.PaymentProfileResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.PaymentProfileResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListPaymentProfilesInput) ( + models.ApiResponse[[]models.PaymentProfileResponse], + error) { + req := p.prepareRequest(ctx, "GET", "/payment_profiles.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.CustomerId != nil { + req.QueryParam("customer_id", *input.CustomerId) + } + var result []models.PaymentProfileResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.PaymentProfileResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadPaymentProfile takes context, paymentProfileId as parameters and -// returns an models.ApiResponse with models.PaymentProfileResponse data and -// an error if there was an issue with the request or response. -// Using the GET method you can retrieve a Payment Profile identified by its unique ID. -// Please note that a different JSON object will be returned if the card method on file is a bank account. -// ### Response for Bank Account -// Example response for Bank Account: -// ``` -// { -// "payment_profile": { -// "id": 10089892, -// "first_name": "Chester", -// "last_name": "Tester", -// "customer_id": 14543792, -// "current_vault": "bogus", -// "vault_token": "0011223344", -// "billing_address": "456 Juniper Court", -// "billing_city": "Boulder", -// "billing_state": "CO", -// "billing_zip": "80302", -// "billing_country": "US", -// "customer_vault_token": null, -// "billing_address_2": "", -// "bank_name": "Bank of Kansas City", -// "masked_bank_routing_number": "XXXX6789", -// "masked_bank_account_number": "XXXX3344", -// "bank_account_type": "checking", -// "bank_account_holder_type": "personal", -// "payment_type": "bank_account", -// "site_gateway_setting_id": 1, -// "gateway_handle": null -// } -// } +// ReadPaymentProfile takes context, paymentProfileId as parameters and +// returns an models.ApiResponse with models.PaymentProfileResponse data and +// an error if there was an issue with the request or response. +// Using the GET method you can retrieve a Payment Profile identified by its unique ID. +// Please note that a different JSON object will be returned if the card method on file is a bank account. +// ### Response for Bank Account +// Example response for Bank Account: +// ``` +// { +// "payment_profile": { +// "id": 10089892, +// "first_name": "Chester", +// "last_name": "Tester", +// "customer_id": 14543792, +// "current_vault": "bogus", +// "vault_token": "0011223344", +// "billing_address": "456 Juniper Court", +// "billing_city": "Boulder", +// "billing_state": "CO", +// "billing_zip": "80302", +// "billing_country": "US", +// "customer_vault_token": null, +// "billing_address_2": "", +// "bank_name": "Bank of Kansas City", +// "masked_bank_routing_number": "XXXX6789", +// "masked_bank_account_number": "XXXX3344", +// "bank_account_type": "checking", +// "bank_account_holder_type": "personal", +// "payment_type": "bank_account", +// "site_gateway_setting_id": 1, +// "gateway_handle": null +// } +// } // ``` func (p *PaymentProfilesController) ReadPaymentProfile( - ctx context.Context, - paymentProfileId int) ( - models.ApiResponse[models.PaymentProfileResponse], - error) { - req := p.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/payment_profiles/%v.json", paymentProfileId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {Message: "Not Found"}, - }) - - var result models.PaymentProfileResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.PaymentProfileResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + paymentProfileId int) ( + models.ApiResponse[models.PaymentProfileResponse], + error) { + req := p.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/payment_profiles/%v.json", paymentProfileId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {Message: "Not Found"}, + }) + + var result models.PaymentProfileResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.PaymentProfileResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdatePaymentProfile takes context, paymentProfileId, body as parameters and -// returns an models.ApiResponse with models.PaymentProfileResponse data and -// an error if there was an issue with the request or response. -// ## Partial Card Updates -// In the event that you are using the Authorize.net, Stripe, Cybersource, Forte or Braintree Blue payment gateways, you can update just the billing and contact information for a payment method. Note the lack of credit-card related data contained in the JSON payload. -// In this case, the following JSON is acceptable: -// ``` -// { -// "payment_profile": { -// "first_name": "Kelly", -// "last_name": "Test", -// "billing_address": "789 Juniper Court", -// "billing_city": "Boulder", -// "billing_state": "CO", -// "billing_zip": "80302", -// "billing_country": "US", -// "billing_address_2": null -// } -// } -// ``` -// The result will be that you have updated the billing information for the card, yet retained the original card number data. -// ## Specific notes on updating payment profiles -// - Merchants with **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe** as their payment gateway can update their Customer’s credit cards without passing in the full credit card number and CVV. -// - If you are using **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe**, Chargify will ignore the credit card number and CVV when processing an update via the API, and attempt a partial update instead. If you wish to change the card number on a payment profile, you will need to create a new payment profile for the given customer. -// - A Payment Profile cannot be updated with the attributes of another type of Payment Profile. For example, if the payment profile you are attempting to update is a credit card, you cannot pass in bank account attributes (like `bank_account_number`), and vice versa. -// - Updating a payment profile directly will not trigger an attempt to capture a past-due balance. If this is the intent, update the card details via the Subscription instead. +// UpdatePaymentProfile takes context, paymentProfileId, body as parameters and +// returns an models.ApiResponse with models.PaymentProfileResponse data and +// an error if there was an issue with the request or response. +// ## Partial Card Updates +// In the event that you are using the Authorize.net, Stripe, Cybersource, Forte or Braintree Blue payment gateways, you can update just the billing and contact information for a payment method. Note the lack of credit-card related data contained in the JSON payload. +// In this case, the following JSON is acceptable: +// ``` +// { +// "payment_profile": { +// "first_name": "Kelly", +// "last_name": "Test", +// "billing_address": "789 Juniper Court", +// "billing_city": "Boulder", +// "billing_state": "CO", +// "billing_zip": "80302", +// "billing_country": "US", +// "billing_address_2": null +// } +// } +// ``` +// The result will be that you have updated the billing information for the card, yet retained the original card number data. +// ## Specific notes on updating payment profiles +// - Merchants with **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe** as their payment gateway can update their Customer’s credit cards without passing in the full credit card number and CVV. +// - If you are using **Authorize.net**, **Cybersource**, **Forte**, **Braintree Blue** or **Stripe**, Chargify will ignore the credit card number and CVV when processing an update via the API, and attempt a partial update instead. If you wish to change the card number on a payment profile, you will need to create a new payment profile for the given customer. +// - A Payment Profile cannot be updated with the attributes of another type of Payment Profile. For example, if the payment profile you are attempting to update is a credit card, you cannot pass in bank account attributes (like `bank_account_number`), and vice versa. +// - Updating a payment profile directly will not trigger an attempt to capture a past-due balance. If this is the intent, update the card details via the Subscription instead. // - If you are using Authorize.net or Stripe, you may elect to manually trigger a retry for a past due subscription after a partial update. func (p *PaymentProfilesController) UpdatePaymentProfile( - ctx context.Context, - paymentProfileId int, - body *models.UpdatePaymentProfileRequest) ( - models.ApiResponse[models.PaymentProfileResponse], - error) { - req := p.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/payment_profiles/%v.json", paymentProfileId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {Message: "Not Found"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorStringMapResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.PaymentProfileResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.PaymentProfileResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + paymentProfileId int, + body *models.UpdatePaymentProfileRequest) ( + models.ApiResponse[models.PaymentProfileResponse], + error) { + req := p.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/payment_profiles/%v.json", paymentProfileId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {Message: "Not Found"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorStringMapResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.PaymentProfileResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.PaymentProfileResponse](decoder) + return models.NewApiResponse(result, resp), err } -// DeleteUnusedPaymentProfile takes context, paymentProfileId as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// Deletes an unused payment profile. +// DeleteUnusedPaymentProfile takes context, paymentProfileId as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// Deletes an unused payment profile. // If the payment profile is in use by one or more subscriptions or groups, a 422 and error message will be returned. func (p *PaymentProfilesController) DeleteUnusedPaymentProfile( - ctx context.Context, - paymentProfileId int) ( - *http.Response, - error) { - req := p.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/payment_profiles/%v.json", paymentProfileId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {Message: "Not Found"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + paymentProfileId int) ( + *http.Response, + error) { + req := p.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/payment_profiles/%v.json", paymentProfileId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {Message: "Not Found"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// DeleteSubscriptionsPaymentProfile takes context, subscriptionId, paymentProfileId as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// This will delete a payment profile belonging to the customer on the subscription. -// + If the customer has multiple subscriptions, the payment profile will be removed from all of them. +// DeleteSubscriptionsPaymentProfile takes context, subscriptionId, paymentProfileId as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// This will delete a payment profile belonging to the customer on the subscription. +// + If the customer has multiple subscriptions, the payment profile will be removed from all of them. // + If you delete the default payment profile for a subscription, you will need to specify another payment profile to be the default through the api, or either prompt the user to enter a card in the billing portal or on the self-service page, or visit the Payment Details tab on the subscription in the Admin UI and use the “Add New Credit Card” or “Make Active Payment Method” link, (depending on whether there are other cards present). func (p *PaymentProfilesController) DeleteSubscriptionsPaymentProfile( - ctx context.Context, - subscriptionId int, - paymentProfileId int) ( - *http.Response, - error) { - req := p.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/subscriptions/%v/payment_profiles/%v.json", subscriptionId, paymentProfileId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subscriptionId int, + paymentProfileId int) ( + *http.Response, + error) { + req := p.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/subscriptions/%v/payment_profiles/%v.json", subscriptionId, paymentProfileId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// VerifyBankAccount takes context, bankAccountId, body as parameters and -// returns an models.ApiResponse with models.BankAccountResponse data and -// an error if there was an issue with the request or response. +// VerifyBankAccount takes context, bankAccountId, body as parameters and +// returns an models.ApiResponse with models.BankAccountResponse data and +// an error if there was an issue with the request or response. // Submit the two small deposit amounts the customer received in their bank account in order to verify the bank account. (Stripe only) func (p *PaymentProfilesController) VerifyBankAccount( - ctx context.Context, - bankAccountId int, - body *models.BankAccountVerificationRequest) ( - models.ApiResponse[models.BankAccountResponse], - error) { - req := p.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/bank_accounts/%v/verification.json", bankAccountId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.BankAccountResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.BankAccountResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + bankAccountId int, + body *models.BankAccountVerificationRequest) ( + models.ApiResponse[models.BankAccountResponse], + error) { + req := p.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/bank_accounts/%v/verification.json", bankAccountId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.BankAccountResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.BankAccountResponse](decoder) + return models.NewApiResponse(result, resp), err } -// DeleteSubscriptionGroupPaymentProfile takes context, uid, paymentProfileId as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// This will delete a Payment Profile belonging to a Subscription Group. +// DeleteSubscriptionGroupPaymentProfile takes context, uid, paymentProfileId as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// This will delete a Payment Profile belonging to a Subscription Group. // **Note**: If the Payment Profile belongs to multiple Subscription Groups and/or Subscriptions, it will be removed from all of them. func (p *PaymentProfilesController) DeleteSubscriptionGroupPaymentProfile( - ctx context.Context, - uid string, - paymentProfileId int) ( - *http.Response, - error) { - req := p.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/subscription_groups/%v/payment_profiles/%v.json", uid, paymentProfileId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + uid string, + paymentProfileId int) ( + *http.Response, + error) { + req := p.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/subscription_groups/%v/payment_profiles/%v.json", uid, paymentProfileId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// ChangeSubscriptionDefaultPaymentProfile takes context, subscriptionId, paymentProfileId as parameters and -// returns an models.ApiResponse with models.PaymentProfileResponse data and -// an error if there was an issue with the request or response. -// This will change the default payment profile on the subscription to the existing payment profile with the id specified. +// ChangeSubscriptionDefaultPaymentProfile takes context, subscriptionId, paymentProfileId as parameters and +// returns an models.ApiResponse with models.PaymentProfileResponse data and +// an error if there was an issue with the request or response. +// This will change the default payment profile on the subscription to the existing payment profile with the id specified. // You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. func (p *PaymentProfilesController) ChangeSubscriptionDefaultPaymentProfile( - ctx context.Context, - subscriptionId int, - paymentProfileId int) ( - models.ApiResponse[models.PaymentProfileResponse], - error) { - req := p.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/payment_profiles/%v/change_payment_profile.json", subscriptionId, paymentProfileId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {Message: "Not Found"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.PaymentProfileResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.PaymentProfileResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + paymentProfileId int) ( + models.ApiResponse[models.PaymentProfileResponse], + error) { + req := p.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/payment_profiles/%v/change_payment_profile.json", subscriptionId, paymentProfileId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {Message: "Not Found"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.PaymentProfileResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.PaymentProfileResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ChangeSubscriptionGroupDefaultPaymentProfile takes context, uid, paymentProfileId as parameters and -// returns an models.ApiResponse with models.PaymentProfileResponse data and -// an error if there was an issue with the request or response. -// This will change the default payment profile on the subscription group to the existing payment profile with the id specified. -// You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. +// ChangeSubscriptionGroupDefaultPaymentProfile takes context, uid, paymentProfileId as parameters and +// returns an models.ApiResponse with models.PaymentProfileResponse data and +// an error if there was an issue with the request or response. +// This will change the default payment profile on the subscription group to the existing payment profile with the id specified. +// You must elect to change the existing payment profile to a new payment profile ID in order to receive a satisfactory response from this endpoint. // The new payment profile must belong to the subscription group's customer, otherwise you will receive an error. func (p *PaymentProfilesController) ChangeSubscriptionGroupDefaultPaymentProfile( - ctx context.Context, - uid string, - paymentProfileId int) ( - models.ApiResponse[models.PaymentProfileResponse], - error) { - req := p.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscription_groups/%v/payment_profiles/%v/change_payment_profile.json", uid, paymentProfileId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.PaymentProfileResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.PaymentProfileResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string, + paymentProfileId int) ( + models.ApiResponse[models.PaymentProfileResponse], + error) { + req := p.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscription_groups/%v/payment_profiles/%v/change_payment_profile.json", uid, paymentProfileId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.PaymentProfileResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.PaymentProfileResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadOneTimeToken takes context, chargifyToken as parameters and -// returns an models.ApiResponse with models.GetOneTimeTokenRequest data and -// an error if there was an issue with the request or response. -// One Time Tokens aka Chargify Tokens house the credit card or ACH (Authorize.Net or Stripe only) data for a customer. -// You can use One Time Tokens while creating a subscription or payment profile instead of passing all bank account or credit card data directly to a given API endpoint. +// ReadOneTimeToken takes context, chargifyToken as parameters and +// returns an models.ApiResponse with models.GetOneTimeTokenRequest data and +// an error if there was an issue with the request or response. +// One Time Tokens aka Chargify Tokens house the credit card or ACH (Authorize.Net or Stripe only) data for a customer. +// You can use One Time Tokens while creating a subscription or payment profile instead of passing all bank account or credit card data directly to a given API endpoint. // To obtain a One Time Token you have to use [chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview). func (p *PaymentProfilesController) ReadOneTimeToken( - ctx context.Context, - chargifyToken string) ( - models.ApiResponse[models.GetOneTimeTokenRequest], - error) { - req := p.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/one_time_tokens/%v.json", chargifyToken), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.GetOneTimeTokenRequest - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.GetOneTimeTokenRequest](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + chargifyToken string) ( + models.ApiResponse[models.GetOneTimeTokenRequest], + error) { + req := p.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/one_time_tokens/%v.json", chargifyToken), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.GetOneTimeTokenRequest + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.GetOneTimeTokenRequest](decoder) + return models.NewApiResponse(result, resp), err } -// SendRequestUpdatePaymentEmail takes context, subscriptionId as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// You can send a "request payment update" email to the customer associated with the subscription. -// If you attempt to send a "request payment update" email more than five times within a 30-minute period, you will receive a `422` response with an error message in the body. This error message will indicate that the request has been rejected due to excessive attempts, and will provide instructions on how to resubmit the request. -// Additionally, if you attempt to send a "request payment update" email for a subscription that does not exist, you will receive a `404` error response. This error message will indicate that the subscription could not be found, and will provide instructions on how to correct the error and resubmit the request. +// SendRequestUpdatePaymentEmail takes context, subscriptionId as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// You can send a "request payment update" email to the customer associated with the subscription. +// If you attempt to send a "request payment update" email more than five times within a 30-minute period, you will receive a `422` response with an error message in the body. This error message will indicate that the request has been rejected due to excessive attempts, and will provide instructions on how to resubmit the request. +// Additionally, if you attempt to send a "request payment update" email for a subscription that does not exist, you will receive a `404` error response. This error message will indicate that the subscription could not be found, and will provide instructions on how to correct the error and resubmit the request. // These error responses are designed to prevent excessive or invalid requests, and to provide clear and helpful information to users who encounter errors during the request process. func (p *PaymentProfilesController) SendRequestUpdatePaymentEmail( - ctx context.Context, - subscriptionId int) ( - *http.Response, - error) { - req := p.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/request_payment_profiles_update.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subscriptionId int) ( + *http.Response, + error) { + req := p.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/request_payment_profiles_update.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } diff --git a/product_families_controller.go b/product_families_controller.go index d61b3022..f3a4bf44 100644 --- a/product_families_controller.go +++ b/product_families_controller.go @@ -1,187 +1,218 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" ) // ProductFamiliesController represents a controller struct. type ProductFamiliesController struct { - baseController + baseController } -// NewProductFamiliesController creates a new instance of ProductFamiliesController. +// NewProductFamiliesController creates a new instance of ProductFamiliesController. // It takes a baseController as a parameter and returns a pointer to the ProductFamiliesController. func NewProductFamiliesController(baseController baseController) *ProductFamiliesController { - productFamiliesController := ProductFamiliesController{baseController: baseController} - return &productFamiliesController + productFamiliesController := ProductFamiliesController{baseController: baseController} + return &productFamiliesController } -// ListProductsForProductFamily takes context, productFamilyId, page, perPage, dateField, startDate, endDate, startDatetime, endDatetime, includeArchived, include, filterPrepaidProductPricePointProductPricePointId, filterUseSiteExchangeRate as parameters and -// returns an models.ApiResponse with []models.ProductResponse data and -// an error if there was an issue with the request or response. +// ListProductsForProductFamilyInput represents the input of the ListProductsForProductFamily endpoint. +type ListProductsForProductFamilyInput struct { + // The Chargify id of the product family to which the product belongs + ProductFamilyId int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The type of filter you would like to apply to your search. + // Use in query: `date_field=created_at`. + DateField *models.BasicDateField + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + StartDate *string + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + EndDate *string + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. + StartDatetime *string + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. + EndDatetime *string + // Include archived products + IncludeArchived *bool + // Allows including additional data in the response. Use in query `include=prepaid_product_price_point`. + Include *models.ListProductsInclude + // Allows fetching products only if a prepaid product price point is present or not. To use this filter you also have to include the following param in the request `include=prepaid_product_price_point`. Use in query `filter[prepaid_product_price_point][product_price_point_id]=not_null`. + FilterPrepaidProductPricePointProductPricePointId *models.IncludeNotNull + // Allows fetching products with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. + FilterUseSiteExchangeRate *bool +} + +// ListProductsForProductFamily takes context, productFamilyId, page, perPage, dateField, startDate, endDate, startDatetime, endDatetime, includeArchived, include, filterPrepaidProductPricePointProductPricePointId, filterUseSiteExchangeRate as parameters and +// returns an models.ApiResponse with []models.ProductResponse data and +// an error if there was an issue with the request or response. // This method allows to retrieve a list of Products belonging to a Product Family. func (p *ProductFamiliesController) ListProductsForProductFamily( - ctx context.Context, - productFamilyId int, - page *int, - perPage *int, - dateField *models.BasicDateField, - startDate *string, - endDate *string, - startDatetime *string, - endDatetime *string, - includeArchived *bool, - include *models.ListProductsInclude, - filterPrepaidProductPricePointProductPricePointId *models.IncludeNotNull, - filterUseSiteExchangeRate *bool) ( - models.ApiResponse[[]models.ProductResponse], - error) { - req := p.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/product_families/%v/products.json", productFamilyId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {Message: "Not Found"}, - }) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if startDate != nil { - req.QueryParam("start_date", *startDate) - } - if endDate != nil { - req.QueryParam("end_date", *endDate) - } - if startDatetime != nil { - req.QueryParam("start_datetime", *startDatetime) - } - if endDatetime != nil { - req.QueryParam("end_datetime", *endDatetime) - } - if includeArchived != nil { - req.QueryParam("include_archived", *includeArchived) - } - if include != nil { - req.QueryParam("include", *include) - } - if filterPrepaidProductPricePointProductPricePointId != nil { - req.QueryParam("filter[prepaid_product_price_point][product_price_point_id]", *filterPrepaidProductPricePointProductPricePointId) - } - if filterUseSiteExchangeRate != nil { - req.QueryParam("filter[use_site_exchange_rate]", *filterUseSiteExchangeRate) - } - - var result []models.ProductResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.ProductResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListProductsForProductFamilyInput) ( + models.ApiResponse[[]models.ProductResponse], + error) { + req := p.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/product_families/%v/products.json", input.ProductFamilyId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {Message: "Not Found"}, + }) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.StartDate != nil { + req.QueryParam("start_date", *input.StartDate) + } + if input.EndDate != nil { + req.QueryParam("end_date", *input.EndDate) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", *input.StartDatetime) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", *input.EndDatetime) + } + if input.IncludeArchived != nil { + req.QueryParam("include_archived", *input.IncludeArchived) + } + if input.Include != nil { + req.QueryParam("include", *input.Include) + } + if input.FilterPrepaidProductPricePointProductPricePointId != nil { + req.QueryParam("filter[prepaid_product_price_point][product_price_point_id]", *input.FilterPrepaidProductPricePointProductPricePointId) + } + if input.FilterUseSiteExchangeRate != nil { + req.QueryParam("filter[use_site_exchange_rate]", *input.FilterUseSiteExchangeRate) + } + + var result []models.ProductResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.ProductResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreateProductFamily takes context, body as parameters and -// returns an models.ApiResponse with models.ProductFamilyResponse data and -// an error if there was an issue with the request or response. -// This method will create a Product Family within your Chargify site. Create a Product Family to act as a container for your products, components and coupons. +// CreateProductFamily takes context, body as parameters and +// returns an models.ApiResponse with models.ProductFamilyResponse data and +// an error if there was an issue with the request or response. +// This method will create a Product Family within your Chargify site. Create a Product Family to act as a container for your products, components and coupons. // Full documentation on how Product Families operate within the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405369633421). func (p *ProductFamiliesController) CreateProductFamily( - ctx context.Context, - body *models.CreateProductFamilyRequest) ( - models.ApiResponse[models.ProductFamilyResponse], - error) { - req := p.prepareRequest(ctx, "POST", "/product_families.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.ProductFamilyResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductFamilyResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.CreateProductFamilyRequest) ( + models.ApiResponse[models.ProductFamilyResponse], + error) { + req := p.prepareRequest(ctx, "POST", "/product_families.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.ProductFamilyResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductFamilyResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListProductFamilies takes context, dateField, startDate, endDate, startDatetime, endDatetime as parameters and -// returns an models.ApiResponse with []models.ProductFamilyResponse data and -// an error if there was an issue with the request or response. +// ListProductFamiliesInput represents the input of the ListProductFamilies endpoint. +type ListProductFamiliesInput struct { + // The type of filter you would like to apply to your search. + // Use in query: `date_field=created_at`. + DateField *models.BasicDateField + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + StartDate *string + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + EndDate *string + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. + StartDatetime *string + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. + EndDatetime *string +} + +// ListProductFamilies takes context, dateField, startDate, endDate, startDatetime, endDatetime as parameters and +// returns an models.ApiResponse with []models.ProductFamilyResponse data and +// an error if there was an issue with the request or response. // This method allows to retrieve a list of Product Families for a site. func (p *ProductFamiliesController) ListProductFamilies( - ctx context.Context, - dateField *models.BasicDateField, - startDate *string, - endDate *string, - startDatetime *string, - endDatetime *string) ( - models.ApiResponse[[]models.ProductFamilyResponse], - error) { - req := p.prepareRequest(ctx, "GET", "/product_families.json") - req.Authenticate(NewAuth("BasicAuth")) - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if startDate != nil { - req.QueryParam("start_date", *startDate) - } - if endDate != nil { - req.QueryParam("end_date", *endDate) - } - if startDatetime != nil { - req.QueryParam("start_datetime", *startDatetime) - } - if endDatetime != nil { - req.QueryParam("end_datetime", *endDatetime) - } - var result []models.ProductFamilyResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.ProductFamilyResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListProductFamiliesInput) ( + models.ApiResponse[[]models.ProductFamilyResponse], + error) { + req := p.prepareRequest(ctx, "GET", "/product_families.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.StartDate != nil { + req.QueryParam("start_date", *input.StartDate) + } + if input.EndDate != nil { + req.QueryParam("end_date", *input.EndDate) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", *input.StartDatetime) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", *input.EndDatetime) + } + var result []models.ProductFamilyResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.ProductFamilyResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadProductFamily takes context, id as parameters and -// returns an models.ApiResponse with models.ProductFamilyResponse data and -// an error if there was an issue with the request or response. -// This method allows to retrieve a Product Family via the `product_family_id`. The response will contain a Product Family object. +// ReadProductFamily takes context, id as parameters and +// returns an models.ApiResponse with models.ProductFamilyResponse data and +// an error if there was an issue with the request or response. +// This method allows to retrieve a Product Family via the `product_family_id`. The response will contain a Product Family object. // The product family can be specified either with the id number, or with the `handle:my-family` format. func (p *ProductFamiliesController) ReadProductFamily( - ctx context.Context, - id int) ( - models.ApiResponse[models.ProductFamilyResponse], - error) { - req := p.prepareRequest(ctx, "GET", fmt.Sprintf("/product_families/%v.json", id)) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.ProductFamilyResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductFamilyResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + id int) ( + models.ApiResponse[models.ProductFamilyResponse], + error) { + req := p.prepareRequest(ctx, "GET", fmt.Sprintf("/product_families/%v.json", id)) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.ProductFamilyResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductFamilyResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/product_price_points_controller.go b/product_price_points_controller.go index e7b984c6..92ffa322 100644 --- a/product_price_points_controller.go +++ b/product_price_points_controller.go @@ -1,425 +1,456 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "time" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "time" ) // ProductPricePointsController represents a controller struct. type ProductPricePointsController struct { - baseController + baseController } -// NewProductPricePointsController creates a new instance of ProductPricePointsController. +// NewProductPricePointsController creates a new instance of ProductPricePointsController. // It takes a baseController as a parameter and returns a pointer to the ProductPricePointsController. func NewProductPricePointsController(baseController baseController) *ProductPricePointsController { - productPricePointsController := ProductPricePointsController{baseController: baseController} - return &productPricePointsController + productPricePointsController := ProductPricePointsController{baseController: baseController} + return &productPricePointsController } -// CreateProductPricePoint takes context, productId, body as parameters and -// returns an models.ApiResponse with models.ProductPricePointResponse data and -// an error if there was an issue with the request or response. +// CreateProductPricePoint takes context, productId, body as parameters and +// returns an models.ApiResponse with models.ProductPricePointResponse data and +// an error if there was an issue with the request or response. // [Product Price Point Documentation](https://chargify.zendesk.com/hc/en-us/articles/4407755824155) func (p *ProductPricePointsController) CreateProductPricePoint( - ctx context.Context, - productId interface{}, - body *models.CreateProductPricePointRequest) ( - models.ApiResponse[models.ProductPricePointResponse], - error) { - req := p.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/products/%v/price_points.json", productId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewProductPricePointErrorResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ProductPricePointResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductPricePointResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productId models.CreateProductPricePointProductId, + body *models.CreateProductPricePointRequest) ( + models.ApiResponse[models.ProductPricePointResponse], + error) { + req := p.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/products/%v/price_points.json", productId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewProductPricePointErrorResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ProductPricePointResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductPricePointResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListProductPricePointsInput represents the input of the ListProductPricePoints endpoint. +type ListProductPricePointsInput struct { + // The id or handle of the product. When using the handle, it must be prefixed with `handle:` + ProductId models.ListProductPricePointsInputProductId + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 10. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + PerPage *int + // When fetching a product's price points, if you have defined multiple currencies at the site level, you can optionally pass the ?currency_prices=true query param to include an array of currency price data in the response. If the product price point is set to use_site_exchange_rate: true, it will return pricing based on the current exchange rate. If the flag is set to false, it will return all of the defined prices for each currency. + CurrencyPrices *bool + // Use in query: `filter[type]=catalog,default`. + FilterType []models.PricePointType } -// ListProductPricePoints takes context, productId, page, perPage, currencyPrices, filterType as parameters and -// returns an models.ApiResponse with models.ListProductPricePointsResponse data and -// an error if there was an issue with the request or response. +// ListProductPricePoints takes context, productId, page, perPage, currencyPrices, filterType as parameters and +// returns an models.ApiResponse with models.ListProductPricePointsResponse data and +// an error if there was an issue with the request or response. // Use this endpoint to retrieve a list of product price points. func (p *ProductPricePointsController) ListProductPricePoints( - ctx context.Context, - productId interface{}, - page *int, - perPage *int, - currencyPrices *bool, - filterType []models.PricePointType) ( - models.ApiResponse[models.ListProductPricePointsResponse], - error) { - req := p.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/products/%v/price_points.json", productId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if currencyPrices != nil { - req.QueryParam("currency_prices", *currencyPrices) - } - if filterType != nil { - req.QueryParam("filter[type]", filterType) - } - - var result models.ListProductPricePointsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListProductPricePointsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListProductPricePointsInput) ( + models.ApiResponse[models.ListProductPricePointsResponse], + error) { + req := p.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/products/%v/price_points.json", input.ProductId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.CurrencyPrices != nil { + req.QueryParam("currency_prices", *input.CurrencyPrices) + } + if input.FilterType != nil { + req.QueryParam("filter[type]", input.FilterType) + } + + var result models.ListProductPricePointsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListProductPricePointsResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateProductPricePoint takes context, productId, pricePointId, body as parameters and -// returns an models.ApiResponse with models.ProductPricePointResponse data and -// an error if there was an issue with the request or response. -// Use this endpoint to update a product price point. +// UpdateProductPricePoint takes context, productId, pricePointId, body as parameters and +// returns an models.ApiResponse with models.ProductPricePointResponse data and +// an error if there was an issue with the request or response. +// Use this endpoint to update a product price point. // Note: Custom product price points are not able to be updated. func (p *ProductPricePointsController) UpdateProductPricePoint( - ctx context.Context, - productId interface{}, - pricePointId interface{}, - body *models.UpdateProductPricePointRequest) ( - models.ApiResponse[models.ProductPricePointResponse], - error) { - req := p.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/products/%v/price_points/%v.json", productId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ProductPricePointResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductPricePointResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productId models.UpdateProductPricePointProductId, + pricePointId models.UpdateProductPricePointPricePointId, + body *models.UpdateProductPricePointRequest) ( + models.ApiResponse[models.ProductPricePointResponse], + error) { + req := p.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/products/%v/price_points/%v.json", productId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ProductPricePointResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductPricePointResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadProductPricePoint takes context, productId, pricePointId, currencyPrices as parameters and -// returns an models.ApiResponse with models.ProductPricePointResponse data and -// an error if there was an issue with the request or response. +// ReadProductPricePoint takes context, productId, pricePointId, currencyPrices as parameters and +// returns an models.ApiResponse with models.ProductPricePointResponse data and +// an error if there was an issue with the request or response. // Use this endpoint to retrieve details for a specific product price point. func (p *ProductPricePointsController) ReadProductPricePoint( - ctx context.Context, - productId interface{}, - pricePointId interface{}, - currencyPrices *bool) ( - models.ApiResponse[models.ProductPricePointResponse], - error) { - req := p.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/products/%v/price_points/%v.json", productId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if currencyPrices != nil { - req.QueryParam("currency_prices", *currencyPrices) - } - - var result models.ProductPricePointResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductPricePointResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productId models.ReadProductPricePointProductId, + pricePointId models.ReadProductPricePointPricePointId, + currencyPrices *bool) ( + models.ApiResponse[models.ProductPricePointResponse], + error) { + req := p.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/products/%v/price_points/%v.json", productId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if currencyPrices != nil { + req.QueryParam("currency_prices", *currencyPrices) + } + + var result models.ProductPricePointResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductPricePointResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ArchiveProductPricePoint takes context, productId, pricePointId as parameters and -// returns an models.ApiResponse with models.ProductPricePointResponse data and -// an error if there was an issue with the request or response. +// ArchiveProductPricePoint takes context, productId, pricePointId as parameters and +// returns an models.ApiResponse with models.ProductPricePointResponse data and +// an error if there was an issue with the request or response. // Use this endpoint to archive a product price point. func (p *ProductPricePointsController) ArchiveProductPricePoint( - ctx context.Context, - productId interface{}, - pricePointId interface{}) ( - models.ApiResponse[models.ProductPricePointResponse], - error) { - req := p.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/products/%v/price_points/%v.json", productId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.ProductPricePointResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductPricePointResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productId models.ArchiveProductPricePointProductId, + pricePointId models.ArchiveProductPricePointPricePointId) ( + models.ApiResponse[models.ProductPricePointResponse], + error) { + req := p.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/products/%v/price_points/%v.json", productId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.ProductPricePointResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductPricePointResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UnarchiveProductPricePoint takes context, productId, pricePointId as parameters and -// returns an models.ApiResponse with models.ProductPricePointResponse data and -// an error if there was an issue with the request or response. +// UnarchiveProductPricePoint takes context, productId, pricePointId as parameters and +// returns an models.ApiResponse with models.ProductPricePointResponse data and +// an error if there was an issue with the request or response. // Use this endpoint to unarchive an archived product price point. func (p *ProductPricePointsController) UnarchiveProductPricePoint( - ctx context.Context, - productId int, - pricePointId int) ( - models.ApiResponse[models.ProductPricePointResponse], - error) { - req := p.prepareRequest( - ctx, - "PATCH", - fmt.Sprintf("/products/%v/price_points/%v/unarchive.json", productId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.ProductPricePointResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductPricePointResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productId int, + pricePointId int) ( + models.ApiResponse[models.ProductPricePointResponse], + error) { + req := p.prepareRequest( + ctx, + "PATCH", + fmt.Sprintf("/products/%v/price_points/%v/unarchive.json", productId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.ProductPricePointResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductPricePointResponse](decoder) + return models.NewApiResponse(result, resp), err } -// PromoteProductPricePointToDefault takes context, productId, pricePointId as parameters and -// returns an models.ApiResponse with models.ProductResponse data and -// an error if there was an issue with the request or response. -// Use this endpoint to make a product price point the default for the product. +// PromoteProductPricePointToDefault takes context, productId, pricePointId as parameters and +// returns an models.ApiResponse with models.ProductResponse data and +// an error if there was an issue with the request or response. +// Use this endpoint to make a product price point the default for the product. // Note: Custom product price points are not able to be set as the default for a product. func (p *ProductPricePointsController) PromoteProductPricePointToDefault( - ctx context.Context, - productId int, - pricePointId int) ( - models.ApiResponse[models.ProductResponse], - error) { - req := p.prepareRequest( - ctx, - "PATCH", - fmt.Sprintf("/products/%v/price_points/%v/default.json", productId, pricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.ProductResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productId int, + pricePointId int) ( + models.ApiResponse[models.ProductResponse], + error) { + req := p.prepareRequest( + ctx, + "PATCH", + fmt.Sprintf("/products/%v/price_points/%v/default.json", productId, pricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.ProductResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductResponse](decoder) + return models.NewApiResponse(result, resp), err } -// BulkCreateProductPricePoints takes context, productId, body as parameters and -// returns an models.ApiResponse with models.BulkCreateProductPricePointsResponse data and -// an error if there was an issue with the request or response. +// BulkCreateProductPricePoints takes context, productId, body as parameters and +// returns an models.ApiResponse with models.BulkCreateProductPricePointsResponse data and +// an error if there was an issue with the request or response. // Use this endpoint to create multiple product price points in one request. func (p *ProductPricePointsController) BulkCreateProductPricePoints( - ctx context.Context, - productId int, - body *models.BulkCreateProductPricePointsRequest) ( - models.ApiResponse[models.BulkCreateProductPricePointsResponse], - error) { - req := p.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/products/%v/price_points/bulk.json", productId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'."}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.BulkCreateProductPricePointsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.BulkCreateProductPricePointsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productId int, + body *models.BulkCreateProductPricePointsRequest) ( + models.ApiResponse[models.BulkCreateProductPricePointsResponse], + error) { + req := p.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/products/%v/price_points/bulk.json", productId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'."}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.BulkCreateProductPricePointsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.BulkCreateProductPricePointsResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreateProductCurrencyPrices takes context, productPricePointId, body as parameters and -// returns an models.ApiResponse with models.CurrencyPricesResponse data and -// an error if there was an issue with the request or response. -// This endpoint allows you to create currency prices for a given currency that has been defined on the site level in your settings. -// When creating currency prices, they need to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. +// CreateProductCurrencyPrices takes context, productPricePointId, body as parameters and +// returns an models.ApiResponse with models.CurrencyPricesResponse data and +// an error if there was an issue with the request or response. +// This endpoint allows you to create currency prices for a given currency that has been defined on the site level in your settings. +// When creating currency prices, they need to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. // Note: Currency Prices are not able to be created for custom product price points. func (p *ProductPricePointsController) CreateProductCurrencyPrices( - ctx context.Context, - productPricePointId int, - body *models.CreateProductCurrencyPricesRequest) ( - models.ApiResponse[models.CurrencyPricesResponse], - error) { - req := p.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/product_price_points/%v/currency_prices.json", productPricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.CurrencyPricesResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CurrencyPricesResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productPricePointId int, + body *models.CreateProductCurrencyPricesRequest) ( + models.ApiResponse[models.CurrencyPricesResponse], + error) { + req := p.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/product_price_points/%v/currency_prices.json", productPricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.CurrencyPricesResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CurrencyPricesResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateProductCurrencyPrices takes context, productPricePointId, body as parameters and -// returns an models.ApiResponse with models.CurrencyPricesResponse data and -// an error if there was an issue with the request or response. -// This endpoint allows you to update the `price`s of currency prices for a given currency that exists on the product price point. -// When updating the pricing, it needs to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. +// UpdateProductCurrencyPrices takes context, productPricePointId, body as parameters and +// returns an models.ApiResponse with models.CurrencyPricesResponse data and +// an error if there was an issue with the request or response. +// This endpoint allows you to update the `price`s of currency prices for a given currency that exists on the product price point. +// When updating the pricing, it needs to mirror the structure of your primary pricing. If the product price point defines a trial and/or setup fee, each currency must also define a trial and/or setup fee. // Note: Currency Prices are not able to be updated for custom product price points. func (p *ProductPricePointsController) UpdateProductCurrencyPrices( - ctx context.Context, - productPricePointId int, - body *models.UpdateCurrencyPricesRequest) ( - models.ApiResponse[models.CurrencyPricesResponse], - error) { - req := p.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/product_price_points/%v/currency_prices.json", productPricePointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.CurrencyPricesResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CurrencyPricesResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productPricePointId int, + body *models.UpdateCurrencyPricesRequest) ( + models.ApiResponse[models.CurrencyPricesResponse], + error) { + req := p.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/product_price_points/%v/currency_prices.json", productPricePointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.CurrencyPricesResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CurrencyPricesResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListAllProductPricePoints takes context, direction, filterArchivedAt, filterDateField, filterEndDate, filterEndDatetime, filterIds, filterStartDate, filterStartDatetime, filterType, include, page, perPage as parameters and -// returns an models.ApiResponse with models.ListProductPricePointsResponse data and -// an error if there was an issue with the request or response. +// ListAllProductPricePointsInput represents the input of the ListAllProductPricePoints endpoint. +type ListAllProductPricePointsInput struct { + // Controls the order in which results are returned. + // Use in query `direction=asc`. + Direction *models.SortingDirection + // Allows fetching price points only if archived_at is present or not. Use in query: `filter[archived_at]=not_null`. + FilterArchivedAt *models.IncludeNotNull + // The type of filter you would like to apply to your search. Use in query: `filter[date_field]=created_at`. + FilterDateField *models.BasicDateField + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + FilterEndDate *time.Time + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. + FilterEndDatetime *time.Time + // Allows fetching price points with matching id based on provided values. Use in query: `filter[ids]=1,2,3`. + FilterIds []int + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns price points with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + FilterStartDate *time.Time + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns price points with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. + FilterStartDatetime *time.Time + // Allows fetching price points with matching type. Use in query: `filter[type]=catalog,custom`. + FilterType []models.PricePointType + // Allows including additional data in the response. Use in query: `include=currency_prices`. + Include *models.ListProductsPricePointsInclude + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int +} + +// ListAllProductPricePoints takes context, direction, filterArchivedAt, filterDateField, filterEndDate, filterEndDatetime, filterIds, filterStartDate, filterStartDatetime, filterType, include, page, perPage as parameters and +// returns an models.ApiResponse with models.ListProductPricePointsResponse data and +// an error if there was an issue with the request or response. // This method allows retrieval of a list of Products Price Points belonging to a Site. func (p *ProductPricePointsController) ListAllProductPricePoints( - ctx context.Context, - direction *models.SortingDirection, - filterArchivedAt *models.IncludeNotNull, - filterDateField *models.BasicDateField, - filterEndDate *time.Time, - filterEndDatetime *time.Time, - filterIds []int, - filterStartDate *time.Time, - filterStartDatetime *time.Time, - filterType []models.PricePointType, - include *models.ListProductsPricePointsInclude, - page *int, - perPage *int) ( - models.ApiResponse[models.ListProductPricePointsResponse], - error) { - req := p.prepareRequest(ctx, "GET", "/products_price_points.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - if direction != nil { - req.QueryParam("direction", *direction) - } - if filterArchivedAt != nil { - req.QueryParam("filter[archived_at]", *filterArchivedAt) - } - if filterDateField != nil { - req.QueryParam("filter[date_field]", *filterDateField) - } - if filterEndDate != nil { - req.QueryParam("filter[end_date]", filterEndDate.Format(models.DEFAULT_DATE)) - } - if filterEndDatetime != nil { - req.QueryParam("filter[end_datetime]", filterEndDatetime.Format(time.RFC3339)) - } - if filterIds != nil { - req.QueryParam("filter[ids]", filterIds) - } - if filterStartDate != nil { - req.QueryParam("filter[start_date]", filterStartDate.Format(models.DEFAULT_DATE)) - } - if filterStartDatetime != nil { - req.QueryParam("filter[start_datetime]", filterStartDatetime.Format(time.RFC3339)) - } - if filterType != nil { - req.QueryParam("filter[type]", filterType) - } - if include != nil { - req.QueryParam("include", *include) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - var result models.ListProductPricePointsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListProductPricePointsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListAllProductPricePointsInput) ( + models.ApiResponse[models.ListProductPricePointsResponse], + error) { + req := p.prepareRequest(ctx, "GET", "/products_price_points.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + if input.FilterArchivedAt != nil { + req.QueryParam("filter[archived_at]", *input.FilterArchivedAt) + } + if input.FilterDateField != nil { + req.QueryParam("filter[date_field]", *input.FilterDateField) + } + if input.FilterEndDate != nil { + req.QueryParam("filter[end_date]", input.FilterEndDate.Format(models.DEFAULT_DATE)) + } + if input.FilterEndDatetime != nil { + req.QueryParam("filter[end_datetime]", input.FilterEndDatetime.Format(time.RFC3339)) + } + if input.FilterIds != nil { + req.QueryParam("filter[ids]", input.FilterIds) + } + if input.FilterStartDate != nil { + req.QueryParam("filter[start_date]", input.FilterStartDate.Format(models.DEFAULT_DATE)) + } + if input.FilterStartDatetime != nil { + req.QueryParam("filter[start_datetime]", input.FilterStartDatetime.Format(time.RFC3339)) + } + if input.FilterType != nil { + req.QueryParam("filter[type]", input.FilterType) + } + if input.Include != nil { + req.QueryParam("include", *input.Include) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + var result models.ListProductPricePointsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListProductPricePointsResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/products_controller.go b/products_controller.go index 50eab7ae..a82d1902 100644 --- a/products_controller.go +++ b/products_controller.go @@ -1,235 +1,254 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "time" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "time" ) // ProductsController represents a controller struct. type ProductsController struct { - baseController + baseController } -// NewProductsController creates a new instance of ProductsController. +// NewProductsController creates a new instance of ProductsController. // It takes a baseController as a parameter and returns a pointer to the ProductsController. func NewProductsController(baseController baseController) *ProductsController { - productsController := ProductsController{baseController: baseController} - return &productsController + productsController := ProductsController{baseController: baseController} + return &productsController } -// CreateProduct takes context, productFamilyId, body as parameters and -// returns an models.ApiResponse with models.ProductResponse data and -// an error if there was an issue with the request or response. -// Use this method to create a product within your Chargify site. -// + [Products Documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405561405709) +// CreateProduct takes context, productFamilyId, body as parameters and +// returns an models.ApiResponse with models.ProductResponse data and +// an error if there was an issue with the request or response. +// Use this method to create a product within your Chargify site. +// + [Products Documentation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405561405709) // + [Changing a Subscription's Product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404225334669-Product-Changes-Migrations) func (p *ProductsController) CreateProduct( - ctx context.Context, - productFamilyId int, - body *models.CreateOrUpdateProductRequest) ( - models.ApiResponse[models.ProductResponse], - error) { - req := p.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/product_families/%v/products.json", productFamilyId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ProductResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productFamilyId int, + body *models.CreateOrUpdateProductRequest) ( + models.ApiResponse[models.ProductResponse], + error) { + req := p.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/product_families/%v/products.json", productFamilyId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ProductResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadProduct takes context, productId as parameters and -// returns an models.ApiResponse with models.ProductResponse data and -// an error if there was an issue with the request or response. +// ReadProduct takes context, productId as parameters and +// returns an models.ApiResponse with models.ProductResponse data and +// an error if there was an issue with the request or response. // This endpoint allows you to read the current details of a product that you've created in Chargify. func (p *ProductsController) ReadProduct( - ctx context.Context, - productId int) ( - models.ApiResponse[models.ProductResponse], - error) { - req := p.prepareRequest(ctx, "GET", fmt.Sprintf("/products/%v.json", productId)) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.ProductResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productId int) ( + models.ApiResponse[models.ProductResponse], + error) { + req := p.prepareRequest(ctx, "GET", fmt.Sprintf("/products/%v.json", productId)) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.ProductResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateProduct takes context, productId, body as parameters and -// returns an models.ApiResponse with models.ProductResponse data and -// an error if there was an issue with the request or response. -// Use this method to change aspects of an existing product. -// ### Input Attributes Update Notes -// + `update_return_params` The parameters we will append to your `update_return_url`. See Return URLs and Parameters -// ### Product Price Point +// UpdateProduct takes context, productId, body as parameters and +// returns an models.ApiResponse with models.ProductResponse data and +// an error if there was an issue with the request or response. +// Use this method to change aspects of an existing product. +// ### Input Attributes Update Notes +// + `update_return_params` The parameters we will append to your `update_return_url`. See Return URLs and Parameters +// ### Product Price Point // Updating a product using this endpoint will create a new price point and set it as the default price point for this product. If you should like to update an existing product price point, that must be done separately. func (p *ProductsController) UpdateProduct( - ctx context.Context, - productId int, - body *models.CreateOrUpdateProductRequest) ( - models.ApiResponse[models.ProductResponse], - error) { - req := p.prepareRequest(ctx, "PUT", fmt.Sprintf("/products/%v.json", productId)) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ProductResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productId int, + body *models.CreateOrUpdateProductRequest) ( + models.ApiResponse[models.ProductResponse], + error) { + req := p.prepareRequest(ctx, "PUT", fmt.Sprintf("/products/%v.json", productId)) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ProductResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ArchiveProduct takes context, productId as parameters and -// returns an models.ApiResponse with models.ProductResponse data and -// an error if there was an issue with the request or response. -// Sending a DELETE request to this endpoint will archive the product. All current subscribers will be unffected; their subscription/purchase will continue to be charged monthly. +// ArchiveProduct takes context, productId as parameters and +// returns an models.ApiResponse with models.ProductResponse data and +// an error if there was an issue with the request or response. +// Sending a DELETE request to this endpoint will archive the product. All current subscribers will be unffected; their subscription/purchase will continue to be charged monthly. // This will restrict the option to chose the product for purchase via the Billing Portal, as well as disable Public Signup Pages for the product. func (p *ProductsController) ArchiveProduct( - ctx context.Context, - productId int) ( - models.ApiResponse[models.ProductResponse], - error) { - req := p.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/products/%v.json", productId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.ProductResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + productId int) ( + models.ApiResponse[models.ProductResponse], + error) { + req := p.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/products/%v.json", productId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.ProductResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadProductByHandle takes context, apiHandle as parameters and -// returns an models.ApiResponse with models.ProductResponse data and -// an error if there was an issue with the request or response. +// ReadProductByHandle takes context, apiHandle as parameters and +// returns an models.ApiResponse with models.ProductResponse data and +// an error if there was an issue with the request or response. // This method allows to retrieve a Product object by its `api_handle`. func (p *ProductsController) ReadProductByHandle( - ctx context.Context, - apiHandle string) ( - models.ApiResponse[models.ProductResponse], - error) { - req := p.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/products/handle/%v.json", apiHandle), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.ProductResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProductResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + apiHandle string) ( + models.ApiResponse[models.ProductResponse], + error) { + req := p.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/products/handle/%v.json", apiHandle), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.ProductResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProductResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListProducts takes context, dateField, endDate, endDatetime, startDate, startDatetime, page, perPage, includeArchived, include, filterPrepaidProductPricePointProductPricePointId, filterUseSiteExchangeRate as parameters and -// returns an models.ApiResponse with []models.ProductResponse data and -// an error if there was an issue with the request or response. +// ListProductsInput represents the input of the ListProducts endpoint. +type ListProductsInput struct { + // The type of filter you would like to apply to your search. + // Use in query: `date_field=created_at`. + DateField *models.BasicDateField + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + EndDate *time.Time + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. + EndDatetime *time.Time + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns products with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + StartDate *time.Time + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns products with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. + StartDatetime *time.Time + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // Include archived products. Use in query: `include_archived=true`. + IncludeArchived *bool + // Allows including additional data in the response. Use in query `include=prepaid_product_price_point`. + Include *models.ListProductsInclude + // Allows fetching products only if a prepaid product price point is present or not. To use this filter you also have to include the following param in the request `include=prepaid_product_price_point`. Use in query `filter[prepaid_product_price_point][product_price_point_id]=not_null`. + FilterPrepaidProductPricePointProductPricePointId *models.IncludeNotNull + // Allows fetching products with matching use_site_exchange_rate based on provided value (refers to default price point). Use in query `filter[use_site_exchange_rate]=true`. + FilterUseSiteExchangeRate *bool +} + +// ListProducts takes context, dateField, endDate, endDatetime, startDate, startDatetime, page, perPage, includeArchived, include, filterPrepaidProductPricePointProductPricePointId, filterUseSiteExchangeRate as parameters and +// returns an models.ApiResponse with []models.ProductResponse data and +// an error if there was an issue with the request or response. // This method allows to retrieve a list of Products belonging to a Site. func (p *ProductsController) ListProducts( - ctx context.Context, - dateField *models.BasicDateField, - endDate *time.Time, - endDatetime *time.Time, - startDate *time.Time, - startDatetime *time.Time, - page *int, - perPage *int, - includeArchived *bool, - include *models.ListProductsInclude, - filterPrepaidProductPricePointProductPricePointId *models.IncludeNotNull, - filterUseSiteExchangeRate *bool) ( - models.ApiResponse[[]models.ProductResponse], - error) { - req := p.prepareRequest(ctx, "GET", "/products.json") - req.Authenticate(NewAuth("BasicAuth")) - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if endDate != nil { - req.QueryParam("end_date", endDate.Format(models.DEFAULT_DATE)) - } - if endDatetime != nil { - req.QueryParam("end_datetime", endDatetime.Format(time.RFC3339)) - } - if startDate != nil { - req.QueryParam("start_date", startDate.Format(models.DEFAULT_DATE)) - } - if startDatetime != nil { - req.QueryParam("start_datetime", startDatetime.Format(time.RFC3339)) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if includeArchived != nil { - req.QueryParam("include_archived", *includeArchived) - } - if include != nil { - req.QueryParam("include", *include) - } - if filterPrepaidProductPricePointProductPricePointId != nil { - req.QueryParam("filter[prepaid_product_price_point][product_price_point_id]", *filterPrepaidProductPricePointProductPricePointId) - } - if filterUseSiteExchangeRate != nil { - req.QueryParam("filter[use_site_exchange_rate]", *filterUseSiteExchangeRate) - } - var result []models.ProductResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.ProductResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListProductsInput) ( + models.ApiResponse[[]models.ProductResponse], + error) { + req := p.prepareRequest(ctx, "GET", "/products.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.EndDate != nil { + req.QueryParam("end_date", input.EndDate.Format(models.DEFAULT_DATE)) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", input.EndDatetime.Format(time.RFC3339)) + } + if input.StartDate != nil { + req.QueryParam("start_date", input.StartDate.Format(models.DEFAULT_DATE)) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", input.StartDatetime.Format(time.RFC3339)) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.IncludeArchived != nil { + req.QueryParam("include_archived", *input.IncludeArchived) + } + if input.Include != nil { + req.QueryParam("include", *input.Include) + } + if input.FilterPrepaidProductPricePointProductPricePointId != nil { + req.QueryParam("filter[prepaid_product_price_point][product_price_point_id]", *input.FilterPrepaidProductPricePointProductPricePointId) + } + if input.FilterUseSiteExchangeRate != nil { + req.QueryParam("filter[use_site_exchange_rate]", *input.FilterUseSiteExchangeRate) + } + var result []models.ProductResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.ProductResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/proforma_invoices_controller.go b/proforma_invoices_controller.go index 0fa4fc9b..6bab8366 100644 --- a/proforma_invoices_controller.go +++ b/proforma_invoices_controller.go @@ -1,387 +1,419 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" ) // ProformaInvoicesController represents a controller struct. type ProformaInvoicesController struct { - baseController + baseController } -// NewProformaInvoicesController creates a new instance of ProformaInvoicesController. +// NewProformaInvoicesController creates a new instance of ProformaInvoicesController. // It takes a baseController as a parameter and returns a pointer to the ProformaInvoicesController. func NewProformaInvoicesController(baseController baseController) *ProformaInvoicesController { - proformaInvoicesController := ProformaInvoicesController{baseController: baseController} - return &proformaInvoicesController + proformaInvoicesController := ProformaInvoicesController{baseController: baseController} + return &proformaInvoicesController } -// CreateConsolidatedProformaInvoice takes context, uid as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// This endpoint will trigger the creation of a consolidated proforma invoice asynchronously. It will return a 201 with no message, or a 422 with any errors. To find and view the new consolidated proforma invoice, you may poll the subscription group listing for proforma invoices; only one consolidated proforma invoice may be created per group at a time. -// If the information becomes outdated, simply void the old consolidated proforma invoice and generate a new one. -// ## Restrictions +// CreateConsolidatedProformaInvoice takes context, uid as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// This endpoint will trigger the creation of a consolidated proforma invoice asynchronously. It will return a 201 with no message, or a 422 with any errors. To find and view the new consolidated proforma invoice, you may poll the subscription group listing for proforma invoices; only one consolidated proforma invoice may be created per group at a time. +// If the information becomes outdated, simply void the old consolidated proforma invoice and generate a new one. +// ## Restrictions // Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be prepaid, and must be in a live state. func (p *ProformaInvoicesController) CreateConsolidatedProformaInvoice( - ctx context.Context, - uid string) ( - *http.Response, - error) { - req := p.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscription_groups/%v/proforma_invoices.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + uid string) ( + *http.Response, + error) { + req := p.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscription_groups/%v/proforma_invoices.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err +} + +// ListSubscriptionGroupProformaInvoicesInput represents the input of the ListSubscriptionGroupProformaInvoices endpoint. +type ListSubscriptionGroupProformaInvoicesInput struct { + // The uid of the subscription group + Uid string + // Include line items data + LineItems *bool + // Include discounts data + Discounts *bool + // Include taxes data + Taxes *bool + // Include credits data + Credits *bool + // Include payments data + Payments *bool + // Include custom fields data + CustomFields *bool } -// ListSubscriptionGroupProformaInvoices takes context, uid, lineItems, discounts, taxes, credits, payments, customFields as parameters and -// returns an models.ApiResponse with models.ListProformaInvoicesResponse data and -// an error if there was an issue with the request or response. -// Only proforma invoices with a `consolidation_level` of parent are returned. +// ListSubscriptionGroupProformaInvoices takes context, uid, lineItems, discounts, taxes, credits, payments, customFields as parameters and +// returns an models.ApiResponse with models.ListProformaInvoicesResponse data and +// an error if there was an issue with the request or response. +// Only proforma invoices with a `consolidation_level` of parent are returned. // By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to true. func (p *ProformaInvoicesController) ListSubscriptionGroupProformaInvoices( - ctx context.Context, - uid string, - lineItems *bool, - discounts *bool, - taxes *bool, - credits *bool, - payments *bool, - customFields *bool) ( - models.ApiResponse[models.ListProformaInvoicesResponse], - error) { - req := p.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscription_groups/%v/proforma_invoices.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - if lineItems != nil { - req.QueryParam("line_items", *lineItems) - } - if discounts != nil { - req.QueryParam("discounts", *discounts) - } - if taxes != nil { - req.QueryParam("taxes", *taxes) - } - if credits != nil { - req.QueryParam("credits", *credits) - } - if payments != nil { - req.QueryParam("payments", *payments) - } - if customFields != nil { - req.QueryParam("custom_fields", *customFields) - } - - var result models.ListProformaInvoicesResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListProformaInvoicesResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListSubscriptionGroupProformaInvoicesInput) ( + models.ApiResponse[models.ListProformaInvoicesResponse], + error) { + req := p.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscription_groups/%v/proforma_invoices.json", input.Uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + if input.LineItems != nil { + req.QueryParam("line_items", *input.LineItems) + } + if input.Discounts != nil { + req.QueryParam("discounts", *input.Discounts) + } + if input.Taxes != nil { + req.QueryParam("taxes", *input.Taxes) + } + if input.Credits != nil { + req.QueryParam("credits", *input.Credits) + } + if input.Payments != nil { + req.QueryParam("payments", *input.Payments) + } + if input.CustomFields != nil { + req.QueryParam("custom_fields", *input.CustomFields) + } + + var result models.ListProformaInvoicesResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListProformaInvoicesResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadProformaInvoice takes context, proformaInvoiceUid as parameters and -// returns an models.ApiResponse with models.ProformaInvoice data and -// an error if there was an issue with the request or response. -// Use this endpoint to read the details of an existing proforma invoice. -// ## Restrictions +// ReadProformaInvoice takes context, proformaInvoiceUid as parameters and +// returns an models.ApiResponse with models.ProformaInvoice data and +// an error if there was an issue with the request or response. +// Use this endpoint to read the details of an existing proforma invoice. +// ## Restrictions // Proforma invoices are only available on Relationship Invoicing sites. func (p *ProformaInvoicesController) ReadProformaInvoice( - ctx context.Context, - proformaInvoiceUid string) ( - models.ApiResponse[models.ProformaInvoice], - error) { - req := p.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/proforma_invoices/%v.json", proformaInvoiceUid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - - var result models.ProformaInvoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProformaInvoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + proformaInvoiceUid string) ( + models.ApiResponse[models.ProformaInvoice], + error) { + req := p.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/proforma_invoices/%v.json", proformaInvoiceUid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + + var result models.ProformaInvoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProformaInvoice](decoder) + return models.NewApiResponse(result, resp), err } -// CreateProformaInvoice takes context, subscriptionId as parameters and -// returns an models.ApiResponse with models.ProformaInvoice data and -// an error if there was an issue with the request or response. -// This endpoint will create a proforma invoice and return it as a response. If the information becomes outdated, simply void the old proforma invoice and generate a new one. -// If you would like to preview the next billing amounts without generating a full proforma invoice, please use the renewal preview endpoint. -// ## Restrictions +// CreateProformaInvoice takes context, subscriptionId as parameters and +// returns an models.ApiResponse with models.ProformaInvoice data and +// an error if there was an issue with the request or response. +// This endpoint will create a proforma invoice and return it as a response. If the information becomes outdated, simply void the old proforma invoice and generate a new one. +// If you would like to preview the next billing amounts without generating a full proforma invoice, please use the renewal preview endpoint. +// ## Restrictions // Proforma invoices are only available on Relationship Invoicing sites. To create a proforma invoice, the subscription must not be in a group, must not be prepaid, and must be in a live state. func (p *ProformaInvoicesController) CreateProformaInvoice( - ctx context.Context, - subscriptionId int) ( - models.ApiResponse[models.ProformaInvoice], - error) { - req := p.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/proforma_invoices.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.ProformaInvoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProformaInvoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int) ( + models.ApiResponse[models.ProformaInvoice], + error) { + req := p.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/proforma_invoices.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.ProformaInvoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProformaInvoice](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListProformaInvoicesInput represents the input of the ListProformaInvoices endpoint. +type ListProformaInvoicesInput struct { + // The Chargify id of the subscription + SubscriptionId int + // The beginning date range for the invoice's Due Date, in the YYYY-MM-DD format. + StartDate *string + // The ending date range for the invoice's Due Date, in the YYYY-MM-DD format. + EndDate *string + // The current status of the invoice. Allowed Values: draft, open, paid, pending, voided + Status *models.ProformaInvoiceStatus + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The sort direction of the returned invoices. + Direction *models.Direction + // Include line items data + LineItems *bool + // Include discounts data + Discounts *bool + // Include taxes data + Taxes *bool + // Include credits data + Credits *bool + // Include payments data + Payments *bool + // Include custom fields data + CustomFields *bool } -// ListProformaInvoices takes context, subscriptionId, startDate, endDate, status, page, perPage, direction, lineItems, discounts, taxes, credits, payments, customFields as parameters and -// returns an models.ApiResponse with models.ListProformaInvoicesResponse data and -// an error if there was an issue with the request or response. +// ListProformaInvoices takes context, subscriptionId, startDate, endDate, status, page, perPage, direction, lineItems, discounts, taxes, credits, payments, customFields as parameters and +// returns an models.ApiResponse with models.ListProformaInvoicesResponse data and +// an error if there was an issue with the request or response. // By default, proforma invoices returned on the index will only include totals, not detailed breakdowns for `line_items`, `discounts`, `taxes`, `credits`, `payments`, or `custom_fields`. To include breakdowns, pass the specific field as a key in the query with a value set to `true`. func (p *ProformaInvoicesController) ListProformaInvoices( - ctx context.Context, - subscriptionId int, - startDate *string, - endDate *string, - status *models.ProformaInvoiceStatus, - page *int, - perPage *int, - direction *models.Direction, - lineItems *bool, - discounts *bool, - taxes *bool, - credits *bool, - payments *bool, - customFields *bool) ( - models.ApiResponse[models.ListProformaInvoicesResponse], - error) { - req := p.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v/proforma_invoices.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if startDate != nil { - req.QueryParam("start_date", *startDate) - } - if endDate != nil { - req.QueryParam("end_date", *endDate) - } - if status != nil { - req.QueryParam("status", *status) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - if lineItems != nil { - req.QueryParam("line_items", *lineItems) - } - if discounts != nil { - req.QueryParam("discounts", *discounts) - } - if taxes != nil { - req.QueryParam("taxes", *taxes) - } - if credits != nil { - req.QueryParam("credits", *credits) - } - if payments != nil { - req.QueryParam("payments", *payments) - } - if customFields != nil { - req.QueryParam("custom_fields", *customFields) - } - - var result models.ListProformaInvoicesResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListProformaInvoicesResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListProformaInvoicesInput) ( + models.ApiResponse[models.ListProformaInvoicesResponse], + error) { + req := p.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v/proforma_invoices.json", input.SubscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.StartDate != nil { + req.QueryParam("start_date", *input.StartDate) + } + if input.EndDate != nil { + req.QueryParam("end_date", *input.EndDate) + } + if input.Status != nil { + req.QueryParam("status", *input.Status) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + if input.LineItems != nil { + req.QueryParam("line_items", *input.LineItems) + } + if input.Discounts != nil { + req.QueryParam("discounts", *input.Discounts) + } + if input.Taxes != nil { + req.QueryParam("taxes", *input.Taxes) + } + if input.Credits != nil { + req.QueryParam("credits", *input.Credits) + } + if input.Payments != nil { + req.QueryParam("payments", *input.Payments) + } + if input.CustomFields != nil { + req.QueryParam("custom_fields", *input.CustomFields) + } + + var result models.ListProformaInvoicesResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListProformaInvoicesResponse](decoder) + return models.NewApiResponse(result, resp), err } -// VoidProformaInvoice takes context, proformaInvoiceUid, body as parameters and -// returns an models.ApiResponse with models.ProformaInvoice data and -// an error if there was an issue with the request or response. -// This endpoint will void a proforma invoice that has the status "draft". -// ## Restrictions -// Proforma invoices are only available on Relationship Invoicing sites. -// Only proforma invoices that have the appropriate status may be reopened. If the invoice identified by {uid} does not have the appropriate status, the response will have HTTP status code 422 and an error message. +// VoidProformaInvoice takes context, proformaInvoiceUid, body as parameters and +// returns an models.ApiResponse with models.ProformaInvoice data and +// an error if there was an issue with the request or response. +// This endpoint will void a proforma invoice that has the status "draft". +// ## Restrictions +// Proforma invoices are only available on Relationship Invoicing sites. +// Only proforma invoices that have the appropriate status may be reopened. If the invoice identified by {uid} does not have the appropriate status, the response will have HTTP status code 422 and an error message. // A reason for the void operation is required to be included in the request body. If one is not provided, the response will have HTTP status code 422 and an error message. func (p *ProformaInvoicesController) VoidProformaInvoice( - ctx context.Context, - proformaInvoiceUid string, - body *models.VoidInvoiceRequest) ( - models.ApiResponse[models.ProformaInvoice], - error) { - req := p.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/proforma_invoices/%v/void.json", proformaInvoiceUid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ProformaInvoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProformaInvoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + proformaInvoiceUid string, + body *models.VoidInvoiceRequest) ( + models.ApiResponse[models.ProformaInvoice], + error) { + req := p.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/proforma_invoices/%v/void.json", proformaInvoiceUid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ProformaInvoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProformaInvoice](decoder) + return models.NewApiResponse(result, resp), err } -// PreviewProformaInvoice takes context, subscriptionId as parameters and -// returns an models.ApiResponse with models.ProformaInvoice data and -// an error if there was an issue with the request or response. -// Return a preview of the data that will be included on a given subscription's proforma invoice if one were to be generated. It will have similar line items and totals as a renewal preview, but the response will be presented in the format of a proforma invoice. Consequently it will include additional information such as the name and addresses that will appear on the proforma invoice. -// The preview endpoint is subject to all the same conditions as the proforma invoice endpoint. For example, previews are only available on the Relationship Invoicing architecture, and previews cannot be made for end-of-life subscriptions. -// If all the data returned in the preview is as expected, you may then create a static proforma invoice and send it to your customer. The data within a preview will not be saved and will not be accessible after the call is made. +// PreviewProformaInvoice takes context, subscriptionId as parameters and +// returns an models.ApiResponse with models.ProformaInvoice data and +// an error if there was an issue with the request or response. +// Return a preview of the data that will be included on a given subscription's proforma invoice if one were to be generated. It will have similar line items and totals as a renewal preview, but the response will be presented in the format of a proforma invoice. Consequently it will include additional information such as the name and addresses that will appear on the proforma invoice. +// The preview endpoint is subject to all the same conditions as the proforma invoice endpoint. For example, previews are only available on the Relationship Invoicing architecture, and previews cannot be made for end-of-life subscriptions. +// If all the data returned in the preview is as expected, you may then create a static proforma invoice and send it to your customer. The data within a preview will not be saved and will not be accessible after the call is made. // Alternatively, if you have some proforma invoices already, you may make a preview call to determine whether any billing information for the subscription's upcoming renewal has changed. func (p *ProformaInvoicesController) PreviewProformaInvoice( - ctx context.Context, - subscriptionId int) ( - models.ApiResponse[models.ProformaInvoice], - error) { - req := p.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/proforma_invoices/preview.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.ProformaInvoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProformaInvoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int) ( + models.ApiResponse[models.ProformaInvoice], + error) { + req := p.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/proforma_invoices/preview.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.ProformaInvoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProformaInvoice](decoder) + return models.NewApiResponse(result, resp), err } -// CreateSignupProformaInvoice takes context, body as parameters and -// returns an models.ApiResponse with models.ProformaInvoice data and -// an error if there was an issue with the request or response. -// This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoices or preview prepaid subscriptions. -// Create a proforma invoice to preview costs before a subscription's signup. Like other proforma invoices, it can be emailed to the customer, voided, and publicly viewed on the chargifypay domain. -// Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. +// CreateSignupProformaInvoice takes context, body as parameters and +// returns an models.ApiResponse with models.ProformaInvoice data and +// an error if there was an issue with the request or response. +// This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoices or preview prepaid subscriptions. +// Create a proforma invoice to preview costs before a subscription's signup. Like other proforma invoices, it can be emailed to the customer, voided, and publicly viewed on the chargifypay domain. +// Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. // A product and customer first name, last name, and email are the minimum requirements. We recommend associating the proforma invoice with a customer_id to easily find their proforma invoices, since the subscription_id will always be blank. func (p *ProformaInvoicesController) CreateSignupProformaInvoice( - ctx context.Context, - body *models.CreateSubscriptionRequest) ( - models.ApiResponse[models.ProformaInvoice], - error) { - req := p.prepareRequest(ctx, "POST", "/subscriptions/proforma_invoices.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "400": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewProformaBadRequestErrorResponse}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.ProformaInvoice - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ProformaInvoice](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.CreateSubscriptionRequest) ( + models.ApiResponse[models.ProformaInvoice], + error) { + req := p.prepareRequest(ctx, "POST", "/subscriptions/proforma_invoices.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "400": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewProformaBadRequestErrorResponse}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.ProformaInvoice + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ProformaInvoice](decoder) + return models.NewApiResponse(result, resp), err } -// PreviewSignupProformaInvoice takes context, include, body as parameters and -// returns an models.ApiResponse with models.SignupProformaPreviewResponse data and -// an error if there was an issue with the request or response. -// This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoice previews or preview prepaid subscriptions. -// Create a signup preview in the format of a proforma invoice to preview costs before a subscription's signup. You have the option of optionally previewing the first renewal's costs as well. The proforma invoice preview will not be persisted. -// Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. +// PreviewSignupProformaInvoice takes context, include, body as parameters and +// returns an models.ApiResponse with models.SignupProformaPreviewResponse data and +// an error if there was an issue with the request or response. +// This endpoint is only available for Relationship Invoicing sites. It cannot be used to create consolidated proforma invoice previews or preview prepaid subscriptions. +// Create a signup preview in the format of a proforma invoice to preview costs before a subscription's signup. You have the option of optionally previewing the first renewal's costs as well. The proforma invoice preview will not be persisted. +// Pass a payload that resembles a subscription create or signup preview request. For example, you can specify components, coupons/a referral, offers, custom pricing, and an existing customer or payment profile to populate a shipping or billing address. // A product and customer first name, last name, and email are the minimum requirements. func (p *ProformaInvoicesController) PreviewSignupProformaInvoice( - ctx context.Context, - include *models.CreateSignupProformaPreviewInclude, - body *models.CreateSubscriptionRequest) ( - models.ApiResponse[models.SignupProformaPreviewResponse], - error) { - req := p.prepareRequest( - ctx, - "POST", - "/subscriptions/proforma_invoices/preview.json", - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "400": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewProformaBadRequestErrorResponse}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, - }) - req.Header("Content-Type", "application/json") - if include != nil { - req.QueryParam("include", *include) - } - if body != nil { - req.Json(*body) - } - var result models.SignupProformaPreviewResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SignupProformaPreviewResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + include *models.CreateSignupProformaPreviewInclude, + body *models.CreateSubscriptionRequest) ( + models.ApiResponse[models.SignupProformaPreviewResponse], + error) { + req := p.prepareRequest( + ctx, + "POST", + "/subscriptions/proforma_invoices/preview.json", + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "400": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewProformaBadRequestErrorResponse}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, + }) + req.Header("Content-Type", "application/json") + if include != nil { + req.QueryParam("include", *include) + } + if body != nil { + req.Json(body) + } + var result models.SignupProformaPreviewResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SignupProformaPreviewResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/reason_codes_controller.go b/reason_codes_controller.go index 95f98621..8fda25fe 100644 --- a/reason_codes_controller.go +++ b/reason_codes_controller.go @@ -1,177 +1,186 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" ) // ReasonCodesController represents a controller struct. type ReasonCodesController struct { - baseController + baseController } -// NewReasonCodesController creates a new instance of ReasonCodesController. +// NewReasonCodesController creates a new instance of ReasonCodesController. // It takes a baseController as a parameter and returns a pointer to the ReasonCodesController. func NewReasonCodesController(baseController baseController) *ReasonCodesController { - reasonCodesController := ReasonCodesController{baseController: baseController} - return &reasonCodesController + reasonCodesController := ReasonCodesController{baseController: baseController} + return &reasonCodesController } -// CreateReasonCode takes context, body as parameters and -// returns an models.ApiResponse with models.ReasonCodeResponse data and -// an error if there was an issue with the request or response. -// # Reason Codes Intro -// ReasonCodes are a way to gain a high level view of why your customers are cancelling the subcription to your product or service. -// Add a set of churn reason codes to be displayed in-app and/or the Chargify Billing Portal. As your subscribers decide to cancel their subscription, learn why they decided to cancel. -// ## Reason Code Documentation -// Full documentation on how Reason Codes operate within Chargify can be located under the following links. -// [Churn Reason Codes](https://chargify.zendesk.com/hc/en-us/articles/4407896775579#churn-reason-codes) -// ## Create Reason Code +// CreateReasonCode takes context, body as parameters and +// returns an models.ApiResponse with models.ReasonCodeResponse data and +// an error if there was an issue with the request or response. +// # Reason Codes Intro +// ReasonCodes are a way to gain a high level view of why your customers are cancelling the subcription to your product or service. +// Add a set of churn reason codes to be displayed in-app and/or the Chargify Billing Portal. As your subscribers decide to cancel their subscription, learn why they decided to cancel. +// ## Reason Code Documentation +// Full documentation on how Reason Codes operate within Chargify can be located under the following links. +// [Churn Reason Codes](https://chargify.zendesk.com/hc/en-us/articles/4407896775579#churn-reason-codes) +// ## Create Reason Code // This method gives a merchant the option to create a reason codes for a given Site. func (r *ReasonCodesController) CreateReasonCode( - ctx context.Context, - body *models.CreateReasonCodeRequest) ( - models.ApiResponse[models.ReasonCodeResponse], - error) { - req := r.prepareRequest(ctx, "POST", "/reason_codes.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.ReasonCodeResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ReasonCodeResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.CreateReasonCodeRequest) ( + models.ApiResponse[models.ReasonCodeResponse], + error) { + req := r.prepareRequest(ctx, "POST", "/reason_codes.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.ReasonCodeResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ReasonCodeResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListReasonCodesInput represents the input of the ListReasonCodes endpoint. +type ListReasonCodesInput struct { + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int } -// ListReasonCodes takes context, page, perPage as parameters and -// returns an models.ApiResponse with []models.ReasonCodeResponse data and -// an error if there was an issue with the request or response. +// ListReasonCodes takes context, page, perPage as parameters and +// returns an models.ApiResponse with []models.ReasonCodeResponse data and +// an error if there was an issue with the request or response. // This method gives a merchant the option to retrieve a list of all of the current churn codes for a given site. func (r *ReasonCodesController) ListReasonCodes( - ctx context.Context, - page *int, - perPage *int) ( - models.ApiResponse[[]models.ReasonCodeResponse], - error) { - req := r.prepareRequest(ctx, "GET", "/reason_codes.json") - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - var result []models.ReasonCodeResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.ReasonCodeResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListReasonCodesInput) ( + models.ApiResponse[[]models.ReasonCodeResponse], + error) { + req := r.prepareRequest(ctx, "GET", "/reason_codes.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + var result []models.ReasonCodeResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.ReasonCodeResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadReasonCode takes context, reasonCodeId as parameters and -// returns an models.ApiResponse with models.ReasonCodeResponse data and -// an error if there was an issue with the request or response. +// ReadReasonCode takes context, reasonCodeId as parameters and +// returns an models.ApiResponse with models.ReasonCodeResponse data and +// an error if there was an issue with the request or response. // This method gives a merchant the option to retrieve a list of a particular code for a given Site by providing the unique numerical ID of the code. func (r *ReasonCodesController) ReadReasonCode( - ctx context.Context, - reasonCodeId int) ( - models.ApiResponse[models.ReasonCodeResponse], - error) { - req := r.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/reason_codes/%v.json", reasonCodeId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - - var result models.ReasonCodeResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ReasonCodeResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + reasonCodeId int) ( + models.ApiResponse[models.ReasonCodeResponse], + error) { + req := r.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/reason_codes/%v.json", reasonCodeId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + + var result models.ReasonCodeResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ReasonCodeResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateReasonCode takes context, reasonCodeId, body as parameters and -// returns an models.ApiResponse with models.ReasonCodeResponse data and -// an error if there was an issue with the request or response. +// UpdateReasonCode takes context, reasonCodeId, body as parameters and +// returns an models.ApiResponse with models.ReasonCodeResponse data and +// an error if there was an issue with the request or response. // This method gives a merchant the option to update an existing reason code for a given site. func (r *ReasonCodesController) UpdateReasonCode( - ctx context.Context, - reasonCodeId int, - body *models.UpdateReasonCodeRequest) ( - models.ApiResponse[models.ReasonCodeResponse], - error) { - req := r.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/reason_codes/%v.json", reasonCodeId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ReasonCodeResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ReasonCodeResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + reasonCodeId int, + body *models.UpdateReasonCodeRequest) ( + models.ApiResponse[models.ReasonCodeResponse], + error) { + req := r.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/reason_codes/%v.json", reasonCodeId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ReasonCodeResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ReasonCodeResponse](decoder) + return models.NewApiResponse(result, resp), err } -// DeleteReasonCode takes context, reasonCodeId as parameters and -// returns an models.ApiResponse with models.ReasonCodesJsonResponse data and -// an error if there was an issue with the request or response. +// DeleteReasonCode takes context, reasonCodeId as parameters and +// returns an models.ApiResponse with models.ReasonCodesJsonResponse data and +// an error if there was an issue with the request or response. // This method gives a merchant the option to delete one reason code from the Churn Reason Codes. This code will be immediately removed. This action is not reversable. func (r *ReasonCodesController) DeleteReasonCode( - ctx context.Context, - reasonCodeId int) ( - models.ApiResponse[models.ReasonCodesJsonResponse], - error) { - req := r.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/reason_codes/%v.json", reasonCodeId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - - var result models.ReasonCodesJsonResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ReasonCodesJsonResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + reasonCodeId int) ( + models.ApiResponse[models.ReasonCodesJsonResponse], + error) { + req := r.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/reason_codes/%v.json", reasonCodeId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + + var result models.ReasonCodesJsonResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ReasonCodesJsonResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/sales_commissions_controller.go b/sales_commissions_controller.go index bc7d6df4..a171c61e 100644 --- a/sales_commissions_controller.go +++ b/sales_commissions_controller.go @@ -1,159 +1,181 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/models" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/models" ) // SalesCommissionsController represents a controller struct. type SalesCommissionsController struct { - baseController + baseController } -// NewSalesCommissionsController creates a new instance of SalesCommissionsController. +// NewSalesCommissionsController creates a new instance of SalesCommissionsController. // It takes a baseController as a parameter and returns a pointer to the SalesCommissionsController. func NewSalesCommissionsController(baseController baseController) *SalesCommissionsController { - salesCommissionsController := SalesCommissionsController{baseController: baseController} - return &salesCommissionsController + salesCommissionsController := SalesCommissionsController{baseController: baseController} + return &salesCommissionsController } -// ListSalesCommissionSettings takes context, sellerId, authorization, liveMode, page, perPage as parameters and -// returns an models.ApiResponse with []models.SaleRepSettings data and -// an error if there was an issue with the request or response. -// Endpoint returns subscriptions with associated sales reps -// ## Modified Authentication Process -// The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). -// Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. +// ListSalesCommissionSettingsInput represents the input of the ListSalesCommissionSettings endpoint. +type ListSalesCommissionSettingsInput struct { + // The Chargify id of your seller account + SellerId string + // For authorization use user API key. See details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). + Authorization *string + // This parameter indicates if records should be fetched from live mode sites. Default value is true. + LiveMode *bool + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 100. + PerPage *int +} + +// ListSalesCommissionSettings takes context, sellerId, authorization, liveMode, page, perPage as parameters and +// returns an models.ApiResponse with []models.SaleRepSettings data and +// an error if there was an issue with the request or response. +// Endpoint returns subscriptions with associated sales reps +// ## Modified Authentication Process +// The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). +// Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. // > Note: The request is at seller level, it means `<>` variable will be replaced by `app` func (s *SalesCommissionsController) ListSalesCommissionSettings( - ctx context.Context, - sellerId string, - authorization *string, - liveMode *bool, - page *int, - perPage *int) ( - models.ApiResponse[[]models.SaleRepSettings], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/sellers/%v/sales_commission_settings.json", sellerId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if authorization != nil { - req.Header("Authorization", *authorization) - } - if liveMode != nil { - req.QueryParam("live_mode", *liveMode) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - - var result []models.SaleRepSettings - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.SaleRepSettings](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListSalesCommissionSettingsInput) ( + models.ApiResponse[[]models.SaleRepSettings], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/sellers/%v/sales_commission_settings.json", input.SellerId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.Authorization != nil { + req.Header("Authorization", *input.Authorization) + } + if input.LiveMode != nil { + req.QueryParam("live_mode", *input.LiveMode) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + + var result []models.SaleRepSettings + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.SaleRepSettings](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListSalesRepsInput represents the input of the ListSalesReps endpoint. +type ListSalesRepsInput struct { + // The Chargify id of your seller account + SellerId string + // For authorization use user API key. See details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). + Authorization *string + // This parameter indicates if records should be fetched from live mode sites. Default value is true. + LiveMode *bool + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 100. + PerPage *int } -// ListSalesReps takes context, sellerId, authorization, liveMode, page, perPage as parameters and -// returns an models.ApiResponse with []models.ListSaleRepItem data and -// an error if there was an issue with the request or response. -// Endpoint returns sales rep list with details -// ## Modified Authentication Process -// The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). -// Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. +// ListSalesReps takes context, sellerId, authorization, liveMode, page, perPage as parameters and +// returns an models.ApiResponse with []models.ListSaleRepItem data and +// an error if there was an issue with the request or response. +// Endpoint returns sales rep list with details +// ## Modified Authentication Process +// The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). +// Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. // > Note: The request is at seller level, it means `<>` variable will be replaced by `app` func (s *SalesCommissionsController) ListSalesReps( - ctx context.Context, - sellerId string, - authorization *string, - liveMode *bool, - page *int, - perPage *int) ( - models.ApiResponse[[]models.ListSaleRepItem], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/sellers/%v/sales_reps.json", sellerId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if authorization != nil { - req.Header("Authorization", *authorization) - } - if liveMode != nil { - req.QueryParam("live_mode", *liveMode) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - - var result []models.ListSaleRepItem - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.ListSaleRepItem](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListSalesRepsInput) ( + models.ApiResponse[[]models.ListSaleRepItem], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/sellers/%v/sales_reps.json", input.SellerId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.Authorization != nil { + req.Header("Authorization", *input.Authorization) + } + if input.LiveMode != nil { + req.QueryParam("live_mode", *input.LiveMode) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + + var result []models.ListSaleRepItem + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.ListSaleRepItem](decoder) + return models.NewApiResponse(result, resp), err } -// ReadSalesRep takes context, sellerId, salesRepId, authorization, liveMode, page, perPage as parameters and -// returns an models.ApiResponse with models.SaleRep data and -// an error if there was an issue with the request or response. -// Endpoint returns sales rep and attached subscriptions details. -// ## Modified Authentication Process -// The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). -// Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. +// ReadSalesRep takes context, sellerId, salesRepId, authorization, liveMode, page, perPage as parameters and +// returns an models.ApiResponse with models.SaleRep data and +// an error if there was an issue with the request or response. +// Endpoint returns sales rep and attached subscriptions details. +// ## Modified Authentication Process +// The Sales Commission API differs from other Chargify API endpoints. This resource is associated with the seller itself. Up to now all available resources were at the level of the site, therefore creating the API Key per site was a sufficient solution. To share resources at the seller level, a new authentication method was introduced, which is user authentication. Creating an API Key for a user is a required step to correctly use the Sales Commission API, more details [here](https://developers.chargify.com/docs/developer-docs/ZG9jOjMyNzk5NTg0-2020-04-20-new-api-authentication). +// Access to the Sales Commission API endpoints is available to users with financial access, where the seller has the Advanced Analytics component enabled. For further information on getting access to Advanced Analytics please contact Chargify support. // > Note: The request is at seller level, it means `<>` variable will be replaced by `app` func (s *SalesCommissionsController) ReadSalesRep( - ctx context.Context, - sellerId string, - salesRepId string, - authorization *string, - liveMode *bool, - page *int, - perPage *int) ( - models.ApiResponse[models.SaleRep], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/sellers/%v/sales_reps/%v.json", sellerId, salesRepId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if authorization != nil { - req.Header("Authorization", *authorization) - } - if liveMode != nil { - req.QueryParam("live_mode", *liveMode) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - - var result models.SaleRep - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SaleRep](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + sellerId string, + salesRepId string, + authorization *string, + liveMode *bool, + page *int, + perPage *int) ( + models.ApiResponse[models.SaleRep], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/sellers/%v/sales_reps/%v.json", sellerId, salesRepId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if authorization != nil { + req.Header("Authorization", *authorization) + } + if liveMode != nil { + req.QueryParam("live_mode", *liveMode) + } + if page != nil { + req.QueryParam("page", *page) + } + if perPage != nil { + req.QueryParam("per_page", *perPage) + } + + var result models.SaleRep + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SaleRep](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/sites_controller.go b/sites_controller.go index d9828f87..2c8912bf 100644 --- a/sites_controller.go +++ b/sites_controller.go @@ -1,98 +1,107 @@ package advancedbilling import ( - "context" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" + "context" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" ) // SitesController represents a controller struct. type SitesController struct { - baseController + baseController } -// NewSitesController creates a new instance of SitesController. +// NewSitesController creates a new instance of SitesController. // It takes a baseController as a parameter and returns a pointer to the SitesController. func NewSitesController(baseController baseController) *SitesController { - sitesController := SitesController{baseController: baseController} - return &sitesController + sitesController := SitesController{baseController: baseController} + return &sitesController } -// ReadSite takes context as parameters and -// returns an models.ApiResponse with models.SiteResponse data and -// an error if there was an issue with the request or response. -// This endpoint allows you to fetch some site data. -// Full documentation on Sites in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407870738587). -// Specifically, the [Clearing Site Data](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405428327309) section is extremely relevant to this endpoint documentation. -// #### Relationship invoicing enabled -// If site has RI enabled then you will see more settings like: -// "customer_hierarchy_enabled": true, -// "whopays_enabled": true, -// "whopays_default_payer": "self" -// You can read more about these settings here: +// ReadSite takes context as parameters and +// returns an models.ApiResponse with models.SiteResponse data and +// an error if there was an issue with the request or response. +// This endpoint allows you to fetch some site data. +// Full documentation on Sites in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407870738587). +// Specifically, the [Clearing Site Data](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405428327309) section is extremely relevant to this endpoint documentation. +// #### Relationship invoicing enabled +// If site has RI enabled then you will see more settings like: +// "customer_hierarchy_enabled": true, +// "whopays_enabled": true, +// "whopays_default_payer": "self" +// You can read more about these settings here: // [Who Pays & Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) func (s *SitesController) ReadSite(ctx context.Context) ( - models.ApiResponse[models.SiteResponse], - error) { - req := s.prepareRequest(ctx, "GET", "/site.json") - req.Authenticate(NewAuth("BasicAuth")) - var result models.SiteResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SiteResponse](decoder) - return models.NewApiResponse(result, resp), err + models.ApiResponse[models.SiteResponse], + error) { + req := s.prepareRequest(ctx, "GET", "/site.json") + req.Authenticate(NewAuth("BasicAuth")) + var result models.SiteResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SiteResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ClearSite takes context, cleanupScope as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// This call is asynchronous and there may be a delay before the site data is fully deleted. If you are clearing site data for an automated test, you will need to build in a delay and/or check that there are no products, etc., in the site before proceeding. +// ClearSite takes context, cleanupScope as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// This call is asynchronous and there may be a delay before the site data is fully deleted. If you are clearing site data for an automated test, you will need to build in a delay and/or check that there are no products, etc., in the site before proceeding. // **This functionality will only work on sites in TEST mode. Attempts to perform this on sites in “live” mode will result in a response of 403 FORBIDDEN.** func (s *SitesController) ClearSite( - ctx context.Context, - cleanupScope *models.CleanupScope) ( - *http.Response, - error) { - req := s.prepareRequest(ctx, "POST", "/sites/clear_data.json") - req.Authenticate(NewAuth("BasicAuth")) - if cleanupScope != nil { - req.QueryParam("cleanup_scope", *cleanupScope) - } - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + cleanupScope *models.CleanupScope) ( + *http.Response, + error) { + req := s.prepareRequest(ctx, "POST", "/sites/clear_data.json") + req.Authenticate(NewAuth("BasicAuth")) + if cleanupScope != nil { + req.QueryParam("cleanup_scope", *cleanupScope) + } + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err +} + +// ListChargifyJsPublicKeysInput represents the input of the ListChargifyJsPublicKeys endpoint. +type ListChargifyJsPublicKeysInput struct { + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int } -// ListChargifyJsPublicKeys takes context, page, perPage as parameters and -// returns an models.ApiResponse with models.ListPublicKeysResponse data and -// an error if there was an issue with the request or response. +// ListChargifyJsPublicKeys takes context, page, perPage as parameters and +// returns an models.ApiResponse with models.ListPublicKeysResponse data and +// an error if there was an issue with the request or response. // This endpoint returns public keys used for Chargify.js. func (s *SitesController) ListChargifyJsPublicKeys( - ctx context.Context, - page *int, - perPage *int) ( - models.ApiResponse[models.ListPublicKeysResponse], - error) { - req := s.prepareRequest(ctx, "GET", "/chargify_js_keys.json") - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - var result models.ListPublicKeysResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListPublicKeysResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListChargifyJsPublicKeysInput) ( + models.ApiResponse[models.ListPublicKeysResponse], + error) { + req := s.prepareRequest(ctx, "GET", "/chargify_js_keys.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + var result models.ListPublicKeysResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListPublicKeysResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/subscription_components_controller.go b/subscription_components_controller.go index e448ee75..bdf5ce39 100644 --- a/subscription_components_controller.go +++ b/subscription_components_controller.go @@ -1,825 +1,888 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" - "time" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" + "time" ) // SubscriptionComponentsController represents a controller struct. type SubscriptionComponentsController struct { - baseController + baseController } -// NewSubscriptionComponentsController creates a new instance of SubscriptionComponentsController. +// NewSubscriptionComponentsController creates a new instance of SubscriptionComponentsController. // It takes a baseController as a parameter and returns a pointer to the SubscriptionComponentsController. func NewSubscriptionComponentsController(baseController baseController) *SubscriptionComponentsController { - subscriptionComponentsController := SubscriptionComponentsController{baseController: baseController} - return &subscriptionComponentsController + subscriptionComponentsController := SubscriptionComponentsController{baseController: baseController} + return &subscriptionComponentsController } -// ReadSubscriptionComponent takes context, subscriptionId, componentId as parameters and -// returns an models.ApiResponse with models.SubscriptionComponentResponse data and -// an error if there was an issue with the request or response. +// ReadSubscriptionComponent takes context, subscriptionId, componentId as parameters and +// returns an models.ApiResponse with models.SubscriptionComponentResponse data and +// an error if there was an issue with the request or response. // This request will list information regarding a specific component owned by a subscription. func (s *SubscriptionComponentsController) ReadSubscriptionComponent( - ctx context.Context, - subscriptionId int, - componentId int) ( - models.ApiResponse[models.SubscriptionComponentResponse], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v/components/%v.json", subscriptionId, componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - - var result models.SubscriptionComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + componentId int) ( + models.ApiResponse[models.SubscriptionComponentResponse], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v/components/%v.json", subscriptionId, componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + + var result models.SubscriptionComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListSubscriptionComponents takes context, subscriptionId, dateField, direction, endDate, endDatetime, pricePointIds, productFamilyIds, sort, startDate, startDatetime, include, filterUseSiteExchangeRate, filterCurrencies as parameters and -// returns an models.ApiResponse with []models.SubscriptionComponentResponse data and -// an error if there was an issue with the request or response. -// This request will list a subscription's applied components. -// ## Archived Components +// ListSubscriptionComponentsInput represents the input of the ListSubscriptionComponents endpoint. +type ListSubscriptionComponentsInput struct { + // The Chargify id of the subscription + SubscriptionId int + // The type of filter you'd like to apply to your search. Use in query `date_field=updated_at`. + DateField *models.SubscriptionListDateField + // Controls the order in which results are returned. + // Use in query `direction=asc`. + Direction *models.SortingDirection + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. + EndDate *string + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. + EndDatetime *string + // Allows fetching components allocation only if price point id is present. Use in query `price_point_ids=not_null`. + PricePointIds *models.IncludeNotNull + // Allows fetching components allocation with matching product family id based on provided ids. Use in query `product_family_ids=1,2,3`. + ProductFamilyIds []int + // The attribute by which to sort. Use in query `sort=updated_at`. + Sort *models.ListSubscriptionComponentsSort + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. + StartDate *string + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. + StartDatetime *string + // Allows including additional data in the response. Use in query `include=subscription`. + Include *models.ListSubscriptionComponentsInclude + // Allows fetching components allocation with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. + FilterUseSiteExchangeRate *bool + // Allows fetching components allocation with matching currency based on provided values. Use in query `filter[currencies]=EUR,USD`. + FilterCurrencies []string +} + +// ListSubscriptionComponents takes context, subscriptionId, dateField, direction, endDate, endDatetime, pricePointIds, productFamilyIds, sort, startDate, startDatetime, include, filterUseSiteExchangeRate, filterCurrencies as parameters and +// returns an models.ApiResponse with []models.SubscriptionComponentResponse data and +// an error if there was an issue with the request or response. +// This request will list a subscription's applied components. +// ## Archived Components // When requesting to list components for a given subscription, if the subscription contains **archived** components they will be listed in the server response. func (s *SubscriptionComponentsController) ListSubscriptionComponents( - ctx context.Context, - subscriptionId int, - dateField *models.SubscriptionListDateField, - direction *models.SortingDirection, - endDate *string, - endDatetime *string, - pricePointIds *models.IncludeNotNull, - productFamilyIds []int, - sort *models.ListSubscriptionComponentsSort, - startDate *string, - startDatetime *string, - include *models.ListSubscriptionComponentsInclude, - filterUseSiteExchangeRate *bool, - filterCurrencies []string) ( - models.ApiResponse[[]models.SubscriptionComponentResponse], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v/components.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - if endDate != nil { - req.QueryParam("end_date", *endDate) - } - if endDatetime != nil { - req.QueryParam("end_datetime", *endDatetime) - } - if pricePointIds != nil { - req.QueryParam("price_point_ids", *pricePointIds) - } - if productFamilyIds != nil { - req.QueryParam("product_family_ids", productFamilyIds) - } - if sort != nil { - req.QueryParam("sort", *sort) - } - if startDate != nil { - req.QueryParam("start_date", *startDate) - } - if startDatetime != nil { - req.QueryParam("start_datetime", *startDatetime) - } - if include != nil { - req.QueryParam("include", *include) - } - if filterUseSiteExchangeRate != nil { - req.QueryParam("filter[use_site_exchange_rate]", *filterUseSiteExchangeRate) - } - if filterCurrencies != nil { - req.QueryParam("filter[currencies]", filterCurrencies) - } - - var result []models.SubscriptionComponentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.SubscriptionComponentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListSubscriptionComponentsInput) ( + models.ApiResponse[[]models.SubscriptionComponentResponse], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v/components.json", input.SubscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + if input.EndDate != nil { + req.QueryParam("end_date", *input.EndDate) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", *input.EndDatetime) + } + if input.PricePointIds != nil { + req.QueryParam("price_point_ids", *input.PricePointIds) + } + if input.ProductFamilyIds != nil { + req.QueryParam("product_family_ids", input.ProductFamilyIds) + } + if input.Sort != nil { + req.QueryParam("sort", *input.Sort) + } + if input.StartDate != nil { + req.QueryParam("start_date", *input.StartDate) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", *input.StartDatetime) + } + if input.Include != nil { + req.QueryParam("include", *input.Include) + } + if input.FilterUseSiteExchangeRate != nil { + req.QueryParam("filter[use_site_exchange_rate]", *input.FilterUseSiteExchangeRate) + } + if input.FilterCurrencies != nil { + req.QueryParam("filter[currencies]", input.FilterCurrencies) + } + + var result []models.SubscriptionComponentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.SubscriptionComponentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// BulkUpdateSubscriptionComponentsPricePoints takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.BulkComponentsPricePointAssignment data and -// an error if there was an issue with the request or response. -// Updates the price points on one or more of a subscription's components. -// The `price_point` key can take either a: -// 1. Price point id (integer) -// 2. Price point handle (string) +// BulkUpdateSubscriptionComponentsPricePoints takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.BulkComponentsPricePointAssignment data and +// an error if there was an issue with the request or response. +// Updates the price points on one or more of a subscription's components. +// The `price_point` key can take either a: +// 1. Price point id (integer) +// 2. Price point handle (string) // 3. `"_default"` string, which will reset the price point to the component's current default price point. func (s *SubscriptionComponentsController) BulkUpdateSubscriptionComponentsPricePoints( - ctx context.Context, - subscriptionId int, - body *models.BulkComponentsPricePointAssignment) ( - models.ApiResponse[models.BulkComponentsPricePointAssignment], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/price_points.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewComponentPricePointError}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.BulkComponentsPricePointAssignment - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.BulkComponentsPricePointAssignment](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.BulkComponentsPricePointAssignment) ( + models.ApiResponse[models.BulkComponentsPricePointAssignment], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/price_points.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewComponentPricePointError}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.BulkComponentsPricePointAssignment + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.BulkComponentsPricePointAssignment](decoder) + return models.NewApiResponse(result, resp), err } -// BulkResetSubscriptionComponentsPricePoints takes context, subscriptionId as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// Resets all of a subscription's components to use the current default. +// BulkResetSubscriptionComponentsPricePoints takes context, subscriptionId as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// Resets all of a subscription's components to use the current default. // **Note**: this will update the price point for all of the subscription's components, even ones that have not been allocated yet. func (s *SubscriptionComponentsController) BulkResetSubscriptionComponentsPricePoints( - ctx context.Context, - subscriptionId int) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/price_points/reset.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/price_points/reset.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// AllocateComponent takes context, subscriptionId, componentId, body as parameters and -// returns an models.ApiResponse with models.AllocationResponse data and -// an error if there was an issue with the request or response. -// This endpoint creates a new allocation, setting the current allocated quantity for the Component and recording a memo. -// **Notice**: Allocations can only be updated for Quantity, On/Off, and Prepaid Components. -// ## Allocations Documentation -// Full documentation on how to record Allocations in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997). It is focused on how allocations operate within the Chargify UI.It goes into greater detail on how the user interface will react when recording allocations. -// This documentation also goes into greater detail on how proration is taken into consideration when applying component allocations. -// ## Proration Schemes -// Changing the allocated quantity of a component mid-period can result in either a Charge or Credit being applied to the subscription. When creating an allocation via the API, you can pass the `upgrade_charge`, `downgrade_credit`, and `accrue_charge` to be applied. -// **Notice:** These proration and accural fields will be ignored for Prepaid Components since this component type always generate charges immediately without proration. -// For background information on prorated components and upgrade/downgrade schemes, see [Setting Component Allocations.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-upgrades-vs-downgrades). -// See the tables below for valid values. -// | upgrade_charge | Definition                                                        | -// |----------------|-------------------------------------------------------------------| -// | `full`         | A charge is added for the full price of the component.            | -// | `prorated`     | A charge is added for the prorated price of the component change. | -// | `none`         | No charge is added.                                               | -// | downgrade_credit | Definition                                        | -// |------------------|---------------------------------------------------| -// | `full`           | A full price credit is added for the amount owed. | -// | `prorated`       | A prorated credit is added for the amount owed.   | -// | `none`           | No charge is added.                               | -// | accrue_charge | Definition                                                                                               | -// |---------------|------------------------------------------------------------------------------------------------------------| -// | `true`        | Attempt to charge the customer at next renewal. | -// | `false`       | Attempt to charge the customer right away. If it fails, the charge will be accrued until the next renewal. | -// ### Order of Resolution for upgrade_charge and downgrade_credit -// 1. Per allocation in API call (within a single allocation of the `allocations` array) -// 2. [Component-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997-Component-Allocations#component-allocations-0-0) -// 3. Allocation API call top level (outside of the `allocations` array) -// 4. [Site-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-schemes) -// ### Order of Resolution for accrue charge -// 1. Allocation API call top level (outside of the `allocations` array) -// 2. [Site-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-schemes) +// AllocateComponent takes context, subscriptionId, componentId, body as parameters and +// returns an models.ApiResponse with models.AllocationResponse data and +// an error if there was an issue with the request or response. +// This endpoint creates a new allocation, setting the current allocated quantity for the Component and recording a memo. +// **Notice**: Allocations can only be updated for Quantity, On/Off, and Prepaid Components. +// ## Allocations Documentation +// Full documentation on how to record Allocations in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997). It is focused on how allocations operate within the Chargify UI.It goes into greater detail on how the user interface will react when recording allocations. +// This documentation also goes into greater detail on how proration is taken into consideration when applying component allocations. +// ## Proration Schemes +// Changing the allocated quantity of a component mid-period can result in either a Charge or Credit being applied to the subscription. When creating an allocation via the API, you can pass the `upgrade_charge`, `downgrade_credit`, and `accrue_charge` to be applied. +// **Notice:** These proration and accural fields will be ignored for Prepaid Components since this component type always generate charges immediately without proration. +// For background information on prorated components and upgrade/downgrade schemes, see [Setting Component Allocations.](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-upgrades-vs-downgrades). +// See the tables below for valid values. +// | upgrade_charge | Definition                                                        | +// |----------------|-------------------------------------------------------------------| +// | `full`         | A charge is added for the full price of the component.            | +// | `prorated`     | A charge is added for the prorated price of the component change. | +// | `none`         | No charge is added.                                               | +// | downgrade_credit | Definition                                        | +// |------------------|---------------------------------------------------| +// | `full`           | A full price credit is added for the amount owed. | +// | `prorated`       | A prorated credit is added for the amount owed.   | +// | `none`           | No charge is added.                               | +// | accrue_charge | Definition                                                                                               | +// |---------------|------------------------------------------------------------------------------------------------------------| +// | `true`        | Attempt to charge the customer at next renewal. | +// | `false`       | Attempt to charge the customer right away. If it fails, the charge will be accrued until the next renewal. | +// ### Order of Resolution for upgrade_charge and downgrade_credit +// 1. Per allocation in API call (within a single allocation of the `allocations` array) +// 2. [Component-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997-Component-Allocations#component-allocations-0-0) +// 3. Allocation API call top level (outside of the `allocations` array) +// 4. [Site-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-schemes) +// ### Order of Resolution for accrue charge +// 1. Allocation API call top level (outside of the `allocations` array) +// 2. [Site-level default value](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#proration-schemes) // **NOTE: Proration uses the current price of the component as well as the current tax rates. Changes to either may cause the prorated charge/credit to be wrong.** func (s *SubscriptionComponentsController) AllocateComponent( - ctx context.Context, - subscriptionId int, - componentId int, - body *models.CreateAllocationRequest) ( - models.ApiResponse[models.AllocationResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/components/%v/allocations.json", subscriptionId, componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.AllocationResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.AllocationResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + componentId int, + body *models.CreateAllocationRequest) ( + models.ApiResponse[models.AllocationResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/components/%v/allocations.json", subscriptionId, componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.AllocationResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.AllocationResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListAllocations takes context, subscriptionId, componentId, page as parameters and -// returns an models.ApiResponse with []models.AllocationResponse data and -// an error if there was an issue with the request or response. -// This endpoint returns the 50 most recent Allocations, ordered by most recent first. -// ## On/Off Components -// When a subscription's on/off component has been toggled to on (`1`) or off (`0`), usage will be logged in this response. -// ## Querying data via Chargify gem -// You can also query the current quantity via the [official Chargify Gem.](http://github.com/chargify/chargify_api_ares) -// ```# First way -// component = Chargify::Subscription::Component.find(1, :params => {:subscription_id => 7}) -// puts component.allocated_quantity -// # => 23 -// # Second way -// component = Chargify::Subscription.find(7).component(1) -// puts component.allocated_quantity -// # => 23 +// ListAllocations takes context, subscriptionId, componentId, page as parameters and +// returns an models.ApiResponse with []models.AllocationResponse data and +// an error if there was an issue with the request or response. +// This endpoint returns the 50 most recent Allocations, ordered by most recent first. +// ## On/Off Components +// When a subscription's on/off component has been toggled to on (`1`) or off (`0`), usage will be logged in this response. +// ## Querying data via Chargify gem +// You can also query the current quantity via the [official Chargify Gem.](http://github.com/chargify/chargify_api_ares) +// ```# First way +// component = Chargify::Subscription::Component.find(1, :params => {:subscription_id => 7}) +// puts component.allocated_quantity +// # => 23 +// # Second way +// component = Chargify::Subscription.find(7).component(1) +// puts component.allocated_quantity +// # => 23 // ``` func (s *SubscriptionComponentsController) ListAllocations( - ctx context.Context, - subscriptionId int, - componentId int, - page *int) ( - models.ApiResponse[[]models.AllocationResponse], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v/components/%v/allocations.json", subscriptionId, componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - if page != nil { - req.QueryParam("page", *page) - } - - var result []models.AllocationResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.AllocationResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + componentId int, + page *int) ( + models.ApiResponse[[]models.AllocationResponse], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v/components/%v/allocations.json", subscriptionId, componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + if page != nil { + req.QueryParam("page", *page) + } + + var result []models.AllocationResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.AllocationResponse](decoder) + return models.NewApiResponse(result, resp), err } -// AllocateComponents takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with []models.AllocationResponse data and -// an error if there was an issue with the request or response. -// Creates multiple allocations, setting the current allocated quantity for each of the components and recording a memo. The charges and/or credits that are created will be rolled up into a single total which is used to determine whether this is an upgrade or a downgrade. Be aware of the Order of Resolutions explained below in determining the proration scheme. -// A `component_id` is required for each allocation. +// AllocateComponents takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with []models.AllocationResponse data and +// an error if there was an issue with the request or response. +// Creates multiple allocations, setting the current allocated quantity for each of the components and recording a memo. The charges and/or credits that are created will be rolled up into a single total which is used to determine whether this is an upgrade or a downgrade. Be aware of the Order of Resolutions explained below in determining the proration scheme. +// A `component_id` is required for each allocation. // This endpoint only responds to JSON. It is not available for XML. func (s *SubscriptionComponentsController) AllocateComponents( - ctx context.Context, - subscriptionId int, - body *models.AllocateComponents) ( - models.ApiResponse[[]models.AllocationResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/allocations.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result []models.AllocationResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.AllocationResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.AllocateComponents) ( + models.ApiResponse[[]models.AllocationResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/allocations.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result []models.AllocationResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.AllocationResponse](decoder) + return models.NewApiResponse(result, resp), err } -// PreviewAllocations takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.AllocationPreviewResponse data and -// an error if there was an issue with the request or response. -// Chargify offers the ability to preview a potential subscription's **quantity-based** or **on/off** component allocation in the middle of the current billing period. This is useful if you want users to be able to see the effect of a component operation before actually doing it. -// ## Fine-grained Component Control: Use with multiple `upgrade_charge`s or `downgrade_credits` -// When the allocation uses multiple different types of `upgrade_charge`s or `downgrade_credit`s, the Allocation is viewed as an Allocation which uses "Fine-Grained Component Control". As a result, the response will not include `direction` and `proration` within the `allocation_preview`, but at the `line_items` and `allocations` level respectfully. +// PreviewAllocations takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.AllocationPreviewResponse data and +// an error if there was an issue with the request or response. +// Chargify offers the ability to preview a potential subscription's **quantity-based** or **on/off** component allocation in the middle of the current billing period. This is useful if you want users to be able to see the effect of a component operation before actually doing it. +// ## Fine-grained Component Control: Use with multiple `upgrade_charge`s or `downgrade_credits` +// When the allocation uses multiple different types of `upgrade_charge`s or `downgrade_credit`s, the Allocation is viewed as an Allocation which uses "Fine-Grained Component Control". As a result, the response will not include `direction` and `proration` within the `allocation_preview`, but at the `line_items` and `allocations` level respectfully. // See example below for Fine-Grained Component Control response. func (s *SubscriptionComponentsController) PreviewAllocations( - ctx context.Context, - subscriptionId int, - body *models.PreviewAllocationsRequest) ( - models.ApiResponse[models.AllocationPreviewResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/allocations/preview.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewComponentAllocationError}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.AllocationPreviewResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.AllocationPreviewResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.PreviewAllocationsRequest) ( + models.ApiResponse[models.AllocationPreviewResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/allocations/preview.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewComponentAllocationError}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.AllocationPreviewResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.AllocationPreviewResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdatePrepaidUsageAllocationExpirationDate takes context, subscriptionId, componentId, allocationId, body as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// When the expiration interval options are selected on a prepaid usage component price point, all allocations will be created with an expiration date. This expiration date can be changed after the fact to allow for extending or shortening the allocation's active window. -// In order to change a prepaid usage allocation's expiration date, a PUT call must be made to the allocation's endpoint with a new expiration date. -// ## Limitations -// A few limitations exist when changing an allocation's expiration date: -// - An expiration date can only be changed for an allocation that belongs to a price point with expiration interval options explicitly set. -// - An expiration date can be changed towards the future with no limitations. +// UpdatePrepaidUsageAllocationExpirationDate takes context, subscriptionId, componentId, allocationId, body as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// When the expiration interval options are selected on a prepaid usage component price point, all allocations will be created with an expiration date. This expiration date can be changed after the fact to allow for extending or shortening the allocation's active window. +// In order to change a prepaid usage allocation's expiration date, a PUT call must be made to the allocation's endpoint with a new expiration date. +// ## Limitations +// A few limitations exist when changing an allocation's expiration date: +// - An expiration date can only be changed for an allocation that belongs to a price point with expiration interval options explicitly set. +// - An expiration date can be changed towards the future with no limitations. // - An expiration date can be changed towards the past (essentially expiring it) up to the subscription's current period beginning date. func (s *SubscriptionComponentsController) UpdatePrepaidUsageAllocationExpirationDate( - ctx context.Context, - subscriptionId int, - componentId int, - allocationId int, - body *models.UpdateAllocationExpirationDate) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/subscriptions/%v/components/%v/allocations/%v.json", subscriptionId, componentId, allocationId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionComponentAllocationError}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subscriptionId int, + componentId int, + allocationId int, + body *models.UpdateAllocationExpirationDate) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/subscriptions/%v/components/%v/allocations/%v.json", subscriptionId, componentId, allocationId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionComponentAllocationError}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// DeletePrepaidUsageAllocation takes context, subscriptionId, componentId, allocationId, body as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// Prepaid Usage components are unique in that their allocations are always additive. In order to reduce a subscription's allocated quantity for a prepaid usage component each allocation must be destroyed individually via this endpoint. -// ## Credit Scheme -// By default, destroying an allocation will generate a service credit on the subscription. This behavior can be modified with the optional `credit_scheme` parameter on this endpoint. The accepted values are: -// 1. `none`: The allocation will be destroyed and the balances will be updated but no service credit or refund will be created. -// 2. `credit`: The allocation will be destroyed and the balances will be updated and a service credit will be generated. This is also the default behavior if the `credit_scheme` param is not passed. +// DeletePrepaidUsageAllocation takes context, subscriptionId, componentId, allocationId, body as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// Prepaid Usage components are unique in that their allocations are always additive. In order to reduce a subscription's allocated quantity for a prepaid usage component each allocation must be destroyed individually via this endpoint. +// ## Credit Scheme +// By default, destroying an allocation will generate a service credit on the subscription. This behavior can be modified with the optional `credit_scheme` parameter on this endpoint. The accepted values are: +// 1. `none`: The allocation will be destroyed and the balances will be updated but no service credit or refund will be created. +// 2. `credit`: The allocation will be destroyed and the balances will be updated and a service credit will be generated. This is also the default behavior if the `credit_scheme` param is not passed. // 3. `refund`: The allocation will be destroyed and the balances will be updated and a refund will be issued along with a Credit Note. func (s *SubscriptionComponentsController) DeletePrepaidUsageAllocation( - ctx context.Context, - subscriptionId int, - componentId int, - allocationId int, - body *models.CreditSchemeRequest) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/subscriptions/%v/components/%v/allocations/%v.json", subscriptionId, componentId, allocationId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionComponentAllocationError}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subscriptionId int, + componentId int, + allocationId int, + body *models.CreditSchemeRequest) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/subscriptions/%v/components/%v/allocations/%v.json", subscriptionId, componentId, allocationId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionComponentAllocationError}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// CreateUsage takes context, subscriptionId, componentId, body as parameters and -// returns an models.ApiResponse with models.UsageResponse data and -// an error if there was an issue with the request or response. -// ## Documentation -// Full documentation on how to create Components in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#creating-components). Additionally, for information on how to record component usage against a subscription, please see the following resources: -// + [Recording Metered Component Usage](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-metered-component-usage) -// + [Reporting Prepaid Component Status](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-prepaid-component-status) -// You may choose to report metered or prepaid usage to Chargify as often as you wish. You may report usage as it happens. You may also report usage periodically, such as each night or once per billing period. If usage events occur in your system very frequently (on the order of thousands of times an hour), it is best to accumulate usage into batches on your side, and then report those batches less frequently, such as daily. This will ensure you remain below any API throttling limits. If your use case requires higher rates of usage reporting, we recommend utilizing Events Based Components. -// ## Create Usage for Subscription -// This endpoint allows you to record an instance of metered or prepaid usage for a subscription. The `quantity` from usage for each component is accumulated to the `unit_balance` on the [Component Line Item](./b3A6MTQxMDgzNzQ-read-subscription-component) for the subscription. -// ## Price Point ID usage -// If you are using price points, for metered and prepaid usage components, Chargify gives you the option to specify a price point in your request. -// You do not need to specify a price point ID. If a price point is not included, the default price point for the component will be used when the usage is recorded. -// If an invalid `price_point_id` is submitted, the endpoint will return an error. -// ## Deducting Usage -// In the event that you need to reverse a previous usage report or otherwise deduct from the current usage balance, you may provide a negative quantity. -// Example: -// Previously recorded: -// ```json -// { -// "usage": { -// "quantity": 5000, -// "memo": "Recording 5000 units" -// } -// } -// ``` -// At this point, `unit_balance` would be `5000`. To reduce the balance to `0`, POST the following payload: -// ```json -// { -// "usage": { -// "quantity": -5000, -// "memo": "Deducting 5000 units" -// } -// } -// ``` -// The `unit_balance` has a floor of `0`; negative unit balances are never allowed. For example, if the usage balance is 100 and you deduct 200 units, the unit balance would then be `0`, not `-100`. -// ## FAQ -// Q. Is it possible to record metered usage for more than one component at a time? +// CreateUsage takes context, subscriptionId, componentId, body as parameters and +// returns an models.ApiResponse with models.UsageResponse data and +// an error if there was an issue with the request or response. +// ## Documentation +// Full documentation on how to create Components in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405020625677#creating-components). Additionally, for information on how to record component usage against a subscription, please see the following resources: +// + [Recording Metered Component Usage](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-metered-component-usage) +// + [Reporting Prepaid Component Status](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404527849997#reporting-prepaid-component-status) +// You may choose to report metered or prepaid usage to Chargify as often as you wish. You may report usage as it happens. You may also report usage periodically, such as each night or once per billing period. If usage events occur in your system very frequently (on the order of thousands of times an hour), it is best to accumulate usage into batches on your side, and then report those batches less frequently, such as daily. This will ensure you remain below any API throttling limits. If your use case requires higher rates of usage reporting, we recommend utilizing Events Based Components. +// ## Create Usage for Subscription +// This endpoint allows you to record an instance of metered or prepaid usage for a subscription. The `quantity` from usage for each component is accumulated to the `unit_balance` on the [Component Line Item](./b3A6MTQxMDgzNzQ-read-subscription-component) for the subscription. +// ## Price Point ID usage +// If you are using price points, for metered and prepaid usage components, Chargify gives you the option to specify a price point in your request. +// You do not need to specify a price point ID. If a price point is not included, the default price point for the component will be used when the usage is recorded. +// If an invalid `price_point_id` is submitted, the endpoint will return an error. +// ## Deducting Usage +// In the event that you need to reverse a previous usage report or otherwise deduct from the current usage balance, you may provide a negative quantity. +// Example: +// Previously recorded: +// ```json +// { +// "usage": { +// "quantity": 5000, +// "memo": "Recording 5000 units" +// } +// } +// ``` +// At this point, `unit_balance` would be `5000`. To reduce the balance to `0`, POST the following payload: +// ```json +// { +// "usage": { +// "quantity": -5000, +// "memo": "Deducting 5000 units" +// } +// } +// ``` +// The `unit_balance` has a floor of `0`; negative unit balances are never allowed. For example, if the usage balance is 100 and you deduct 200 units, the unit balance would then be `0`, not `-100`. +// ## FAQ +// Q. Is it possible to record metered usage for more than one component at a time? // A. No. Usage should be reported as one API call per component on a single subscription. For example, to record that a subscriber has sent both an SMS Message and an Email, send an API call for each. func (s *SubscriptionComponentsController) CreateUsage( - ctx context.Context, - subscriptionId int, - componentId interface{}, - body *models.CreateUsageRequest) ( - models.ApiResponse[models.UsageResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/components/%v/usages.json", subscriptionId, componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.UsageResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.UsageResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + componentId models.CreateUsageComponentId, + body *models.CreateUsageRequest) ( + models.ApiResponse[models.UsageResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/components/%v/usages.json", subscriptionId, componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.UsageResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.UsageResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListUsages takes context, subscriptionId, componentId, sinceId, maxId, sinceDate, untilDate, page, perPage as parameters and -// returns an models.ApiResponse with []models.UsageResponse data and -// an error if there was an issue with the request or response. -// This request will return a list of the usages associated with a subscription for a particular metered component. This will display the previously recorded components for a subscription. -// This endpoint is not compatible with quantity-based components. -// ## Since Date and Until Date Usage -// Note: The `since_date` and `until_date` attributes each default to midnight on the date specified. For example, in order to list usages for January 20th, you would need to append the following to the URL. -// ``` -// ?since_date=2016-01-20&until_date=2016-01-21 -// ``` -// ## Read Usage by Handle +// ListUsagesInput represents the input of the ListUsages endpoint. +type ListUsagesInput struct { + // The Chargify id of the subscription + SubscriptionId int + // Either the Chargify id for the component or the component's handle prefixed by `handle:` + ComponentId models.ListUsagesInputComponentId + // Returns usages with an id greater than or equal to the one specified + SinceId *int + // Returns usages with an id less than or equal to the one specified + MaxId *int + // Returns usages with a created_at date greater than or equal to midnight (12:00 AM) on the date specified. + SinceDate *time.Time + // Returns usages with a created_at date less than or equal to midnight (12:00 AM) on the date specified. + UntilDate *time.Time + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int +} + +// ListUsages takes context, subscriptionId, componentId, sinceId, maxId, sinceDate, untilDate, page, perPage as parameters and +// returns an models.ApiResponse with []models.UsageResponse data and +// an error if there was an issue with the request or response. +// This request will return a list of the usages associated with a subscription for a particular metered component. This will display the previously recorded components for a subscription. +// This endpoint is not compatible with quantity-based components. +// ## Since Date and Until Date Usage +// Note: The `since_date` and `until_date` attributes each default to midnight on the date specified. For example, in order to list usages for January 20th, you would need to append the following to the URL. +// ``` +// ?since_date=2016-01-20&until_date=2016-01-21 +// ``` +// ## Read Usage by Handle // Use this endpoint to read the previously recorded components for a subscription. You can now specify either the component id (integer) or the component handle prefixed by "handle:" to specify the unique identifier for the component you are working with. func (s *SubscriptionComponentsController) ListUsages( - ctx context.Context, - subscriptionId int, - componentId interface{}, - sinceId *int, - maxId *int, - sinceDate *time.Time, - untilDate *time.Time, - page *int, - perPage *int) ( - models.ApiResponse[[]models.UsageResponse], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v/components/%v/usages.json", subscriptionId, componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if sinceId != nil { - req.QueryParam("since_id", *sinceId) - } - if maxId != nil { - req.QueryParam("max_id", *maxId) - } - if sinceDate != nil { - req.QueryParam("since_date", sinceDate.Format(models.DEFAULT_DATE)) - } - if untilDate != nil { - req.QueryParam("until_date", untilDate.Format(models.DEFAULT_DATE)) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - - var result []models.UsageResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.UsageResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListUsagesInput) ( + models.ApiResponse[[]models.UsageResponse], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v/components/%v/usages.json", input.SubscriptionId, input.ComponentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.SinceId != nil { + req.QueryParam("since_id", *input.SinceId) + } + if input.MaxId != nil { + req.QueryParam("max_id", *input.MaxId) + } + if input.SinceDate != nil { + req.QueryParam("since_date", input.SinceDate.Format(models.DEFAULT_DATE)) + } + if input.UntilDate != nil { + req.QueryParam("until_date", input.UntilDate.Format(models.DEFAULT_DATE)) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + + var result []models.UsageResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.UsageResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ActivateEventBasedComponent takes context, subscriptionId, componentId as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// In order to bill your subscribers on your Events data under the Events-Based Billing feature, the components must be activated for the subscriber. -// Learn more about the role of activation in the [Events-Based Billing docs](https://chargify.zendesk.com/hc/en-us/articles/4407720810907#activating-components-for-subscribers). -// Use this endpoint to activate an event-based component for a single subscription. Activating an event-based component causes Chargify to bill for events when the subscription is renewed. +// ActivateEventBasedComponent takes context, subscriptionId, componentId as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// In order to bill your subscribers on your Events data under the Events-Based Billing feature, the components must be activated for the subscriber. +// Learn more about the role of activation in the [Events-Based Billing docs](https://chargify.zendesk.com/hc/en-us/articles/4407720810907#activating-components-for-subscribers). +// Use this endpoint to activate an event-based component for a single subscription. Activating an event-based component causes Chargify to bill for events when the subscription is renewed. // *Note: it is possible to stream events for a subscription at any time, regardless of component activation status. The activation status only determines if the subscription should be billed for event-based component usage at renewal.* func (s *SubscriptionComponentsController) ActivateEventBasedComponent( - ctx context.Context, - subscriptionId int, - componentId int) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/event_based_billing/subscriptions/%v/components/%v/activate.json", subscriptionId, componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subscriptionId int, + componentId int) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/event_based_billing/subscriptions/%v/components/%v/activate.json", subscriptionId, componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// DeactivateEventBasedComponent takes context, subscriptionId, componentId as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. +// DeactivateEventBasedComponent takes context, subscriptionId, componentId as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. // Use this endpoint to deactivate an event-based component for a single subscription. Deactivating the event-based component causes Chargify to ignore related events at subscription renewal. func (s *SubscriptionComponentsController) DeactivateEventBasedComponent( - ctx context.Context, - subscriptionId int, - componentId int) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/event_based_billing/subscriptions/%v/components/%v/deactivate.json", subscriptionId, componentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subscriptionId int, + componentId int) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/event_based_billing/subscriptions/%v/components/%v/deactivate.json", subscriptionId, componentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// RecordEvent takes context, subdomain, apiHandle, storeUid, body as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// ## Documentation -// Events-Based Billing is an evolved form of metered billing that is based on data-rich events streamed in real-time from your system to Chargify. -// These events can then be transformed, enriched, or analyzed to form the computed totals of usage charges billed to your customers. -// This API allows you to stream events into the Chargify data ingestion engine. -// Learn more about the feature in general in the [Events-Based Billing help docs](https://chargify.zendesk.com/hc/en-us/articles/4407720613403). -// ## Record Event -// Use this endpoint to record a single event. -// *Note: this endpoint differs from the standard Chargify endpoints in that the URL subdomain will be `events` and your site subdomain will be included in the URL path. For example:* -// ``` -// https://events.chargify.com/my-site-subdomain/events/my-stream-api-handle +// RecordEvent takes context, subdomain, apiHandle, storeUid, body as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// ## Documentation +// Events-Based Billing is an evolved form of metered billing that is based on data-rich events streamed in real-time from your system to Chargify. +// These events can then be transformed, enriched, or analyzed to form the computed totals of usage charges billed to your customers. +// This API allows you to stream events into the Chargify data ingestion engine. +// Learn more about the feature in general in the [Events-Based Billing help docs](https://chargify.zendesk.com/hc/en-us/articles/4407720613403). +// ## Record Event +// Use this endpoint to record a single event. +// *Note: this endpoint differs from the standard Chargify endpoints in that the URL subdomain will be `events` and your site subdomain will be included in the URL path. For example:* +// ``` +// https://events.chargify.com/my-site-subdomain/events/my-stream-api-handle // ``` func (s *SubscriptionComponentsController) RecordEvent( - ctx context.Context, - subdomain string, - apiHandle string, - storeUid *string, - body *models.EBBEvent) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/%v/events/%v.json", subdomain, apiHandle), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if storeUid != nil { - req.QueryParam("store_uid", *storeUid) - } - if body != nil { - req.Json(*body) - } - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subdomain string, + apiHandle string, + storeUid *string, + body *models.EBBEvent) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/%v/events/%v.json", subdomain, apiHandle), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if storeUid != nil { + req.QueryParam("store_uid", *storeUid) + } + if body != nil { + req.Json(body) + } + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// BulkRecordEvents takes context, subdomain, apiHandle, storeUid, body as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// Use this endpoint to record a collection of events. -// *Note: this endpoint differs from the standard Chargify endpoints in that the subdomain will be `events` and your site subdomain will be included in the URL path.* +// BulkRecordEvents takes context, subdomain, apiHandle, storeUid, body as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// Use this endpoint to record a collection of events. +// *Note: this endpoint differs from the standard Chargify endpoints in that the subdomain will be `events` and your site subdomain will be included in the URL path.* // A maximum of 1000 events can be published in a single request. A 422 will be returned if this limit is exceeded. func (s *SubscriptionComponentsController) BulkRecordEvents( - ctx context.Context, - subdomain string, - apiHandle string, - storeUid *string, - body []models.EBBEvent) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/%v/events/%v/bulk.json", subdomain, apiHandle), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if storeUid != nil { - req.QueryParam("store_uid", *storeUid) - } - if body != nil { - req.Json(body) - } - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subdomain string, + apiHandle string, + storeUid *string, + body []models.EBBEvent) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/%v/events/%v/bulk.json", subdomain, apiHandle), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if storeUid != nil { + req.QueryParam("store_uid", *storeUid) + } + if body != nil { + req.Json(body) + } + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err +} + +// ListSubscriptionComponentsForSiteInput represents the input of the ListSubscriptionComponentsForSite endpoint. +type ListSubscriptionComponentsForSiteInput struct { + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The attribute by which to sort. Use in query: `sort=updated_at`. + Sort *models.ListSubscriptionComponentsSort + // Controls the order in which results are returned. + // Use in query `direction=asc`. + Direction *models.SortingDirection + // The type of filter you'd like to apply to your search. Use in query: `date_field=updated_at`. + DateField *models.SubscriptionListDateField + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `start_date=2011-12-15`. + StartDate *string + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `start_datetime=2022-07-01 09:00:05`. + StartDatetime *string + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `end_date=2011-12-16`. + EndDate *string + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `end_datetime=2022-07-01 09:00:05`. + EndDatetime *string + // Allows fetching components allocation with matching subscription id based on provided ids. Use in query `subscription_ids=1,2,3`. + SubscriptionIds []int + // Allows fetching components allocation only if price point id is present. Use in query `price_point_ids=not_null`. + PricePointIds *models.IncludeNotNull + // Allows fetching components allocation with matching product family id based on provided ids. Use in query `product_family_ids=1,2,3`. + ProductFamilyIds []int + // Allows including additional data in the response. Use in query `include=subscription`. + Include *models.ListSubscriptionComponentsInclude + // Allows fetching components allocation with matching use_site_exchange_rate based on provided value. Use in query `filter[use_site_exchange_rate]=true`. + FilterUseSiteExchangeRate *bool + // Allows fetching components allocation with matching currency based on provided values. Use in query `filter[currencies]=USD,EUR`. + FilterCurrencies []string + // Allows fetching components allocations that belong to the subscription with matching states based on provided values. To use this filter you also have to include the following param in the request `include=subscription`. Use in query `filter[subscription][states]=active,canceled&include=subscription`. + FilterSubscriptionStates []models.SubscriptionStateFilter + // The type of filter you'd like to apply to your search. To use this filter you also have to include the following param in the request `include=subscription`. + FilterSubscriptionDateField *models.SubscriptionListDateField + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. To use this filter you also have to include the following param in the request `include=subscription`. + FilterSubscriptionStartDate *time.Time + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of start_date. To use this filter you also have to include the following param in the request `include=subscription`. + FilterSubscriptionStartDatetime *time.Time + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns components that belong to the subscription with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. To use this filter you also have to include the following param in the request `include=subscription`. + FilterSubscriptionEndDate *time.Time + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns components that belong to the subscription with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site''s time zone will be used. If provided, this parameter will be used instead of end_date. To use this filter you also have to include the following param in the request `include=subscription`. + FilterSubscriptionEndDatetime *time.Time } -// ListSubscriptionComponentsForSite takes context, page, perPage, sort, direction, dateField, startDate, startDatetime, endDate, endDatetime, subscriptionIds, pricePointIds, productFamilyIds, include, filterUseSiteExchangeRate, filterCurrencies, filterSubscriptionStates, filterSubscriptionDateField, filterSubscriptionStartDate, filterSubscriptionStartDatetime, filterSubscriptionEndDate, filterSubscriptionEndDatetime as parameters and -// returns an models.ApiResponse with models.ListSubscriptionComponentsResponse data and -// an error if there was an issue with the request or response. +// ListSubscriptionComponentsForSite takes context, page, perPage, sort, direction, dateField, startDate, startDatetime, endDate, endDatetime, subscriptionIds, pricePointIds, productFamilyIds, include, filterUseSiteExchangeRate, filterCurrencies, filterSubscriptionStates, filterSubscriptionDateField, filterSubscriptionStartDate, filterSubscriptionStartDatetime, filterSubscriptionEndDate, filterSubscriptionEndDatetime as parameters and +// returns an models.ApiResponse with models.ListSubscriptionComponentsResponse data and +// an error if there was an issue with the request or response. // This request will list components applied to each subscription. func (s *SubscriptionComponentsController) ListSubscriptionComponentsForSite( - ctx context.Context, - page *int, - perPage *int, - sort *models.ListSubscriptionComponentsSort, - direction *models.SortingDirection, - dateField *models.SubscriptionListDateField, - startDate *string, - startDatetime *string, - endDate *string, - endDatetime *string, - subscriptionIds []int, - pricePointIds *models.IncludeNotNull, - productFamilyIds []int, - include *models.ListSubscriptionComponentsInclude, - filterUseSiteExchangeRate *bool, - filterCurrencies []string, - filterSubscriptionStates []models.SubscriptionStateFilter, - filterSubscriptionDateField *models.SubscriptionListDateField, - filterSubscriptionStartDate *time.Time, - filterSubscriptionStartDatetime *time.Time, - filterSubscriptionEndDate *time.Time, - filterSubscriptionEndDatetime *time.Time) ( - models.ApiResponse[models.ListSubscriptionComponentsResponse], - error) { - req := s.prepareRequest(ctx, "GET", "/subscriptions_components.json") - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if sort != nil { - req.QueryParam("sort", *sort) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if startDate != nil { - req.QueryParam("start_date", *startDate) - } - if startDatetime != nil { - req.QueryParam("start_datetime", *startDatetime) - } - if endDate != nil { - req.QueryParam("end_date", *endDate) - } - if endDatetime != nil { - req.QueryParam("end_datetime", *endDatetime) - } - if subscriptionIds != nil { - req.QueryParam("subscription_ids", subscriptionIds) - } - if pricePointIds != nil { - req.QueryParam("price_point_ids", *pricePointIds) - } - if productFamilyIds != nil { - req.QueryParam("product_family_ids", productFamilyIds) - } - if include != nil { - req.QueryParam("include", *include) - } - if filterUseSiteExchangeRate != nil { - req.QueryParam("filter[use_site_exchange_rate]", *filterUseSiteExchangeRate) - } - if filterCurrencies != nil { - req.QueryParam("filter[currencies]", filterCurrencies) - } - if filterSubscriptionStates != nil { - req.QueryParam("filter[subscription][states]", filterSubscriptionStates) - } - if filterSubscriptionDateField != nil { - req.QueryParam("filter[subscription][date_field]", *filterSubscriptionDateField) - } - if filterSubscriptionStartDate != nil { - req.QueryParam("filter[subscription][start_date]", filterSubscriptionStartDate.Format(models.DEFAULT_DATE)) - } - if filterSubscriptionStartDatetime != nil { - req.QueryParam("filter[subscription][start_datetime]", filterSubscriptionStartDatetime.Format(time.RFC3339)) - } - if filterSubscriptionEndDate != nil { - req.QueryParam("filter[subscription][end_date]", filterSubscriptionEndDate.Format(models.DEFAULT_DATE)) - } - if filterSubscriptionEndDatetime != nil { - req.QueryParam("filter[subscription][end_datetime]", filterSubscriptionEndDatetime.Format(time.RFC3339)) - } - var result models.ListSubscriptionComponentsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListSubscriptionComponentsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListSubscriptionComponentsForSiteInput) ( + models.ApiResponse[models.ListSubscriptionComponentsResponse], + error) { + req := s.prepareRequest(ctx, "GET", "/subscriptions_components.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Sort != nil { + req.QueryParam("sort", *input.Sort) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.StartDate != nil { + req.QueryParam("start_date", *input.StartDate) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", *input.StartDatetime) + } + if input.EndDate != nil { + req.QueryParam("end_date", *input.EndDate) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", *input.EndDatetime) + } + if input.SubscriptionIds != nil { + req.QueryParam("subscription_ids", input.SubscriptionIds) + } + if input.PricePointIds != nil { + req.QueryParam("price_point_ids", *input.PricePointIds) + } + if input.ProductFamilyIds != nil { + req.QueryParam("product_family_ids", input.ProductFamilyIds) + } + if input.Include != nil { + req.QueryParam("include", *input.Include) + } + if input.FilterUseSiteExchangeRate != nil { + req.QueryParam("filter[use_site_exchange_rate]", *input.FilterUseSiteExchangeRate) + } + if input.FilterCurrencies != nil { + req.QueryParam("filter[currencies]", input.FilterCurrencies) + } + if input.FilterSubscriptionStates != nil { + req.QueryParam("filter[subscription][states]", input.FilterSubscriptionStates) + } + if input.FilterSubscriptionDateField != nil { + req.QueryParam("filter[subscription][date_field]", *input.FilterSubscriptionDateField) + } + if input.FilterSubscriptionStartDate != nil { + req.QueryParam("filter[subscription][start_date]", input.FilterSubscriptionStartDate.Format(models.DEFAULT_DATE)) + } + if input.FilterSubscriptionStartDatetime != nil { + req.QueryParam("filter[subscription][start_datetime]", input.FilterSubscriptionStartDatetime.Format(time.RFC3339)) + } + if input.FilterSubscriptionEndDate != nil { + req.QueryParam("filter[subscription][end_date]", input.FilterSubscriptionEndDate.Format(models.DEFAULT_DATE)) + } + if input.FilterSubscriptionEndDatetime != nil { + req.QueryParam("filter[subscription][end_datetime]", input.FilterSubscriptionEndDatetime.Format(time.RFC3339)) + } + var result models.ListSubscriptionComponentsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListSubscriptionComponentsResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/subscription_group_invoice_account_controller.go b/subscription_group_invoice_account_controller.go index d5c345b5..3097e6b1 100644 --- a/subscription_group_invoice_account_controller.go +++ b/subscription_group_invoice_account_controller.go @@ -1,174 +1,192 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "time" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "time" ) // SubscriptionGroupInvoiceAccountController represents a controller struct. type SubscriptionGroupInvoiceAccountController struct { - baseController + baseController } -// NewSubscriptionGroupInvoiceAccountController creates a new instance of SubscriptionGroupInvoiceAccountController. +// NewSubscriptionGroupInvoiceAccountController creates a new instance of SubscriptionGroupInvoiceAccountController. // It takes a baseController as a parameter and returns a pointer to the SubscriptionGroupInvoiceAccountController. func NewSubscriptionGroupInvoiceAccountController(baseController baseController) *SubscriptionGroupInvoiceAccountController { - subscriptionGroupInvoiceAccountController := SubscriptionGroupInvoiceAccountController{baseController: baseController} - return &subscriptionGroupInvoiceAccountController + subscriptionGroupInvoiceAccountController := SubscriptionGroupInvoiceAccountController{baseController: baseController} + return &subscriptionGroupInvoiceAccountController } -// CreateSubscriptionGroupPrepayment takes context, uid, body as parameters and -// returns an models.ApiResponse with models.SubscriptionGroupPrepaymentResponse data and -// an error if there was an issue with the request or response. +// CreateSubscriptionGroupPrepayment takes context, uid, body as parameters and +// returns an models.ApiResponse with models.SubscriptionGroupPrepaymentResponse data and +// an error if there was an issue with the request or response. // A prepayment can be added for a subscription group identified by the group's `uid`. This endpoint requires a `amount`, `details`, `method`, and `memo`. On success, the prepayment will be added to the group's prepayment balance. func (s *SubscriptionGroupInvoiceAccountController) CreateSubscriptionGroupPrepayment( - ctx context.Context, - uid string, - body *models.SubscriptionGroupPrepaymentRequest) ( - models.ApiResponse[models.SubscriptionGroupPrepaymentResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscription_groups/%v/prepayments.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionGroupPrepaymentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionGroupPrepaymentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string, + body *models.SubscriptionGroupPrepaymentRequest) ( + models.ApiResponse[models.SubscriptionGroupPrepaymentResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscription_groups/%v/prepayments.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionGroupPrepaymentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionGroupPrepaymentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListPrepaymentsForSubscriptionGroup takes context, uid, filterDateField, filterEndDate, filterStartDate, page, perPage as parameters and -// returns an models.ApiResponse with models.ListSubscriptionGroupPrepaymentResponse data and -// an error if there was an issue with the request or response. +// ListPrepaymentsForSubscriptionGroupInput represents the input of the ListPrepaymentsForSubscriptionGroup endpoint. +type ListPrepaymentsForSubscriptionGroupInput struct { + // The uid of the subscription group + Uid string + // The type of filter you would like to apply to your search. + // Use in query: `filter[date_field]=created_at`. + FilterDateField *models.ListSubscriptionGroupPrepaymentDateField + // The end date (format YYYY-MM-DD) with which to filter the date_field. + // Returns prepayments with a timestamp up to and including 11:59:59PM in your site's time zone on the date specified. + // Use in query: `filter[end_date]=2011-12-15`. + FilterEndDate *time.Time + // The start date (format YYYY-MM-DD) with which to filter the date_field. + // Returns prepayments with a timestamp at or after midnight (12:00:00 AM) in your site's time zone on the date specified. + // Use in query: `filter[start_date]=2011-12-15`. + FilterStartDate *time.Time + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int +} + +// ListPrepaymentsForSubscriptionGroup takes context, uid, filterDateField, filterEndDate, filterStartDate, page, perPage as parameters and +// returns an models.ApiResponse with models.ListSubscriptionGroupPrepaymentResponse data and +// an error if there was an issue with the request or response. // This request will list a subscription group's prepayments. func (s *SubscriptionGroupInvoiceAccountController) ListPrepaymentsForSubscriptionGroup( - ctx context.Context, - uid string, - filterDateField *models.ListSubscriptionGroupPrepaymentDateField, - filterEndDate *time.Time, - filterStartDate *time.Time, - page *int, - perPage *int) ( - models.ApiResponse[models.ListSubscriptionGroupPrepaymentResponse], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscription_groups/%v/prepayments.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - if filterDateField != nil { - req.QueryParam("filter[date_field]", *filterDateField) - } - if filterEndDate != nil { - req.QueryParam("filter[end_date]", filterEndDate.Format(models.DEFAULT_DATE)) - } - if filterStartDate != nil { - req.QueryParam("filter[start_date]", filterStartDate.Format(models.DEFAULT_DATE)) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - - var result models.ListSubscriptionGroupPrepaymentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListSubscriptionGroupPrepaymentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListPrepaymentsForSubscriptionGroupInput) ( + models.ApiResponse[models.ListSubscriptionGroupPrepaymentResponse], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscription_groups/%v/prepayments.json", input.Uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + if input.FilterDateField != nil { + req.QueryParam("filter[date_field]", *input.FilterDateField) + } + if input.FilterEndDate != nil { + req.QueryParam("filter[end_date]", input.FilterEndDate.Format(models.DEFAULT_DATE)) + } + if input.FilterStartDate != nil { + req.QueryParam("filter[start_date]", input.FilterStartDate.Format(models.DEFAULT_DATE)) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + + var result models.ListSubscriptionGroupPrepaymentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListSubscriptionGroupPrepaymentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// IssueSubscriptionGroupServiceCredit takes context, uid, body as parameters and -// returns an models.ApiResponse with models.ServiceCreditResponse data and -// an error if there was an issue with the request or response. +// IssueSubscriptionGroupServiceCredit takes context, uid, body as parameters and +// returns an models.ApiResponse with models.ServiceCreditResponse data and +// an error if there was an issue with the request or response. // Credit can be issued for a subscription group identified by the group's `uid`. Credit will be added to the group in the amount specified in the request body. The credit will be applied to group member invoices as they are generated. func (s *SubscriptionGroupInvoiceAccountController) IssueSubscriptionGroupServiceCredit( - ctx context.Context, - uid string, - body *models.IssueServiceCreditRequest) ( - models.ApiResponse[models.ServiceCreditResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscription_groups/%v/service_credits.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ServiceCreditResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ServiceCreditResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string, + body *models.IssueServiceCreditRequest) ( + models.ApiResponse[models.ServiceCreditResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscription_groups/%v/service_credits.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ServiceCreditResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ServiceCreditResponse](decoder) + return models.NewApiResponse(result, resp), err } -// DeductSubscriptionGroupServiceCredit takes context, uid, body as parameters and -// returns an models.ApiResponse with models.ServiceCredit data and -// an error if there was an issue with the request or response. +// DeductSubscriptionGroupServiceCredit takes context, uid, body as parameters and +// returns an models.ApiResponse with models.ServiceCredit data and +// an error if there was an issue with the request or response. // Credit can be deducted for a subscription group identified by the group's `uid`. Credit will be deducted from the group in the amount specified in the request body. func (s *SubscriptionGroupInvoiceAccountController) DeductSubscriptionGroupServiceCredit( - ctx context.Context, - uid string, - body *models.DeductServiceCreditRequest) ( - models.ApiResponse[models.ServiceCredit], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscription_groups/%v/service_credit_deductions.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ServiceCredit - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ServiceCredit](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string, + body *models.DeductServiceCreditRequest) ( + models.ApiResponse[models.ServiceCredit], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscription_groups/%v/service_credit_deductions.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ServiceCredit + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ServiceCredit](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/subscription_group_status_controller.go b/subscription_group_status_controller.go index 46a87d60..dcbeeddc 100644 --- a/subscription_group_status_controller.go +++ b/subscription_group_status_controller.go @@ -1,151 +1,151 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" ) // SubscriptionGroupStatusController represents a controller struct. type SubscriptionGroupStatusController struct { - baseController + baseController } -// NewSubscriptionGroupStatusController creates a new instance of SubscriptionGroupStatusController. +// NewSubscriptionGroupStatusController creates a new instance of SubscriptionGroupStatusController. // It takes a baseController as a parameter and returns a pointer to the SubscriptionGroupStatusController. func NewSubscriptionGroupStatusController(baseController baseController) *SubscriptionGroupStatusController { - subscriptionGroupStatusController := SubscriptionGroupStatusController{baseController: baseController} - return &subscriptionGroupStatusController + subscriptionGroupStatusController := SubscriptionGroupStatusController{baseController: baseController} + return &subscriptionGroupStatusController } -// CancelSubscriptionsInGroup takes context, uid, body as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// This endpoint will immediately cancel all subscriptions within the specified group. The group is identified by it's `uid` passed in the URL. To successfully cancel the group, the primary subscription must be on automatic billing. The group members as well must be on automatic billing or they must be prepaid. +// CancelSubscriptionsInGroup takes context, uid, body as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// This endpoint will immediately cancel all subscriptions within the specified group. The group is identified by it's `uid` passed in the URL. To successfully cancel the group, the primary subscription must be on automatic billing. The group members as well must be on automatic billing or they must be prepaid. // In order to cancel a subscription group while also charging for any unbilled usage on metered or prepaid components, the `charge_unbilled_usage=true` parameter must be included in the request. func (s *SubscriptionGroupStatusController) CancelSubscriptionsInGroup( - ctx context.Context, - uid string, - body *models.CancelGroupedSubscriptionsRequest) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscription_groups/%v/cancel.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + uid string, + body *models.CancelGroupedSubscriptionsRequest) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscription_groups/%v/cancel.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// InitiateDelayedCancellationForGroup takes context, uid as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// This endpoint will schedule all subscriptions within the specified group to be canceled at the end of their billing period. The group is identified by it's uid passed in the URL. +// InitiateDelayedCancellationForGroup takes context, uid as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// This endpoint will schedule all subscriptions within the specified group to be canceled at the end of their billing period. The group is identified by it's uid passed in the URL. // All subscriptions in the group must be on automatic billing in order to successfully cancel them, and the group must not be in a "past_due" state. func (s *SubscriptionGroupStatusController) InitiateDelayedCancellationForGroup( - ctx context.Context, - uid string) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscription_groups/%v/delayed_cancel.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + uid string) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscription_groups/%v/delayed_cancel.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// CancelDelayedCancellationForGroup takes context, uid as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. +// CancelDelayedCancellationForGroup takes context, uid as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. // Removing the delayed cancellation on a subscription group will ensure that the subscriptions do not get canceled at the end of the period. The request will reset the `cancel_at_end_of_period` flag to false on each member in the group. func (s *SubscriptionGroupStatusController) CancelDelayedCancellationForGroup( - ctx context.Context, - uid string) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/subscription_groups/%v/delayed_cancel.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + uid string) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/subscription_groups/%v/delayed_cancel.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// ReactivateSubscriptionGroup takes context, uid, body as parameters and -// returns an models.ApiResponse with models.ReactivateSubscriptionGroupResponse data and -// an error if there was an issue with the request or response. -// This endpoint will attempt to reactivate or resume a cancelled subscription group. Upon reactivation, any canceled invoices created after the beginning of the primary subscription's billing period will be reopened and payment will be attempted on them. If the subscription group is being reactivated (as opposed to resumed), new charges will also be assessed for the new billing period. -// Whether a subscription group is reactivated (a new billing period is created) or resumed (the current billing period is respected) will depend on the parameters that are sent with the request as well as the date of the request relative to the primary subscription's period. -// ## Reactivating within the current period -// If a subscription group is cancelled and reactivated within the primary subscription's current period, we can choose to either start a new billing period or maintain the existing one. If we want to maintain the existing billing period the `resume=true` option must be passed in request parameters. -// An exception to the above are subscriptions that are on calendar billing. These subscriptions cannot be reactivated within the current period. If the `resume=true` option is not passed the request will return an error. -// The `resume_members` option is ignored in this case. All eligible group members will be automatically resumed. -// ## Reactivating beyond the current period -// In this case, a subscription group can only be reactivated with a new billing period. If the `resume=true` option is passed it will be ignored. -// Member subscriptions can have billing periods that are longer than the primary (e.g. a monthly primary with annual group members). If the primary subscription in a group cannot be reactivated within the current period, but other group members can be, passing `resume_members=true` will resume the existing billing period for eligible group members. The primary subscription will begin a new billing period. +// ReactivateSubscriptionGroup takes context, uid, body as parameters and +// returns an models.ApiResponse with models.ReactivateSubscriptionGroupResponse data and +// an error if there was an issue with the request or response. +// This endpoint will attempt to reactivate or resume a cancelled subscription group. Upon reactivation, any canceled invoices created after the beginning of the primary subscription's billing period will be reopened and payment will be attempted on them. If the subscription group is being reactivated (as opposed to resumed), new charges will also be assessed for the new billing period. +// Whether a subscription group is reactivated (a new billing period is created) or resumed (the current billing period is respected) will depend on the parameters that are sent with the request as well as the date of the request relative to the primary subscription's period. +// ## Reactivating within the current period +// If a subscription group is cancelled and reactivated within the primary subscription's current period, we can choose to either start a new billing period or maintain the existing one. If we want to maintain the existing billing period the `resume=true` option must be passed in request parameters. +// An exception to the above are subscriptions that are on calendar billing. These subscriptions cannot be reactivated within the current period. If the `resume=true` option is not passed the request will return an error. +// The `resume_members` option is ignored in this case. All eligible group members will be automatically resumed. +// ## Reactivating beyond the current period +// In this case, a subscription group can only be reactivated with a new billing period. If the `resume=true` option is passed it will be ignored. +// Member subscriptions can have billing periods that are longer than the primary (e.g. a monthly primary with annual group members). If the primary subscription in a group cannot be reactivated within the current period, but other group members can be, passing `resume_members=true` will resume the existing billing period for eligible group members. The primary subscription will begin a new billing period. // For calendar billing subscriptions, the new billing period created will be a partial one, spanning from the date of reactivation to the next corresponding calendar renewal date. func (s *SubscriptionGroupStatusController) ReactivateSubscriptionGroup( - ctx context.Context, - uid string, - body *models.ReactivateSubscriptionGroupRequest) ( - models.ApiResponse[models.ReactivateSubscriptionGroupResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscription_groups/%v/reactivate.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ReactivateSubscriptionGroupResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ReactivateSubscriptionGroupResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string, + body *models.ReactivateSubscriptionGroupRequest) ( + models.ApiResponse[models.ReactivateSubscriptionGroupResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscription_groups/%v/reactivate.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ReactivateSubscriptionGroupResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ReactivateSubscriptionGroupResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/subscription_groups_controller.go b/subscription_groups_controller.go index 6a6665da..31630aac 100644 --- a/subscription_groups_controller.go +++ b/subscription_groups_controller.go @@ -1,302 +1,317 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" ) // SubscriptionGroupsController represents a controller struct. type SubscriptionGroupsController struct { - baseController + baseController } -// NewSubscriptionGroupsController creates a new instance of SubscriptionGroupsController. +// NewSubscriptionGroupsController creates a new instance of SubscriptionGroupsController. // It takes a baseController as a parameter and returns a pointer to the SubscriptionGroupsController. func NewSubscriptionGroupsController(baseController baseController) *SubscriptionGroupsController { - subscriptionGroupsController := SubscriptionGroupsController{baseController: baseController} - return &subscriptionGroupsController + subscriptionGroupsController := SubscriptionGroupsController{baseController: baseController} + return &subscriptionGroupsController } -// SignupWithSubscriptionGroup takes context, body as parameters and -// returns an models.ApiResponse with models.SubscriptionGroupSignupResponse data and -// an error if there was an issue with the request or response. -// Create multiple subscriptions at once under the same customer and consolidate them into a subscription group. -// You must provide one and only one of the `payer_id`/`payer_reference`/`payer_attributes` for the customer attached to the group. -// You must provide one and only one of the `payment_profile_id`/`credit_card_attributes`/`bank_account_attributes` for the payment profile attached to the group. -// Only one of the `subscriptions` can have `"primary": true` attribute set. +// SignupWithSubscriptionGroup takes context, body as parameters and +// returns an models.ApiResponse with models.SubscriptionGroupSignupResponse data and +// an error if there was an issue with the request or response. +// Create multiple subscriptions at once under the same customer and consolidate them into a subscription group. +// You must provide one and only one of the `payer_id`/`payer_reference`/`payer_attributes` for the customer attached to the group. +// You must provide one and only one of the `payment_profile_id`/`credit_card_attributes`/`bank_account_attributes` for the payment profile attached to the group. +// Only one of the `subscriptions` can have `"primary": true` attribute set. // When passing product to a subscription you can use either `product_id` or `product_handle` or `offer_id`. You can also use `custom_price` instead. func (s *SubscriptionGroupsController) SignupWithSubscriptionGroup( - ctx context.Context, - body *models.SubscriptionGroupSignupRequest) ( - models.ApiResponse[models.SubscriptionGroupSignupResponse], - error) { - req := s.prepareRequest(ctx, "POST", "/subscription_groups/signup.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionGroupSignupErrorResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.SubscriptionGroupSignupResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionGroupSignupResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.SubscriptionGroupSignupRequest) ( + models.ApiResponse[models.SubscriptionGroupSignupResponse], + error) { + req := s.prepareRequest(ctx, "POST", "/subscription_groups/signup.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionGroupSignupErrorResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.SubscriptionGroupSignupResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionGroupSignupResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreateSubscriptionGroup takes context, body as parameters and -// returns an models.ApiResponse with models.SubscriptionGroupResponse data and -// an error if there was an issue with the request or response. +// CreateSubscriptionGroup takes context, body as parameters and +// returns an models.ApiResponse with models.SubscriptionGroupResponse data and +// an error if there was an issue with the request or response. // Creates a subscription group with given members. func (s *SubscriptionGroupsController) CreateSubscriptionGroup( - ctx context.Context, - body *models.CreateSubscriptionGroupRequest) ( - models.ApiResponse[models.SubscriptionGroupResponse], - error) { - req := s.prepareRequest(ctx, "POST", "/subscription_groups.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleStringErrorResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.SubscriptionGroupResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionGroupResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.CreateSubscriptionGroupRequest) ( + models.ApiResponse[models.SubscriptionGroupResponse], + error) { + req := s.prepareRequest(ctx, "POST", "/subscription_groups.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionGroupCreateErrorResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.SubscriptionGroupResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionGroupResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListSubscriptionGroupsInput represents the input of the ListSubscriptionGroups endpoint. +type ListSubscriptionGroupsInput struct { + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // A list of additional information to include in the response. The following values are supported: + // - `account_balances`: Account balance information for the subscription groups. Use in query: `include[]=account_balances` + Include []models.SubscriptionGroupsListInclude } -// ListSubscriptionGroups takes context, page, perPage, include as parameters and -// returns an models.ApiResponse with models.ListSubscriptionGroupsResponse data and -// an error if there was an issue with the request or response. -// Returns an array of subscription groups for the site. The response is paginated and will return a `meta` key with pagination information. -// #### Account Balance Information +// ListSubscriptionGroups takes context, page, perPage, include as parameters and +// returns an models.ApiResponse with models.ListSubscriptionGroupsResponse data and +// an error if there was an issue with the request or response. +// Returns an array of subscription groups for the site. The response is paginated and will return a `meta` key with pagination information. +// #### Account Balance Information // Account balance information for the subscription groups is not returned by default. If this information is desired, the `include[]=account_balances` parameter must be provided with the request. func (s *SubscriptionGroupsController) ListSubscriptionGroups( - ctx context.Context, - page *int, - perPage *int, - include *string) ( - models.ApiResponse[models.ListSubscriptionGroupsResponse], - error) { - req := s.prepareRequest(ctx, "GET", "/subscription_groups.json") - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if include != nil { - req.QueryParam("include", *include) - } - var result models.ListSubscriptionGroupsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ListSubscriptionGroupsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListSubscriptionGroupsInput) ( + models.ApiResponse[models.ListSubscriptionGroupsResponse], + error) { + req := s.prepareRequest(ctx, "GET", "/subscription_groups.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Include != nil { + req.QueryParam("include[]", input.Include) + } + var result models.ListSubscriptionGroupsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ListSubscriptionGroupsResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadSubscriptionGroup takes context, uid as parameters and -// returns an models.ApiResponse with models.FullSubscriptionGroupResponse data and -// an error if there was an issue with the request or response. -// Use this endpoint to find subscription group details. -// #### Current Billing Amount in Cents +// ReadSubscriptionGroup takes context, uid, include as parameters and +// returns an models.ApiResponse with models.FullSubscriptionGroupResponse data and +// an error if there was an issue with the request or response. +// Use this endpoint to find subscription group details. +// #### Current Billing Amount in Cents // Current billing amount for the subscription group is not returned by default. If this information is desired, the `include[]=current_billing_amount_in_cents` parameter must be provided with the request. func (s *SubscriptionGroupsController) ReadSubscriptionGroup( - ctx context.Context, - uid string) ( - models.ApiResponse[models.FullSubscriptionGroupResponse], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscription_groups/%v.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.FullSubscriptionGroupResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.FullSubscriptionGroupResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string, + include []models.SubscriptionGroupInclude) ( + models.ApiResponse[models.FullSubscriptionGroupResponse], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscription_groups/%v.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + if include != nil { + req.QueryParam("include[]", include) + } + + var result models.FullSubscriptionGroupResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.FullSubscriptionGroupResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateSubscriptionGroupMembers takes context, uid, body as parameters and -// returns an models.ApiResponse with models.SubscriptionGroupResponse data and -// an error if there was an issue with the request or response. -// Use this endpoint to update subscription group members. +// UpdateSubscriptionGroupMembers takes context, uid, body as parameters and +// returns an models.ApiResponse with models.SubscriptionGroupResponse data and +// an error if there was an issue with the request or response. +// Use this endpoint to update subscription group members. // `"member_ids": []` should contain an array of both subscription IDs to set as group members and subscription IDs already present in the groups. Not including them will result in removing them from subscription group. To clean up members, just leave the array empty. func (s *SubscriptionGroupsController) UpdateSubscriptionGroupMembers( - ctx context.Context, - uid string, - body *models.UpdateSubscriptionGroupRequest) ( - models.ApiResponse[models.SubscriptionGroupResponse], - error) { - req := s.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/subscription_groups/%v.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionGroupUpdateErrorResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionGroupResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionGroupResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string, + body *models.UpdateSubscriptionGroupRequest) ( + models.ApiResponse[models.SubscriptionGroupResponse], + error) { + req := s.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/subscription_groups/%v.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionGroupUpdateErrorResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionGroupResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionGroupResponse](decoder) + return models.NewApiResponse(result, resp), err } -// DeleteSubscriptionGroup takes context, uid as parameters and -// returns an models.ApiResponse with models.DeleteSubscriptionGroupResponse data and -// an error if there was an issue with the request or response. -// Use this endpoint to delete subscription group. +// DeleteSubscriptionGroup takes context, uid as parameters and +// returns an models.ApiResponse with models.DeleteSubscriptionGroupResponse data and +// an error if there was an issue with the request or response. +// Use this endpoint to delete subscription group. // Only groups without members can be deleted func (s *SubscriptionGroupsController) DeleteSubscriptionGroup( - ctx context.Context, - uid string) ( - models.ApiResponse[models.DeleteSubscriptionGroupResponse], - error) { - req := s.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/subscription_groups/%v.json", uid), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - - var result models.DeleteSubscriptionGroupResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.DeleteSubscriptionGroupResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + uid string) ( + models.ApiResponse[models.DeleteSubscriptionGroupResponse], + error) { + req := s.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/subscription_groups/%v.json", uid), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + + var result models.DeleteSubscriptionGroupResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.DeleteSubscriptionGroupResponse](decoder) + return models.NewApiResponse(result, resp), err } -// FindSubscriptionGroup takes context, subscriptionId as parameters and -// returns an models.ApiResponse with models.FullSubscriptionGroupResponse data and -// an error if there was an issue with the request or response. -// Use this endpoint to find subscription group associated with subscription. +// FindSubscriptionGroup takes context, subscriptionId as parameters and +// returns an models.ApiResponse with models.FullSubscriptionGroupResponse data and +// an error if there was an issue with the request or response. +// Use this endpoint to find subscription group associated with subscription. // If the subscription is not in a group endpoint will return 404 code. func (s *SubscriptionGroupsController) FindSubscriptionGroup( - ctx context.Context, - subscriptionId string) ( - models.ApiResponse[models.FullSubscriptionGroupResponse], - error) { - req := s.prepareRequest(ctx, "GET", "/subscription_groups/lookup.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - req.QueryParam("subscription_id", subscriptionId) - var result models.FullSubscriptionGroupResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.FullSubscriptionGroupResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId string) ( + models.ApiResponse[models.FullSubscriptionGroupResponse], + error) { + req := s.prepareRequest(ctx, "GET", "/subscription_groups/lookup.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + req.QueryParam("subscription_id", subscriptionId) + var result models.FullSubscriptionGroupResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.FullSubscriptionGroupResponse](decoder) + return models.NewApiResponse(result, resp), err } -// AddSubscriptionToGroup takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.SubscriptionGroupResponse data and -// an error if there was an issue with the request or response. -// For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to add existing subscriptions to subscription groups. -// Passing `group` parameters with a `target` containing a `type` and optional `id` is all that's needed. When the `target` parameter specifies a `"customer"` or `"subscription"` that is already part of a hierarchy, the subscription will become a member of the customer's subscription group. If the target customer or subscription is not part of a subscription group, a new group will be created and the subscription will become part of the group with the specified target customer set as the responsible payer for the group's subscriptions. -// **Please Note:** In order to add an existing subscription to a subscription group, it must belong to either the same customer record as the target, or be within the same customer hierarchy. -// Rather than specifying a customer, the `target` parameter could instead simply have a value of -// * `"self"` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer, -// * `"parent"` which indicates the subscription will be paid for by the subscribing customer's parent within a customer hierarchy, or -// * `"eldest"` which indicates the subscription will be paid for by the root-level customer in the subscribing customer's hierarchy. -// To create a new subscription into a subscription group, please reference the following: +// AddSubscriptionToGroup takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.SubscriptionGroupResponse data and +// an error if there was an issue with the request or response. +// For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to add existing subscriptions to subscription groups. +// Passing `group` parameters with a `target` containing a `type` and optional `id` is all that's needed. When the `target` parameter specifies a `"customer"` or `"subscription"` that is already part of a hierarchy, the subscription will become a member of the customer's subscription group. If the target customer or subscription is not part of a subscription group, a new group will be created and the subscription will become part of the group with the specified target customer set as the responsible payer for the group's subscriptions. +// **Please Note:** In order to add an existing subscription to a subscription group, it must belong to either the same customer record as the target, or be within the same customer hierarchy. +// Rather than specifying a customer, the `target` parameter could instead simply have a value of +// * `"self"` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer, +// * `"parent"` which indicates the subscription will be paid for by the subscribing customer's parent within a customer hierarchy, or +// * `"eldest"` which indicates the subscription will be paid for by the root-level customer in the subscribing customer's hierarchy. +// To create a new subscription into a subscription group, please reference the following: // [Create Subscription in a Subscription Group](https://developers.chargify.com/docs/api-docs/d571659cf0f24-create-subscription#subscription-in-a-subscription-group) func (s *SubscriptionGroupsController) AddSubscriptionToGroup( - ctx context.Context, - subscriptionId int, - body *models.AddSubscriptionToAGroup) ( - models.ApiResponse[models.SubscriptionGroupResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/group.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionGroupResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionGroupResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.AddSubscriptionToAGroup) ( + models.ApiResponse[models.SubscriptionGroupResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/group.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionGroupResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionGroupResponse](decoder) + return models.NewApiResponse(result, resp), err } -// RemoveSubscriptionFromGroup takes context, subscriptionId as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. +// RemoveSubscriptionFromGroup takes context, subscriptionId as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. // For sites making use of the [Relationship Billing](https://chargify.zendesk.com/hc/en-us/articles/4407737494171) and [Customer Hierarchy](https://chargify.zendesk.com/hc/en-us/articles/4407746683291) features, it is possible to remove existing subscription from subscription group. func (s *SubscriptionGroupsController) RemoveSubscriptionFromGroup( - ctx context.Context, - subscriptionId int) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/subscriptions/%v/group.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subscriptionId int) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/subscriptions/%v/group.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } diff --git a/subscription_invoice_account_controller.go b/subscription_invoice_account_controller.go index b710cd5d..642cd7b5 100644 --- a/subscription_invoice_account_controller.go +++ b/subscription_invoice_account_controller.go @@ -1,233 +1,249 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" - "time" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" + "time" ) // SubscriptionInvoiceAccountController represents a controller struct. type SubscriptionInvoiceAccountController struct { - baseController + baseController } -// NewSubscriptionInvoiceAccountController creates a new instance of SubscriptionInvoiceAccountController. +// NewSubscriptionInvoiceAccountController creates a new instance of SubscriptionInvoiceAccountController. // It takes a baseController as a parameter and returns a pointer to the SubscriptionInvoiceAccountController. func NewSubscriptionInvoiceAccountController(baseController baseController) *SubscriptionInvoiceAccountController { - subscriptionInvoiceAccountController := SubscriptionInvoiceAccountController{baseController: baseController} - return &subscriptionInvoiceAccountController + subscriptionInvoiceAccountController := SubscriptionInvoiceAccountController{baseController: baseController} + return &subscriptionInvoiceAccountController } -// ReadAccountBalances takes context, subscriptionId as parameters and -// returns an models.ApiResponse with models.AccountBalances data and -// an error if there was an issue with the request or response. +// ReadAccountBalances takes context, subscriptionId as parameters and +// returns an models.ApiResponse with models.AccountBalances data and +// an error if there was an issue with the request or response. // Returns the `balance_in_cents` of the Subscription's Pending Discount, Service Credit, and Prepayment accounts, as well as the sum of the Subscription's open, payable invoices. func (s *SubscriptionInvoiceAccountController) ReadAccountBalances( - ctx context.Context, - subscriptionId int) ( - models.ApiResponse[models.AccountBalances], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v/account_balances.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.AccountBalances - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.AccountBalances](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int) ( + models.ApiResponse[models.AccountBalances], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v/account_balances.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.AccountBalances + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.AccountBalances](decoder) + return models.NewApiResponse(result, resp), err } -// CreatePrepayment takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.CreatePrepaymentResponse data and -// an error if there was an issue with the request or response. -// ## Create Prepayment -// In order to specify a prepayment made against a subscription, specify the `amount, memo, details, method`. -// When the `method` specified is `"credit_card_on_file"`, the prepayment amount will be collected using the default credit card payment profile and applied to the prepayment account balance. This is especially useful for manual replenishment of prepaid subscriptions. +// CreatePrepayment takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.CreatePrepaymentResponse data and +// an error if there was an issue with the request or response. +// ## Create Prepayment +// In order to specify a prepayment made against a subscription, specify the `amount, memo, details, method`. +// When the `method` specified is `"credit_card_on_file"`, the prepayment amount will be collected using the default credit card payment profile and applied to the prepayment account balance. This is especially useful for manual replenishment of prepaid subscriptions. // Please note that you **can't** pass `amount_in_cents`. func (s *SubscriptionInvoiceAccountController) CreatePrepayment( - ctx context.Context, - subscriptionId int, - body *models.CreatePrepaymentRequest) ( - models.ApiResponse[models.CreatePrepaymentResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/prepayments.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.CreatePrepaymentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.CreatePrepaymentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.CreatePrepaymentRequest) ( + models.ApiResponse[models.CreatePrepaymentResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/prepayments.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'."}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.CreatePrepaymentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.CreatePrepaymentResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListPrepayments takes context, subscriptionId, page, perPage, filterDateField, filterStartDate, filterEndDate as parameters and -// returns an models.ApiResponse with models.PrepaymentsResponse data and -// an error if there was an issue with the request or response. +// ListPrepaymentsInput represents the input of the ListPrepayments endpoint. +type ListPrepaymentsInput struct { + // The Chargify id of the subscription + SubscriptionId int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The type of filter you would like to apply to your search. created_at - Time when prepayment was created. application_at - Time when prepayment was applied to invoice. Use in query `filter[date_field]=created_at`. + FilterDateField *models.BasicDateField + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns prepayments with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `filter[start_date]=2011-12-15`. + FilterStartDate *time.Time + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns prepayments with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `filter[end_date]=2011-12-15`. + FilterEndDate *time.Time +} + +// ListPrepayments takes context, subscriptionId, page, perPage, filterDateField, filterStartDate, filterEndDate as parameters and +// returns an models.ApiResponse with models.PrepaymentsResponse data and +// an error if there was an issue with the request or response. // This request will list a subscription's prepayments. func (s *SubscriptionInvoiceAccountController) ListPrepayments( - ctx context.Context, - subscriptionId int, - page *int, - perPage *int, - filterDateField *models.BasicDateField, - filterStartDate *time.Time, - filterEndDate *time.Time) ( - models.ApiResponse[models.PrepaymentsResponse], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v/prepayments.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if filterDateField != nil { - req.QueryParam("filter[date_field]", *filterDateField) - } - if filterStartDate != nil { - req.QueryParam("filter[start_date]", filterStartDate.Format(models.DEFAULT_DATE)) - } - if filterEndDate != nil { - req.QueryParam("filter[end_date]", filterEndDate.Format(models.DEFAULT_DATE)) - } - - var result models.PrepaymentsResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.PrepaymentsResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListPrepaymentsInput) ( + models.ApiResponse[models.PrepaymentsResponse], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v/prepayments.json", input.SubscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.FilterDateField != nil { + req.QueryParam("filter[date_field]", *input.FilterDateField) + } + if input.FilterStartDate != nil { + req.QueryParam("filter[start_date]", input.FilterStartDate.Format(models.DEFAULT_DATE)) + } + if input.FilterEndDate != nil { + req.QueryParam("filter[end_date]", input.FilterEndDate.Format(models.DEFAULT_DATE)) + } + + var result models.PrepaymentsResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.PrepaymentsResponse](decoder) + return models.NewApiResponse(result, resp), err } -// IssueServiceCredit takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.ServiceCredit data and -// an error if there was an issue with the request or response. +// IssueServiceCredit takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.ServiceCredit data and +// an error if there was an issue with the request or response. // Credit will be added to the subscription in the amount specified in the request body. The credit is subsequently applied to the next generated invoice. func (s *SubscriptionInvoiceAccountController) IssueServiceCredit( - ctx context.Context, - subscriptionId int, - body *models.IssueServiceCreditRequest) ( - models.ApiResponse[models.ServiceCredit], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/service_credits.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.ServiceCredit - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ServiceCredit](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.IssueServiceCreditRequest) ( + models.ApiResponse[models.ServiceCredit], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/service_credits.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.ServiceCredit + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ServiceCredit](decoder) + return models.NewApiResponse(result, resp), err } -// DeductServiceCredit takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. +// DeductServiceCredit takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. // Credit will be removed from the subscription in the amount specified in the request body. The credit amount being deducted must be equal to or less than the current credit balance. func (s *SubscriptionInvoiceAccountController) DeductServiceCredit( - ctx context.Context, - subscriptionId int, - body *models.DeductServiceCreditRequest) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/service_credit_deductions.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subscriptionId int, + body *models.DeductServiceCreditRequest) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/service_credit_deductions.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// RefundPrepayment takes context, subscriptionId, prepaymentId, body as parameters and -// returns an models.ApiResponse with models.PrepaymentResponse data and -// an error if there was an issue with the request or response. -// This endpoint will refund, completely or partially, a particular prepayment applied to a subscription. The `prepayment_id` will be the account transaction ID of the original payment. The prepayment must have some amount remaining in order to be refunded. +// RefundPrepayment takes context, subscriptionId, prepaymentId, body as parameters and +// returns an models.ApiResponse with models.PrepaymentResponse data and +// an error if there was an issue with the request or response. +// This endpoint will refund, completely or partially, a particular prepayment applied to a subscription. The `prepayment_id` will be the account transaction ID of the original payment. The prepayment must have some amount remaining in order to be refunded. // The amount may be passed either as a decimal, with `amount`, or an integer in cents, with `amount_in_cents`. func (s *SubscriptionInvoiceAccountController) RefundPrepayment( - ctx context.Context, - subscriptionId int, - prepaymentId string, - body *models.RefundPrepaymentRequest) ( - models.ApiResponse[models.PrepaymentResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/prepayments/%v/refunds.json", subscriptionId, prepaymentId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "400": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewRefundPrepaymentBaseErrorsResponse}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewRefundPrepaymentAggregatedErrorsResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.PrepaymentResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.PrepaymentResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + prepaymentId string, + body *models.RefundPrepaymentRequest) ( + models.ApiResponse[models.PrepaymentResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/prepayments/%v/refunds.json", subscriptionId, prepaymentId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "400": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewRefundPrepaymentBaseErrorsResponse}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewRefundPrepaymentAggregatedErrorsResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.PrepaymentResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.PrepaymentResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/subscription_notes_controller.go b/subscription_notes_controller.go index 6cca5a18..574c9545 100644 --- a/subscription_notes_controller.go +++ b/subscription_notes_controller.go @@ -1,173 +1,183 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" ) // SubscriptionNotesController represents a controller struct. type SubscriptionNotesController struct { - baseController + baseController } -// NewSubscriptionNotesController creates a new instance of SubscriptionNotesController. +// NewSubscriptionNotesController creates a new instance of SubscriptionNotesController. // It takes a baseController as a parameter and returns a pointer to the SubscriptionNotesController. func NewSubscriptionNotesController(baseController baseController) *SubscriptionNotesController { - subscriptionNotesController := SubscriptionNotesController{baseController: baseController} - return &subscriptionNotesController + subscriptionNotesController := SubscriptionNotesController{baseController: baseController} + return &subscriptionNotesController } -// CreateSubscriptionNote takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.SubscriptionNoteResponse data and -// an error if there was an issue with the request or response. -// Use the following method to create a note for a subscription. -// ## How to Use Subscription Notes -// Notes allow you to record information about a particular Subscription in a free text format. -// If you have structured data such as birth date, color, etc., consider using Metadata instead. +// CreateSubscriptionNote takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.SubscriptionNoteResponse data and +// an error if there was an issue with the request or response. +// Use the following method to create a note for a subscription. +// ## How to Use Subscription Notes +// Notes allow you to record information about a particular Subscription in a free text format. +// If you have structured data such as birth date, color, etc., consider using Metadata instead. // Full documentation on how to use Notes in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404434903181-Subscription-Summary#notes). func (s *SubscriptionNotesController) CreateSubscriptionNote( - ctx context.Context, - subscriptionId int, - body *models.UpdateSubscriptionNoteRequest) ( - models.ApiResponse[models.SubscriptionNoteResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/notes.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionNoteResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionNoteResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.UpdateSubscriptionNoteRequest) ( + models.ApiResponse[models.SubscriptionNoteResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/notes.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionNoteResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionNoteResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListSubscriptionNotesInput represents the input of the ListSubscriptionNotes endpoint. +type ListSubscriptionNotesInput struct { + // The Chargify id of the subscription + SubscriptionId int + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int } -// ListSubscriptionNotes takes context, subscriptionId, page, perPage as parameters and -// returns an models.ApiResponse with []models.SubscriptionNoteResponse data and -// an error if there was an issue with the request or response. +// ListSubscriptionNotes takes context, subscriptionId, page, perPage as parameters and +// returns an models.ApiResponse with []models.SubscriptionNoteResponse data and +// an error if there was an issue with the request or response. // Use this method to retrieve a list of Notes associated with a Subscription. The response will be an array of Notes. func (s *SubscriptionNotesController) ListSubscriptionNotes( - ctx context.Context, - subscriptionId int, - page *int, - perPage *int) ( - models.ApiResponse[[]models.SubscriptionNoteResponse], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v/notes.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - - var result []models.SubscriptionNoteResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.SubscriptionNoteResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListSubscriptionNotesInput) ( + models.ApiResponse[[]models.SubscriptionNoteResponse], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v/notes.json", input.SubscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + + var result []models.SubscriptionNoteResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.SubscriptionNoteResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadSubscriptionNote takes context, subscriptionId, noteId as parameters and -// returns an models.ApiResponse with models.SubscriptionNoteResponse data and -// an error if there was an issue with the request or response. +// ReadSubscriptionNote takes context, subscriptionId, noteId as parameters and +// returns an models.ApiResponse with models.SubscriptionNoteResponse data and +// an error if there was an issue with the request or response. // Once you have obtained the ID of the note you wish to read, use this method to show a particular note attached to a subscription. func (s *SubscriptionNotesController) ReadSubscriptionNote( - ctx context.Context, - subscriptionId int, - noteId int) ( - models.ApiResponse[models.SubscriptionNoteResponse], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v/notes/%v.json", subscriptionId, noteId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.SubscriptionNoteResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionNoteResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + noteId int) ( + models.ApiResponse[models.SubscriptionNoteResponse], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v/notes/%v.json", subscriptionId, noteId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.SubscriptionNoteResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionNoteResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateSubscriptionNote takes context, subscriptionId, noteId, body as parameters and -// returns an models.ApiResponse with models.SubscriptionNoteResponse data and -// an error if there was an issue with the request or response. +// UpdateSubscriptionNote takes context, subscriptionId, noteId, body as parameters and +// returns an models.ApiResponse with models.SubscriptionNoteResponse data and +// an error if there was an issue with the request or response. // Use the following method to update a note for a Subscription. func (s *SubscriptionNotesController) UpdateSubscriptionNote( - ctx context.Context, - subscriptionId int, - noteId int, - body *models.UpdateSubscriptionNoteRequest) ( - models.ApiResponse[models.SubscriptionNoteResponse], - error) { - req := s.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/subscriptions/%v/notes/%v.json", subscriptionId, noteId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionNoteResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionNoteResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + noteId int, + body *models.UpdateSubscriptionNoteRequest) ( + models.ApiResponse[models.SubscriptionNoteResponse], + error) { + req := s.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/subscriptions/%v/notes/%v.json", subscriptionId, noteId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionNoteResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionNoteResponse](decoder) + return models.NewApiResponse(result, resp), err } -// DeleteSubscriptionNote takes context, subscriptionId, noteId as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. +// DeleteSubscriptionNote takes context, subscriptionId, noteId as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. // Use the following method to delete a note for a Subscription. func (s *SubscriptionNotesController) DeleteSubscriptionNote( - ctx context.Context, - subscriptionId int, - noteId int) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/subscriptions/%v/notes/%v.json", subscriptionId, noteId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subscriptionId int, + noteId int) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/subscriptions/%v/notes/%v.json", subscriptionId, noteId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } diff --git a/subscription_products_controller.go b/subscription_products_controller.go index 795d7fd4..8562d8ac 100644 --- a/subscription_products_controller.go +++ b/subscription_products_controller.go @@ -1,129 +1,129 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" ) // SubscriptionProductsController represents a controller struct. type SubscriptionProductsController struct { - baseController + baseController } -// NewSubscriptionProductsController creates a new instance of SubscriptionProductsController. +// NewSubscriptionProductsController creates a new instance of SubscriptionProductsController. // It takes a baseController as a parameter and returns a pointer to the SubscriptionProductsController. func NewSubscriptionProductsController(baseController baseController) *SubscriptionProductsController { - subscriptionProductsController := SubscriptionProductsController{baseController: baseController} - return &subscriptionProductsController + subscriptionProductsController := SubscriptionProductsController{baseController: baseController} + return &subscriptionProductsController } -// MigrateSubscriptionProduct takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// In order to create a migration, you must pass the `product_id` or `product_handle` in the object when you send a POST request. You may also pass either a `product_price_point_id` or `product_price_point_handle` to choose which price point the subscription is moved to. If no price point identifier is passed the subscription will be moved to the products default price point. The response will be the updated subscription. -// ## Valid Subscriptions -// Subscriptions should be in the `active` or `trialing` state in order to be migrated. -// (For backwards compatibility reasons, it is possible to migrate a subscription that is in the `trial_ended` state via the API, however this is not recommended. Since `trial_ended` is an end-of-life state, the subscription should be canceled, the product changed, and then the subscription can be reactivated.) -// ## Migrations Documentation -// Full documentation on how to record Migrations in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407898373531). -// ## Failed Migrations -// One of the most common ways that a migration can fail is when the attempt is made to migrate a subscription to it's current product. Please be aware of this issue! -// ## Migration 3D Secure - Stripe -// It may happen that a payment needs 3D Secure Authentication when the subscription is migrated to a new product; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: -// ```json -// { -// "errors": [ -// "Your card was declined. This transaction requires 3D secure authentication." -// ], -// "gateway_payment_id": "pi_1F0aGoJ2UDb3Q4av7zU3sHPh", -// "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", -// "action_link": "http://acme.chargify.com/3d-secure/pi_1F0aGoJ2UDb3Q4av7zU3sHPh?one_time_token_id=242" -// } -// ``` -// To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. -// Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: -// - whether the authentication was successful (`success`) -// - the gateway ID for the payment (`gateway_payment_id`) -// - the subscription ID (`subscription_id`) -// Lastly, you can also specify a `redirect_url` within the `action_link` URL if you’d like to redirect a customer back to your site. -// It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. -// The final URL that you send a customer to to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com` -// ### Example Redirect Flow -// You may wish to redirect customers to different pages depending on whether their SCA was performed successfully. Here's an example flow to use as a reference: -// 1. Create a migration via API; it requires 3DS -// 2. You receive a `gateway_payment_id` in the `action_link` along other params in the response. -// 3. Use this `gateway_payment_id` to, for example, connect with your internal resources or generate a session_id -// 4. Include 1 of those attributes inside the `callback_url` and `redirect_url` to be aware which “session” this applies to -// 5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied -// 6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. -// 7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known +// MigrateSubscriptionProduct takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// In order to create a migration, you must pass the `product_id` or `product_handle` in the object when you send a POST request. You may also pass either a `product_price_point_id` or `product_price_point_handle` to choose which price point the subscription is moved to. If no price point identifier is passed the subscription will be moved to the products default price point. The response will be the updated subscription. +// ## Valid Subscriptions +// Subscriptions should be in the `active` or `trialing` state in order to be migrated. +// (For backwards compatibility reasons, it is possible to migrate a subscription that is in the `trial_ended` state via the API, however this is not recommended. Since `trial_ended` is an end-of-life state, the subscription should be canceled, the product changed, and then the subscription can be reactivated.) +// ## Migrations Documentation +// Full documentation on how to record Migrations in the Chargify UI can be located [here](https://chargify.zendesk.com/hc/en-us/articles/4407898373531). +// ## Failed Migrations +// One of the most common ways that a migration can fail is when the attempt is made to migrate a subscription to it's current product. Please be aware of this issue! +// ## Migration 3D Secure - Stripe +// It may happen that a payment needs 3D Secure Authentication when the subscription is migrated to a new product; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: +// ```json +// { +// "errors": [ +// "Your card was declined. This transaction requires 3D secure authentication." +// ], +// "gateway_payment_id": "pi_1F0aGoJ2UDb3Q4av7zU3sHPh", +// "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", +// "action_link": "http://acme.chargify.com/3d-secure/pi_1F0aGoJ2UDb3Q4av7zU3sHPh?one_time_token_id=242" +// } +// ``` +// To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. +// Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: +// - whether the authentication was successful (`success`) +// - the gateway ID for the payment (`gateway_payment_id`) +// - the subscription ID (`subscription_id`) +// Lastly, you can also specify a `redirect_url` within the `action_link` URL if you’d like to redirect a customer back to your site. +// It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. +// The final URL that you send a customer to to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com` +// ### Example Redirect Flow +// You may wish to redirect customers to different pages depending on whether their SCA was performed successfully. Here's an example flow to use as a reference: +// 1. Create a migration via API; it requires 3DS +// 2. You receive a `gateway_payment_id` in the `action_link` along other params in the response. +// 3. Use this `gateway_payment_id` to, for example, connect with your internal resources or generate a session_id +// 4. Include 1 of those attributes inside the `callback_url` and `redirect_url` to be aware which “session” this applies to +// 5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied +// 6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. +// 7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known // 8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not. func (s *SubscriptionProductsController) MigrateSubscriptionProduct( - ctx context.Context, - subscriptionId int, - body *models.SubscriptionProductMigrationRequest) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/migrations.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.SubscriptionProductMigrationRequest) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/migrations.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// PreviewSubscriptionProductMigration takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.SubscriptionMigrationPreviewResponse data and -// an error if there was an issue with the request or response. -// ## Previewing a future date -// It is also possible to preview the migration for a date in the future, as long as it's still within the subscription's current billing period, by passing a `proration_date` along with the request (eg: `"proration_date": "2020-12-18T18:25:43.511Z"`). +// PreviewSubscriptionProductMigration takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.SubscriptionMigrationPreviewResponse data and +// an error if there was an issue with the request or response. +// ## Previewing a future date +// It is also possible to preview the migration for a date in the future, as long as it's still within the subscription's current billing period, by passing a `proration_date` along with the request (eg: `"proration_date": "2020-12-18T18:25:43.511Z"`). // This will calculate the prorated adjustment, charge, payment and credit applied values assuming the migration is done at that date in the future as opposed to right now. func (s *SubscriptionProductsController) PreviewSubscriptionProductMigration( - ctx context.Context, - subscriptionId int, - body *models.SubscriptionMigrationPreviewRequest) ( - models.ApiResponse[models.SubscriptionMigrationPreviewResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/migrations/preview.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionMigrationPreviewResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionMigrationPreviewResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.SubscriptionMigrationPreviewRequest) ( + models.ApiResponse[models.SubscriptionMigrationPreviewResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/migrations/preview.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionMigrationPreviewResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionMigrationPreviewResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/subscription_status_controller.go b/subscription_status_controller.go index 7d067de0..15ad2d7c 100644 --- a/subscription_status_controller.go +++ b/subscription_status_controller.go @@ -1,465 +1,465 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" ) // SubscriptionStatusController represents a controller struct. type SubscriptionStatusController struct { - baseController + baseController } -// NewSubscriptionStatusController creates a new instance of SubscriptionStatusController. +// NewSubscriptionStatusController creates a new instance of SubscriptionStatusController. // It takes a baseController as a parameter and returns a pointer to the SubscriptionStatusController. func NewSubscriptionStatusController(baseController baseController) *SubscriptionStatusController { - subscriptionStatusController := SubscriptionStatusController{baseController: baseController} - return &subscriptionStatusController + subscriptionStatusController := SubscriptionStatusController{baseController: baseController} + return &subscriptionStatusController } -// RetrySubscription takes context, subscriptionId as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// Chargify offers the ability to retry collecting the balance due on a past due Subscription without waiting for the next scheduled attempt. -// ## Successful Reactivation -// The response will be `200 OK` with the updated Subscription. -// ## Failed Reactivation +// RetrySubscription takes context, subscriptionId as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// Chargify offers the ability to retry collecting the balance due on a past due Subscription without waiting for the next scheduled attempt. +// ## Successful Reactivation +// The response will be `200 OK` with the updated Subscription. +// ## Failed Reactivation // The response will be `422 "Unprocessable Entity`. func (s *SubscriptionStatusController) RetrySubscription( - ctx context.Context, - subscriptionId int) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/subscriptions/%v/retry.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/subscriptions/%v/retry.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CancelSubscription takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. +// CancelSubscription takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. // The DELETE action causes the cancellation of the Subscription. This means, the method sets the Subscription state to "canceled". func (s *SubscriptionStatusController) CancelSubscription( - ctx context.Context, - subscriptionId int, - body *models.CancellationRequest) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/subscriptions/%v.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'."}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.CancellationRequest) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/subscriptions/%v.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'."}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ResumeSubscription takes context, subscriptionId, calendarBillingResumptionCharge as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. +// ResumeSubscription takes context, subscriptionId, calendarBillingResumptionCharge as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. // Resume a paused (on-hold) subscription. If the normal next renewal date has not passed, the subscription will return to active and will renew on that date. Otherwise, it will behave like a reactivation, setting the billing date to 'now' and charging the subscriber. func (s *SubscriptionStatusController) ResumeSubscription( - ctx context.Context, - subscriptionId int, - calendarBillingResumptionCharge *models.ResumptionCharge) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/resume.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - if calendarBillingResumptionCharge != nil { - req.QueryParam("calendar_billing['resumption_charge']", *calendarBillingResumptionCharge) - } - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + calendarBillingResumptionCharge *models.ResumptionCharge) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/resume.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + if calendarBillingResumptionCharge != nil { + req.QueryParam("calendar_billing['resumption_charge']", *calendarBillingResumptionCharge) + } + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// PauseSubscription takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// This will place the subscription in the on_hold state and it will not renew. -// ## Limitations +// PauseSubscription takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// This will place the subscription in the on_hold state and it will not renew. +// ## Limitations // You may not place a subscription on hold if the `next_billing` date is within 24 hours. func (s *SubscriptionStatusController) PauseSubscription( - ctx context.Context, - subscriptionId int, - body *models.PauseRequest) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/hold.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.PauseRequest) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/hold.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateAutomaticSubscriptionResumption takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// Once a subscription has been paused / put on hold, you can update the date which was specified to automatically resume the subscription. -// To update a subscription's resume date, use this method to change or update the `automatically_resume_at` date. -// ### Remove the resume date +// UpdateAutomaticSubscriptionResumption takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// Once a subscription has been paused / put on hold, you can update the date which was specified to automatically resume the subscription. +// To update a subscription's resume date, use this method to change or update the `automatically_resume_at` date. +// ### Remove the resume date // Alternately, you can change the `automatically_resume_at` to `null` if you would like the subscription to not have a resume date. func (s *SubscriptionStatusController) UpdateAutomaticSubscriptionResumption( - ctx context.Context, - subscriptionId int, - body *models.PauseRequest) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/subscriptions/%v/hold.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.PauseRequest) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/subscriptions/%v/hold.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReactivateSubscription takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// Chargify offers the ability to reactivate a previously canceled subscription. For details on how the reactivation works, and how to reactivate subscriptions through the application, see [reactivation](https://chargify.zendesk.com/hc/en-us/articles/4407898737691). -// **Please note: The term -// "resume" is used also during another process in Chargify. This occurs when an on-hold subscription is "resumed". This returns the subscription to an active state.** -// + The response returns the subscription object in the `active` or `trialing` state. -// + The `canceled_at` and `cancellation_message` fields do not have values. -// + The method works for "Canceled" or "Trial Ended" subscriptions. -// + It will not work for items not marked as "Canceled", "Unpaid", or "Trial Ended". -// ## Resume the current billing period for a subscription -// A subscription is considered "resumable" if you are attempting to reactivate within the billing period the subscription was canceled in. -// A resumed subscription's billing date remains the same as before it was canceled. In other words, it does not start a new billing period. Payment may or may not be collected for a resumed subscription, depending on whether or not the subscription had a balance when it was canceled (for example, if it was canceled because of dunning). -// Consider a subscription which was created on June 1st, and would renew on July 1st. The subscription is then canceled on June 15. -// If a reactivation with `resume: true` were attempted _before_ what would have been the next billing date of July 1st, then Chargify would resume the subscription. -// If a reactivation with `resume: true` were attempted _after_ what would have been the next billing date of July 1st, then Chargify would not resume the subscription, and instead it would be reactivated with a new billing period. -// | Canceled | Reactivation | Resumable? | -// |---|---|---| -// | Jun 15 | June 28 | Yes | -// | Jun 15 | July 2 | No | -// ## Reactivation Scenarios -// ### Reactivating Canceled Subscription While Preserving Balance -// + Given you have a product that costs $20 -// + Given you have a canceled subscription to the $20 product -// + 1 charge should exist for $20 -// + 1 payment should exist for $20 -// + When the subscription has canceled due to dunning, it retained a negative balance of $20 -// #### Results -// The resulting charges upon reactivation will be: -// + 1 charge for $20 for the new product -// + 1 charge for $20 for the balance due -// + Total charges = $40 -// + The subscription will transition to active -// + The subscription balance will be zero -// ### Reactivating a Canceled Subscription With Coupon -// + Given you have a canceled subscription -// + It has no current period defined -// + You have a coupon code "EARLYBIRD" -// + The coupon is set to recur for 6 periods -// PUT request sent to: -// `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?coupon_code=EARLYBIRD` -// #### Results -// + The subscription will transition to active -// + The subscription should have applied a coupon with code "EARLYBIRD" -// ### Reactivating Canceled Subscription With a Trial, Without the include_trial Flag -// + Given you have a canceled subscription -// + The product associated with the subscription has a trial -// + PUT request to -// `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json` -// #### Results -// + The subscription will transition to active -// ### Reactivating Canceled Subscription With Trial, With the include_trial Flag -// + Given you have a canceled subscription -// + The product associated with the subscription has a trial -// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?include_trial=1` -// #### Results -// + The subscription will transition to trialing -// ### Reactivating Trial Ended Subscription -// + Given you have a trial_ended subscription -// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json` -// #### Results -// + The subscription will transition to active -// ### Resuming a Canceled Subscription -// + Given you have a `canceled` subscription and it is resumable -// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?resume=true` -// #### Results -// + The subscription will transition to active -// + The next billing date should not have changed -// ### Attempting to resume a subscription which is not resumable -// + Given you have a `canceled` subscription, and it is not resumable -// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?resume=true` -// #### Results -// + The subscription will transition to active, with a new billing period. -// ### Attempting to resume but not reactivate a subscription which is not resumable -// + Given you have a `canceled` subscription, and it is not resumable -// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?resume[require_resume]=true` -// + The response status should be "422 UNPROCESSABLE ENTITY" -// + The subscription should be canceled with the following response -// ``` -// { -// "errors": ["Request was 'resume only', but this subscription cannot be resumed."] -// } -// ``` -// #### Results -// + The subscription should remain `canceled` -// + The next billing date should not have changed -// ### Resuming Subscription Which Was Trialing -// + Given you have a `trial_ended` subscription, and it is resumable -// + And the subscription was canceled in the middle of a trial -// + And there is still time left on the trial -// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?resume=true` -// #### Results -// + The subscription will transition to trialing -// + The next billing date should not have changed -// ### Resuming Subscription Which Was trial_ended -// + Given you have a `trial_ended` subscription, and it is resumable -// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?resume=true` -// #### Results -// + The subscription will transition to active -// + The next billing date should not have changed +// ReactivateSubscription takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// Chargify offers the ability to reactivate a previously canceled subscription. For details on how the reactivation works, and how to reactivate subscriptions through the application, see [reactivation](https://chargify.zendesk.com/hc/en-us/articles/4407898737691). +// **Please note: The term +// "resume" is used also during another process in Chargify. This occurs when an on-hold subscription is "resumed". This returns the subscription to an active state.** +// + The response returns the subscription object in the `active` or `trialing` state. +// + The `canceled_at` and `cancellation_message` fields do not have values. +// + The method works for "Canceled" or "Trial Ended" subscriptions. +// + It will not work for items not marked as "Canceled", "Unpaid", or "Trial Ended". +// ## Resume the current billing period for a subscription +// A subscription is considered "resumable" if you are attempting to reactivate within the billing period the subscription was canceled in. +// A resumed subscription's billing date remains the same as before it was canceled. In other words, it does not start a new billing period. Payment may or may not be collected for a resumed subscription, depending on whether or not the subscription had a balance when it was canceled (for example, if it was canceled because of dunning). +// Consider a subscription which was created on June 1st, and would renew on July 1st. The subscription is then canceled on June 15. +// If a reactivation with `resume: true` were attempted _before_ what would have been the next billing date of July 1st, then Chargify would resume the subscription. +// If a reactivation with `resume: true` were attempted _after_ what would have been the next billing date of July 1st, then Chargify would not resume the subscription, and instead it would be reactivated with a new billing period. +// | Canceled | Reactivation | Resumable? | +// |---|---|---| +// | Jun 15 | June 28 | Yes | +// | Jun 15 | July 2 | No | +// ## Reactivation Scenarios +// ### Reactivating Canceled Subscription While Preserving Balance +// + Given you have a product that costs $20 +// + Given you have a canceled subscription to the $20 product +// + 1 charge should exist for $20 +// + 1 payment should exist for $20 +// + When the subscription has canceled due to dunning, it retained a negative balance of $20 +// #### Results +// The resulting charges upon reactivation will be: +// + 1 charge for $20 for the new product +// + 1 charge for $20 for the balance due +// + Total charges = $40 +// + The subscription will transition to active +// + The subscription balance will be zero +// ### Reactivating a Canceled Subscription With Coupon +// + Given you have a canceled subscription +// + It has no current period defined +// + You have a coupon code "EARLYBIRD" +// + The coupon is set to recur for 6 periods +// PUT request sent to: +// `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?coupon_code=EARLYBIRD` +// #### Results +// + The subscription will transition to active +// + The subscription should have applied a coupon with code "EARLYBIRD" +// ### Reactivating Canceled Subscription With a Trial, Without the include_trial Flag +// + Given you have a canceled subscription +// + The product associated with the subscription has a trial +// + PUT request to +// `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json` +// #### Results +// + The subscription will transition to active +// ### Reactivating Canceled Subscription With Trial, With the include_trial Flag +// + Given you have a canceled subscription +// + The product associated with the subscription has a trial +// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?include_trial=1` +// #### Results +// + The subscription will transition to trialing +// ### Reactivating Trial Ended Subscription +// + Given you have a trial_ended subscription +// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json` +// #### Results +// + The subscription will transition to active +// ### Resuming a Canceled Subscription +// + Given you have a `canceled` subscription and it is resumable +// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?resume=true` +// #### Results +// + The subscription will transition to active +// + The next billing date should not have changed +// ### Attempting to resume a subscription which is not resumable +// + Given you have a `canceled` subscription, and it is not resumable +// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?resume=true` +// #### Results +// + The subscription will transition to active, with a new billing period. +// ### Attempting to resume but not reactivate a subscription which is not resumable +// + Given you have a `canceled` subscription, and it is not resumable +// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?resume[require_resume]=true` +// + The response status should be "422 UNPROCESSABLE ENTITY" +// + The subscription should be canceled with the following response +// ``` +// { +// "errors": ["Request was 'resume only', but this subscription cannot be resumed."] +// } +// ``` +// #### Results +// + The subscription should remain `canceled` +// + The next billing date should not have changed +// ### Resuming Subscription Which Was Trialing +// + Given you have a `trial_ended` subscription, and it is resumable +// + And the subscription was canceled in the middle of a trial +// + And there is still time left on the trial +// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?resume=true` +// #### Results +// + The subscription will transition to trialing +// + The next billing date should not have changed +// ### Resuming Subscription Which Was trial_ended +// + Given you have a `trial_ended` subscription, and it is resumable +// + Send a PUT request to `https://acme.chargify.com/subscriptions/{subscription_id}/reactivate.json?resume=true` +// #### Results +// + The subscription will transition to active +// + The next billing date should not have changed // + Any product-related charges should have been collected func (s *SubscriptionStatusController) ReactivateSubscription( - ctx context.Context, - subscriptionId int, - body *models.ReactivateSubscriptionRequest) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/subscriptions/%v/reactivate.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.ReactivateSubscriptionRequest) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/subscriptions/%v/reactivate.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// InitiateDelayedCancellation takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.DelayedCancellationResponse data and -// an error if there was an issue with the request or response. -// Chargify offers the ability to cancel a subscription at the end of the current billing period. This period is set by its current product. -// Requesting to cancel the subscription at the end of the period sets the `cancel_at_end_of_period` flag to true. +// InitiateDelayedCancellation takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.DelayedCancellationResponse data and +// an error if there was an issue with the request or response. +// Chargify offers the ability to cancel a subscription at the end of the current billing period. This period is set by its current product. +// Requesting to cancel the subscription at the end of the period sets the `cancel_at_end_of_period` flag to true. // Note that you cannot set `cancel_at_end_of_period` at subscription creation, or if the subscription is past due. func (s *SubscriptionStatusController) InitiateDelayedCancellation( - ctx context.Context, - subscriptionId int, - body *models.CancellationRequest) ( - models.ApiResponse[models.DelayedCancellationResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/delayed_cancel.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.DelayedCancellationResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.DelayedCancellationResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.CancellationRequest) ( + models.ApiResponse[models.DelayedCancellationResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/delayed_cancel.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.DelayedCancellationResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.DelayedCancellationResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CancelDelayedCancellation takes context, subscriptionId as parameters and -// returns an models.ApiResponse with models.DelayedCancellationResponse data and -// an error if there was an issue with the request or response. -// Removing the delayed cancellation on a subscription will ensure that it doesn't get canceled at the end of the period that it is in. The request will reset the `cancel_at_end_of_period` flag to `false`. +// CancelDelayedCancellation takes context, subscriptionId as parameters and +// returns an models.ApiResponse with models.DelayedCancellationResponse data and +// an error if there was an issue with the request or response. +// Removing the delayed cancellation on a subscription will ensure that it doesn't get canceled at the end of the period that it is in. The request will reset the `cancel_at_end_of_period` flag to `false`. // This endpoint is idempotent. If the subscription was not set to cancel in the future, removing the delayed cancellation has no effect and the call will be successful. func (s *SubscriptionStatusController) CancelDelayedCancellation( - ctx context.Context, - subscriptionId int) ( - models.ApiResponse[models.DelayedCancellationResponse], - error) { - req := s.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/subscriptions/%v/delayed_cancel.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - }) - - var result models.DelayedCancellationResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.DelayedCancellationResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int) ( + models.ApiResponse[models.DelayedCancellationResponse], + error) { + req := s.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/subscriptions/%v/delayed_cancel.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + }) + + var result models.DelayedCancellationResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.DelayedCancellationResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CancelDunning takes context, subscriptionId as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. +// CancelDunning takes context, subscriptionId as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. // If a subscription is currently in dunning, the subscription will be set to active and the active Dunner will be resolved. func (s *SubscriptionStatusController) CancelDunning( - ctx context.Context, - subscriptionId int) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/cancel_dunning.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/cancel_dunning.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// PreviewRenewal takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.RenewalPreviewResponse data and -// an error if there was an issue with the request or response. -// The Chargify API allows you to preview a renewal by posting to the renewals endpoint. Renewal Preview is an object representing a subscription’s next assessment. You can retrieve it to see a snapshot of how much your customer will be charged on their next renewal. -// The "Next Billing" amount and "Next Billing" date are already represented in the UI on each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). -// ## Optional Component Fields -// This endpoint is particularly useful due to the fact that it will return the computed billing amount for the base product and the components which are in use by a subscriber. -// By default, the preview will include billing details for all components _at their **current** quantities_. This means: -// * Current `allocated_quantity` for quantity-based components -// * Current enabled/disabled status for on/off components -// * Current metered usage `unit_balance` for metered components -// * Current metric quantity value for events recorded thus far for events-based components -// In the above statements, "current" means the quantity or value as of the call to the renewal preview endpoint. We do not predict end-of-period values for components, so metered or events-based usage may be less than it will eventually be at the end of the period. -// Optionally, **you may provide your own custom quantities** for any component to see a billing preview for non-current quantities. This is accomplished by sending a request body with data under the `components` key. See the request body documentation below. -// ## Subscription Side Effects +// PreviewRenewal takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.RenewalPreviewResponse data and +// an error if there was an issue with the request or response. +// The Chargify API allows you to preview a renewal by posting to the renewals endpoint. Renewal Preview is an object representing a subscription’s next assessment. You can retrieve it to see a snapshot of how much your customer will be charged on their next renewal. +// The "Next Billing" amount and "Next Billing" date are already represented in the UI on each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). +// ## Optional Component Fields +// This endpoint is particularly useful due to the fact that it will return the computed billing amount for the base product and the components which are in use by a subscriber. +// By default, the preview will include billing details for all components _at their **current** quantities_. This means: +// * Current `allocated_quantity` for quantity-based components +// * Current enabled/disabled status for on/off components +// * Current metered usage `unit_balance` for metered components +// * Current metric quantity value for events recorded thus far for events-based components +// In the above statements, "current" means the quantity or value as of the call to the renewal preview endpoint. We do not predict end-of-period values for components, so metered or events-based usage may be less than it will eventually be at the end of the period. +// Optionally, **you may provide your own custom quantities** for any component to see a billing preview for non-current quantities. This is accomplished by sending a request body with data under the `components` key. See the request body documentation below. +// ## Subscription Side Effects // You can request a `POST` to obtain this data from the endpoint without any side effects. Plain and simple, this will preview data, not log any changes against a subscription. func (s *SubscriptionStatusController) PreviewRenewal( - ctx context.Context, - subscriptionId int, - body *models.RenewalPreviewRequest) ( - models.ApiResponse[models.RenewalPreviewResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/renewals/preview.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.RenewalPreviewResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.RenewalPreviewResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.RenewalPreviewRequest) ( + models.ApiResponse[models.RenewalPreviewResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/renewals/preview.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.RenewalPreviewResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.RenewalPreviewResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/subscriptions_controller.go b/subscriptions_controller.go index eef6565e..d9d0bdcc 100644 --- a/subscriptions_controller.go +++ b/subscriptions_controller.go @@ -1,985 +1,1008 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" - "net/http" - "time" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" + "net/http" + "time" ) // SubscriptionsController represents a controller struct. type SubscriptionsController struct { - baseController + baseController } -// NewSubscriptionsController creates a new instance of SubscriptionsController. +// NewSubscriptionsController creates a new instance of SubscriptionsController. // It takes a baseController as a parameter and returns a pointer to the SubscriptionsController. func NewSubscriptionsController(baseController baseController) *SubscriptionsController { - subscriptionsController := SubscriptionsController{baseController: baseController} - return &subscriptionsController + subscriptionsController := SubscriptionsController{baseController: baseController} + return &subscriptionsController } -// CreateSubscription takes context, body as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// Full documentation on how subscriptions operate within Chargify can be located under the following topics: -// + [Subscriptions Reference](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577172749-Subscription-Introduction) -// + [Subscriptions Actions](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions) -// + [Subscription Cancellation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions#initiate-cancellation) -// + [Subscription Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021-Reactivating-and-Resuming) -// + [Subscription Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821-Imports) -// When creating a subscription, you must specify a product and a customer. Credit card details may be required, depending on the options for the Product being subscribed ([see Product Options](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221#payment-method-settings)). -// The product may be specified by `product_id` or by `product_handle` (API Handle). In similar fashion, to pass a particular product price point, you may either use `product_price_point_handle` or `product_price_point_id`. -// An existing customer may be specified by a `customer_id` (ID within Chargify) or a `customer_reference` (unique value within your app that you have shared with Chargify via the reference attribute on a customer). You may also pass in an existing payment profile for that customer with `payment_profile_id`. A new customer may be created by providing `customer_attributes`. -// Credit card details may be required, depending on the options for the product being subscribed. The product can be specified by `product_id` or by `product_handle` (API Handle). -// If you are creating a subscription with a payment profile, the attribute to send will be `credit_card_attributes` or `bank_account_attributes` for ACH and Direct Debit. That said, when you read the subscription after creation, we return the profile details under `credit_card` or `bank_account`. -// ## Taxable Subscriptions -// If your intent is to charge your subscribers tax via [Avalara Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405275711885-Avalara-VAT-Tax) or [Custom Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405069041549-Custom-Taxes), there are a few considerations to be made regarding collecting subscription data. -// For subscribers to be eligible to be taxed, the following information for the `customer` object or `payment_profile` object must by supplied: -// + A subscription to a [taxable product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221-Product-Editing#tax-settings) -// + [Full valid billing or shipping address](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#full-address-required-for-taxable-subscriptions) to identify the tax locale -// + The portion of the address that houses the [state information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-state-format-for-taxable-subscriptions) of either adddress must adhere to the ISO standard of a 2-3 character limit/format. -// + The portion of the address that houses the [country information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-country-format-for-taxable-subscriptions) must adhere to the ISO standard of a 2 character limit/format. -// ## Subscription Request Examples -// The subscription examples below will be split into two sections. -// The first section, "Subscription Customization", will focus on passing different information with a subscription, such as components, calendar billing, and custom fields. These examples will presume you are using a secure `chargify_token` generated by Chargify.js. -// The second section, "Passing Payment Information", will focus on passing payment information into Chargify. Please be aware that collecting and sending Chargify raw card details requires PCI compliance on your end; these examples are provided as guidance. If your business is not PCI compliant, we recommend using Chargify.js to collect credit cards or bank accounts. -// # Subscription Customization -// ## With Components -// Different components require slightly different data. For example, quantity-based and on/off components accept `allocated_quantity`, while metered components accept `unit_balance`. -// When creating a subscription with a component, a `price_point_id` can be passed in along with the `component_id` to specify which price point to use. If not passed in, the default price point will be used. -// Note: if an invalid `price_point_id` is used, the subscription will still proceed but will use the component's default price point. -// Components and their price points may be added by ID or by handle. See the example request body labeled "Components By Handle (Quantity-Based)"; the format will be the same for other component types. -// ## With Coupon(s) -// Pass an array of `coupon_codes`. See the example request body "With Coupon". -// ## With Manual Invoice Collection -// The `invoice` collection method works only on legacy Statement Architecture. -// On Relationship Invoicing Architecture use the `remittance` collection method. -// ## Prepaid Subscription -// A prepaid subscription can be created with the usual subscription creation parameters, specifying `prepaid` as the `payment_collection_method` and including a nested `prepaid_configuration`. -// After a prepaid subscription has been created, additional funds can be manually added to the prepayment account through the [Create Prepayment Endpoint](https://developers.chargify.com/docs/api-docs/7ec482de77ba7-create-prepayment). -// Prepaid subscriptions do not work on legacy Statement Architecture. -// ## With Metafields -// Metafields can either attach to subscriptions or customers. Metafields are popuplated with the supplied metadata to the resource specified. -// If the metafield doesn't exist yet, it will be created on-the-fly. -// ## With Custom Pricing -// Custom pricing is pricing specific to the subscription in question. -// Create a subscription with custom pricing by passing pricing information instead of a price point. -// For a custom priced product, pass the custom_price object in place of `product_price_point_id`. For a custom priced component, pass the `custom_price` object within the component object. -// Custom prices and price points can exist in harmony on a subscription. -// # Passing Payment Information -// ## Subscription with Chargify.js token -// The `chargify_token` can be obtained using [chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview). The token represents payment profile attributes that were provided by the customer in their browser and stored at the payment gateway. -// The `payment_type` attribute may either be `credit_card` or `bank_account`, depending on the type of payment method being added. If a bank account is being passed, the payment attributes should be changed to `bank_account_attributes`. -// ```json -// { -// "subscription": { -// "product_handle": "pro-plan", -// "customer_attributes": { -// "first_name": "Joe", -// "last_name": "Smith", -// "email": "j.smith@example.com" -// }, -// "credit_card_attributes": { -// "chargify_token": "tok_cwhvpfcnbtgkd8nfkzf9dnjn", -// "payment_type": "credit_card" -// } -// } -// } -// ``` -// ## Subscription with vault token -// If you already have a customer and card stored in your payment gateway, you may create a subscription with a `vault_token`. Providing the last_four, card type and expiration date will allow the card to be displayed properly in the Chargify UI. -// ```json -// { -// "subscription": { -// "product_handle": "pro-plan", -// "customer_attributes": { -// "first_name": "Joe", -// "last_name": "Smith", -// "email": "j.smith@example.com" -// }, -// "credit_card_attributes": { -// first_name: "Joe, -// last_name: "Smith", -// card_type: "visa", -// expiration_month: "05", -// expiration_year: "2025", -// last_four: "1234", -// vault_token: "12345abc", -// current_vault: "braintree_blue" -// } -// } -// ``` -// ## Subscription with Credit Card -// ```json -// "subscription": { -// "product_handle": "basic", -// "customer_attributes": { -// "first_name": "Joe", -// "last_name": "Blow", -// "email": "joe@example.com", -// "zip": "02120", -// "state": "MA", -// "reference": "XYZ", -// "phone": "(617) 111 - 0000", -// "organization": "Acme", -// "country": "US", -// "city": "Boston", -// "address_2": null, -// "address": "123 Mass Ave." -// }, -// "credit_card_attributes": { -// "last_name": "Smith", -// "first_name": "Joe", -// "full_number": "4111111111111111", -// "expiration_year": "2021", -// "expiration_month": "1", -// "card_type": "visa", -// "billing_zip": "02120", -// "billing_state": "MA", -// "billing_country": "US", -// "billing_city": "Boston", -// "billing_address_2": null, -// "billing_address": "123 Mass Ave." -// } -// } -// ``` -// ## Subscription with ACH as Payment Profile -// ```json -// { -// "subscription": { -// "product_handle": "gold-product", -// "customer_attributes": { -// "first_name": "Joe", -// "last_name": "Blow", -// "email": "joe@example.com", -// "zip": "02120", -// "state": "MA", -// "reference": "XYZ", -// "phone": "(617) 111 - 0000", -// "organization": "Acme", -// "country": "US", -// "city": "Boston", -// "address_2": null, -// "address": "123 Mass Ave." -// }, -// "bank_account_attributes": { -// "bank_name": "Best Bank", -// "bank_routing_number": "021000089", -// "bank_account_number": "111111111111", -// "bank_account_type": "checking", -// "bank_account_holder_type": "business", -// "payment_type": "bank_account" -// } -// } -// } -// ``` -// ## Subscription with PayPal payment profile -// ### With the nonce from Braintree JS -// ```json -// { "subscription": { -// "product_handle":"test-product-b", -// "customer_attributes": { -// "first_name":"Amelia", -// "last_name":"Johnson", -// "email":"amelia@example.com", -// "organization":"My Awesome Company" -// }, -// "payment_profile_attributes":{ -// "paypal_email": "amelia@example.com", -// "current_vault": "braintree_blue", -// "payment_method_nonce":"abc123", -// "payment_type":"paypal_account" -// } -// } -// ``` -// ### With the Braintree Customer ID as the vault token: -// ```json -// { "subscription": { -// "product_handle":"test-product-b", -// "customer_attributes": { -// "first_name":"Amelia", -// "last_name":"Johnson", -// "email":"amelia@example.com", -// "organization":"My Awesome Company" -// }, -// "payment_profile_attributes":{ -// "paypal_email": "amelia@example.com", -// "current_vault": "braintree_blue", -// "vault_token":"58271347", -// "payment_type":"paypal_account" -// } -// } -// ``` -// ## Subscription using GoCardless Bank Number -// These examples creates a customer, bank account and mandate in GoCardless. -// For more information on GoCardless, please view the following two resources: -// + [Payment Profiles via API for GoCardless](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#gocardless) -// + [Full documentation on GoCardless](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404501889677) -// + [Using Chargify.js with GoCardless - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-direct-debit-gocardless-gateway) -// + [Using Chargify.js with GoCardless - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-direct-debit-gocardless-gateway) -// ```json -// { -// "subscription": { -// "product_handle": "gold-product", -// "customer_attributes": { -// "first_name": "Jane", -// "last_name": "Doe", -// "email": "jd@chargify.test" -// }, -// "bank_account_attributes": { -// "bank_name": "Royal Bank of France", -// "bank_account_number": "0000000", -// "bank_routing_number": "0003", -// "bank_branch_code": "00006", -// "payment_type": "bank_account", -// "billing_address": "20 Place de la Gare", -// "billing_city": "Colombes", -// "billing_state": "Île-de-France", -// "billing_zip": "92700", -// "billing_country": "FR" -// } -// } -// } -// ``` -// ## Subscription using GoCardless IBAN Number -// ```json -// { -// "subscription": { -// "product_handle": "gold-product", -// "customer_attributes": { -// "first_name": "Jane", -// "last_name": "Doe", -// "email": "jd@chargify.test" -// }, -// "bank_account_attributes": { -// "bank_name": "French Bank", -// "bank_iban": "FR1420041010050500013M02606", -// "payment_type": "bank_account", -// "billing_address": "20 Place de la Gare", -// "billing_city": "Colombes", -// "billing_state": "Île-de-France", -// "billing_zip": "92700", -// "billing_country": "FR" -// } -// } -// } -// ``` -// ## Subscription using Stripe SEPA Direct Debit -// For more information on Stripe Direct Debit, please view the following two resources: -// + [Payment Profiles via API for Stripe SEPA Direct Debit](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#sepa-direct-debit) -// + [Full documentation on Stripe Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) -// + [Using Chargify.js with Stripe SEPA or BECS Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) -// + [Using Chargify.js with Stripe SEPA Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-sepa-direct-debit-stripe-gateway) -// ```json -// { -// "subscription": { -// "product_handle": "gold-product", -// "customer_attributes": { -// "first_name": "Jane", -// "last_name": "Doe", -// "email": "jd@chargify.test" -// }, -// "bank_account_attributes": { -// "bank_name": "Test Bank", -// "bank_iban": "DE89370400440532013000", -// "payment_type": "bank_account" -// } -// } -// } -// ``` -// ## Subscription using Stripe BECS Direct Debit -// For more information on Stripe Direct Debit, please view the following two resources: -// + [Payment Profiles via API for Stripe BECS Direct Debit](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#stripe-becs-direct-debit) -// + [Full documentation on Stripe Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) -// + [Using Chargify.js with Stripe SEPA or BECS Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) -// + [Using Chargify.js with Stripe BECS Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-becs-direct-debit-stripe-gateway) -// ```json -// { -// "subscription": { -// "product_handle": "gold-product", -// "customer_attributes": { -// "first_name": "Jane", -// "last_name": "Doe", -// "email": "jd@chargify.test" -// }, -// "bank_account_attributes": { -// "bank_name": "Test Bank", -// "bank_branch_code": "000000", -// "bank_account_number": "000123456", -// "payment_type": "bank_account" -// } -// } -// } -// ``` -// ## 3D Secure - Stripe -// It may happen that a payment needs 3D Secure Authentication when the subscription is created; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: -// ```json -// { -// "errors": [ -// "Your card was declined. This transaction requires 3D secure authentication." -// ], -// "gateway_payment_id": "pi_1F0aGoJ2UDb3Q4av7zU3sHPh", -// "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", -// "action_link": "http://acme.chargify.com/3d-secure/pi_1F0aGoJ2UDb3Q4av7zU3sHPh?one_time_token_id=242" -// } -// ``` -// To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. -// Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: -// - whether the authentication was successful (`success`) -// - the gateway ID for the payment (`gateway_payment_id`) -// - the subscription ID (`subscription_id`) -// Lastly, you can also specify a `redirect_url` within the `action_link` URL if you’d like to redirect a customer back to your site. -// It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. -// The final URL that you send a customer to to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com` -// ## 3D Secure - Checkout -// It may happen that a payment needs 3D Secure Authentication when the subscription is created; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: -// ```json -// { -// "errors": [ -// "Your card was declined. This transaction requires 3D secure authentication." -// ], -// "gateway_payment_id": "pay_6gjofv7dlyrkpizlolsuspvtiu", -// "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", -// "action_link": "http://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123" -// } -// ``` -// To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. -// Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: -// - whether the authentication was successful (`success`) -// - the gateway ID for the payment (`gateway_payment_id`) -// - the subscription ID (`subscription_id`) -// Lastly, you can also specify a `redirect_url` parameter within the `action_link` URL if you’d like to redirect a customer back to your site. -// It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. -// The final URL that you send a customer to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com` -// ### Example Redirect Flow -// You may wish to redirect customers to different pages depending on whether their SCA was performed successfully. Here's an example flow to use as a reference: -// 1. Create a subscription via API; it requires 3DS -// 2. You receive a `gateway_payment_id` in the `action_link` along other params in the response. -// 3. Use this `gateway_payment_id` to, for example, connect with your internal resources or generate a session_id -// 4. Include 1 of those attributes inside the `callback_url` and `redirect_url` to be aware which “session” this applies to -// 5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied -// 6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. -// 7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known -// 8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not -// ## Subscriptions Import -// Subscriptions can be “imported” via the API to handle the following scenarios: -// + You already have existing subscriptions with specific start and renewal dates that you would like to import to Chargify -// + You already have credit cards stored in your provider’s vault and you would like to create subscriptions using those tokens -// Before importing, you should have already set up your products to match your offerings. Then, you can create Subscriptions via the API just like you normally would, but using a few special attributes. -// Full documentation on how import Subscriptions using the **import tool** in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#imports-0-0). -// ### Important Notices and Disclaimers regarding Imports -// Before performing a bulk import of subscriptions via the API, we suggest reading the [Subscriptions Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#important-notices-and-disclaimers) instructions to understand the repurcussions of a large import. -// ### Subscription Input Attributes -// The following _additional_ attributes to the subscription input attributes make imports possible: `next_billing_at`, `previous_billing_at`, and `import_mrr`. -// ### Current Vault -// If you are using a Legacy gateway such as "eWAY Rapid (Legacy)" or "Stripe (Legacy)" then please contact Support for further instructions on subscription imports. -// ### Braintree Blue (Braintree v2) Imports -// Braintree Blue is Braintree’s newer (version 2) API. For this gateway, please provide the `vault_token` parameter with the value from Braintree’s “Customer ID” rather than the “Payment Profile Token”. At this time we do not use `current_vault_token` with the Braintree Blue gateway, and we only support a single payment profile per Braintree Customer. -// When importing PayPal type payment profiles, please set `payment_type` to `paypal_account`. -// ### Stripe ACH Imports -// If the bank account has already been verified, currently you will need to create the customer, create the payment profile in Chargify - setting verified=true, then create a subscription using the customer_id and payment_profile_id. -// ### Webhooks During Import -// If no `next_billing_at` is provided, webhooks will be fired as normal. If you do set a future `next_billing_at`, only a subset of the webhooks are fired when the subscription is created. Keep reading for more information as to what webhooks will be fired under which scenarios. -// #### Successful creation with Billing Date -// Scenario: If `next_billing_at` provided -// + `signup_success` -// + `billing_date_change` -// #### Successful creation without Billing Date -// Scenario: If no `next_billing_at` provided -// + `signup_success` -// + `payment_success` -// #### Unsuccessful creation -// Scenario: If card can’t be charged, and no `next_billing_at` provided -// + signup_failure -// #### Webhooks fired when next_billing_at is reached: -// + `renewal_success or renewal_failure` -// + `payment_success or payment_failure` -// ### Date and Time Formats -// We will attempt to parse any string you send as the value of next_billing_at in to a date or time. For best results, use a known format like described in “Date and Time Specification” of RFC 2822 or ISO 8601 . -// The following are all equivalent and will work as input to `next_billing_at`: -// ``` -// Aug 06 2030 11:34:00 -0400 -// Aug 06 2030 11:34 -0400 -// 2030-08-06T11:34:00-04:00 -// 8/6/2030 11:34:00 EDT -// 8/6/2030 8:34:00 PDT -// 2030-08-06T15:34:00Z -// ``` -// You may also pass just a date, in which case we will assume the time to be noon -// ``` -// 2010-08-06 -// ``` -// ## Subscription Hierarchies & WhoPays -// When subscription groups were first added to our Relationship Invoicing architecture, to group together invoices for related subscriptions and allow for complex customer hierarchies and WhoPays scenarios, they were designed to consist of a primary and a collection of group members. The primary would control many aspects of the group, such as when the consolidated invoice is generated. As of today, groups still function this way. -// In the future, the concept of a "primary" will be removed in order to offer more flexibility into group management and reduce confusion concerning what actions must be done on a primary level, rather than a member level. -// We have introduced a two scheme system as a bridge between these two group organizations. Scheme 1, which is relevant to all subscription groups today, marks the group as being "ruled" by a primary. -// When reading a subscription via API, they will return a top-level attribute called `group`, which will denote which scheme is being used. At this time, the `scheme` attribute will always be 1. -// ### Subscription in a Customer Hierarchy -// For sites making use of the [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) and [Customer Hierarchy](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404900384141) features, it is possible to create subscriptions within a customer hierarchy. This can be achieved through the API by passing group parameters in the **Create Subscription** request. -// + The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. -// When the `target` parameter specifies a customer that is already part of a hierarchy, the new subscription will become a member of the customer hierarchy as well. If the target customer is not part of a hierarchy, a new customer hierarchy will be created and both the target customer and the new subscription will become part of the hierarchy with the specified target customer set as the responsible payer for the hierarchy's subscriptions. -// Rather than specifying a customer, the `target` parameter could instead simply have a value of `self` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer. This will be true whether the customer is being created new, is already part of a hierarchy, or already exists outside a hierarchy. A valid payment method must also be specified in the subscription parameters. -// Note that when creating subscriptions in a customer hierarchy, if the customer hierarchy does not already have a payment method, passing valid credit card attributes in the subscription parameters will also result in the payment method being established as the default payment method for the customer hierarchy irrespective of the responsible payer. -// The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the default subscription group in the customer hierarchy. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the default subscription group in the customer hierarchy also. -// ### Subscription in a Subscription Group -// For sites making use of [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) it may be desireable to create a subscription as part of a [subscription group](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577356173) in order to rely on [invoice consolidation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404980119949). This can be achieved through the API by passing group parameters in the Create Subscription request. The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. -// The `target` parameters specify an existing subscription with which the newly created subscription should be grouped. If the target subscription is already part of a group, the new subscription will become a member of the group as well. If the target subscription is not part of a group, a new group will be created and both the target and the new subscription will become part of the group with the target as the group's primary subscription. -// The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the target subscription. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the target subscription also. -// ## Providing Agreement Acceptance Params -// It is possible to provide a proof of customer's acceptance of terms and policies. -// We will be storing this proof in case it might be required (i.e. chargeback). -// Currently, we already keep it for subscriptions created via Public Signup Pages. -// In order to create a subscription with the proof of agreement acceptance, you must provide additional parameters `agreement acceptance` with `ip_address` and at least one url to the policy that was accepted: `terms_url` or `privacy_policy_url`. Additional urls that can be provided: `return_refund_policy_url`, `delivery_policy_url` and -// `secure_checkout_policy_url`. -// ```json -// "subscription": { -// "product_handle": "gold-product", -// "customer_attributes": { -// "first_name": "Jane", -// "last_name": "Doe", -// "email": "jd@chargify.test" -// }, -// "agreement_acceptance": { -// "ip_address": "1.2.3.4", -// "terms_url": "https://terms.url", -// "privacy_policy_url": "https://privacy_policy.url", -// "return_refund_policy_url": "https://return_refund_policy.url", -// "delivery_policy_url": "https://delivery_policy.url", -// "secure_checkout_policy_url": "https://secure_checkout_policy.url" -// } -// } -// } -// ``` -// **For Maxio Payments subscriptions, the agreement acceptance params are required, with at least terms_url provided.** -// ## Providing ACH Agreement params -// It is also possible to provide a proof that a customer authorized ACH agreement terms. -// The proof will be stored and the email will be sent to the customer with a copy of the terms (if enabled). -// In order to create a subscription with the proof of authorized ACH agreement terms, you must provide the additional parameter `ach_agreement` with the following nested parameters: `agreement_terms`, `authorizer_first_name`, `authorizer_last_name` and `ip_address`. -// Each of them is required. -// ```json -// "subscription": { -// "product_handle": "gold-product", -// "customer_attributes": { -// "first_name": "Jane", -// "last_name": "Doe", -// "email": "jd@chargify.test" -// }, -// "bank_account_attributes": { -// "bank_name": "Test Bank", -// "bank_routing_number": "021000089", -// "bank_account_number": "111111111111", -// "bank_account_type": "checking", -// "bank_account_holder_type": "business", -// "payment_type": "bank_account" -// }, -// "ach_agreement": { -// "agreement_terms": "ACH agreement terms", -// "authorizer_first_name": "Jane", -// "authorizer_last_name": "Doe", -// "ip_address": "1.2.3.4" -// } -// } +// CreateSubscription takes context, body as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// Full documentation on how subscriptions operate within Chargify can be located under the following topics: +// + [Subscriptions Reference](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577172749-Subscription-Introduction) +// + [Subscriptions Actions](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions) +// + [Subscription Cancellation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405510556557-Actions#initiate-cancellation) +// + [Subscription Reactivation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404559291021-Reactivating-and-Resuming) +// + [Subscription Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821-Imports) +// When creating a subscription, you must specify a product and a customer. Credit card details may be required, depending on the options for the Product being subscribed ([see Product Options](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221#payment-method-settings)). +// The product may be specified by `product_id` or by `product_handle` (API Handle). In similar fashion, to pass a particular product price point, you may either use `product_price_point_handle` or `product_price_point_id`. +// An existing customer may be specified by a `customer_id` (ID within Chargify) or a `customer_reference` (unique value within your app that you have shared with Chargify via the reference attribute on a customer). You may also pass in an existing payment profile for that customer with `payment_profile_id`. A new customer may be created by providing `customer_attributes`. +// Credit card details may be required, depending on the options for the product being subscribed. The product can be specified by `product_id` or by `product_handle` (API Handle). +// If you are creating a subscription with a payment profile, the attribute to send will be `credit_card_attributes` or `bank_account_attributes` for ACH and Direct Debit. That said, when you read the subscription after creation, we return the profile details under `credit_card` or `bank_account`. +// ## Taxable Subscriptions +// If your intent is to charge your subscribers tax via [Avalara Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405275711885-Avalara-VAT-Tax) or [Custom Taxes](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405069041549-Custom-Taxes), there are a few considerations to be made regarding collecting subscription data. +// For subscribers to be eligible to be taxed, the following information for the `customer` object or `payment_profile` object must by supplied: +// + A subscription to a [taxable product](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405246782221-Product-Editing#tax-settings) +// + [Full valid billing or shipping address](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#full-address-required-for-taxable-subscriptions) to identify the tax locale +// + The portion of the address that houses the [state information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-state-format-for-taxable-subscriptions) of either adddress must adhere to the ISO standard of a 2-3 character limit/format. +// + The portion of the address that houses the [country information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405356114317#required-country-format-for-taxable-subscriptions) must adhere to the ISO standard of a 2 character limit/format. +// ## Subscription Request Examples +// The subscription examples below will be split into two sections. +// The first section, "Subscription Customization", will focus on passing different information with a subscription, such as components, calendar billing, and custom fields. These examples will presume you are using a secure `chargify_token` generated by Chargify.js. +// The second section, "Passing Payment Information", will focus on passing payment information into Chargify. Please be aware that collecting and sending Chargify raw card details requires PCI compliance on your end; these examples are provided as guidance. If your business is not PCI compliant, we recommend using Chargify.js to collect credit cards or bank accounts. +// # Subscription Customization +// ## With Components +// Different components require slightly different data. For example, quantity-based and on/off components accept `allocated_quantity`, while metered components accept `unit_balance`. +// When creating a subscription with a component, a `price_point_id` can be passed in along with the `component_id` to specify which price point to use. If not passed in, the default price point will be used. +// Note: if an invalid `price_point_id` is used, the subscription will still proceed but will use the component's default price point. +// Components and their price points may be added by ID or by handle. See the example request body labeled "Components By Handle (Quantity-Based)"; the format will be the same for other component types. +// ## With Coupon(s) +// Pass an array of `coupon_codes`. See the example request body "With Coupon". +// ## With Manual Invoice Collection +// The `invoice` collection method works only on legacy Statement Architecture. +// On Relationship Invoicing Architecture use the `remittance` collection method. +// ## Prepaid Subscription +// A prepaid subscription can be created with the usual subscription creation parameters, specifying `prepaid` as the `payment_collection_method` and including a nested `prepaid_configuration`. +// After a prepaid subscription has been created, additional funds can be manually added to the prepayment account through the [Create Prepayment Endpoint](https://developers.chargify.com/docs/api-docs/7ec482de77ba7-create-prepayment). +// Prepaid subscriptions do not work on legacy Statement Architecture. +// ## With Metafields +// Metafields can either attach to subscriptions or customers. Metafields are popuplated with the supplied metadata to the resource specified. +// If the metafield doesn't exist yet, it will be created on-the-fly. +// ## With Custom Pricing +// Custom pricing is pricing specific to the subscription in question. +// Create a subscription with custom pricing by passing pricing information instead of a price point. +// For a custom priced product, pass the custom_price object in place of `product_price_point_id`. For a custom priced component, pass the `custom_price` object within the component object. +// Custom prices and price points can exist in harmony on a subscription. +// # Passing Payment Information +// ## Subscription with Chargify.js token +// The `chargify_token` can be obtained using [chargify.js](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDI0-overview). The token represents payment profile attributes that were provided by the customer in their browser and stored at the payment gateway. +// The `payment_type` attribute may either be `credit_card` or `bank_account`, depending on the type of payment method being added. If a bank account is being passed, the payment attributes should be changed to `bank_account_attributes`. +// ```json +// { +// "subscription": { +// "product_handle": "pro-plan", +// "customer_attributes": { +// "first_name": "Joe", +// "last_name": "Smith", +// "email": "j.smith@example.com" +// }, +// "credit_card_attributes": { +// "chargify_token": "tok_cwhvpfcnbtgkd8nfkzf9dnjn", +// "payment_type": "credit_card" +// } +// } +// } +// ``` +// ## Subscription with vault token +// If you already have a customer and card stored in your payment gateway, you may create a subscription with a `vault_token`. Providing the last_four, card type and expiration date will allow the card to be displayed properly in the Chargify UI. +// ```json +// { +// "subscription": { +// "product_handle": "pro-plan", +// "customer_attributes": { +// "first_name": "Joe", +// "last_name": "Smith", +// "email": "j.smith@example.com" +// }, +// "credit_card_attributes": { +// first_name: "Joe, +// last_name: "Smith", +// card_type: "visa", +// expiration_month: "05", +// expiration_year: "2025", +// last_four: "1234", +// vault_token: "12345abc", +// current_vault: "braintree_blue" +// } +// } +// ``` +// ## Subscription with Credit Card +// ```json +// "subscription": { +// "product_handle": "basic", +// "customer_attributes": { +// "first_name": "Joe", +// "last_name": "Blow", +// "email": "joe@example.com", +// "zip": "02120", +// "state": "MA", +// "reference": "XYZ", +// "phone": "(617) 111 - 0000", +// "organization": "Acme", +// "country": "US", +// "city": "Boston", +// "address_2": null, +// "address": "123 Mass Ave." +// }, +// "credit_card_attributes": { +// "last_name": "Smith", +// "first_name": "Joe", +// "full_number": "4111111111111111", +// "expiration_year": "2021", +// "expiration_month": "1", +// "card_type": "visa", +// "billing_zip": "02120", +// "billing_state": "MA", +// "billing_country": "US", +// "billing_city": "Boston", +// "billing_address_2": null, +// "billing_address": "123 Mass Ave." +// } +// } +// ``` +// ## Subscription with ACH as Payment Profile +// ```json +// { +// "subscription": { +// "product_handle": "gold-product", +// "customer_attributes": { +// "first_name": "Joe", +// "last_name": "Blow", +// "email": "joe@example.com", +// "zip": "02120", +// "state": "MA", +// "reference": "XYZ", +// "phone": "(617) 111 - 0000", +// "organization": "Acme", +// "country": "US", +// "city": "Boston", +// "address_2": null, +// "address": "123 Mass Ave." +// }, +// "bank_account_attributes": { +// "bank_name": "Best Bank", +// "bank_routing_number": "021000089", +// "bank_account_number": "111111111111", +// "bank_account_type": "checking", +// "bank_account_holder_type": "business", +// "payment_type": "bank_account" +// } +// } +// } +// ``` +// ## Subscription with PayPal payment profile +// ### With the nonce from Braintree JS +// ```json +// { "subscription": { +// "product_handle":"test-product-b", +// "customer_attributes": { +// "first_name":"Amelia", +// "last_name":"Johnson", +// "email":"amelia@example.com", +// "organization":"My Awesome Company" +// }, +// "payment_profile_attributes":{ +// "paypal_email": "amelia@example.com", +// "current_vault": "braintree_blue", +// "payment_method_nonce":"abc123", +// "payment_type":"paypal_account" +// } +// } +// ``` +// ### With the Braintree Customer ID as the vault token: +// ```json +// { "subscription": { +// "product_handle":"test-product-b", +// "customer_attributes": { +// "first_name":"Amelia", +// "last_name":"Johnson", +// "email":"amelia@example.com", +// "organization":"My Awesome Company" +// }, +// "payment_profile_attributes":{ +// "paypal_email": "amelia@example.com", +// "current_vault": "braintree_blue", +// "vault_token":"58271347", +// "payment_type":"paypal_account" +// } +// } +// ``` +// ## Subscription using GoCardless Bank Number +// These examples creates a customer, bank account and mandate in GoCardless. +// For more information on GoCardless, please view the following two resources: +// + [Payment Profiles via API for GoCardless](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#gocardless) +// + [Full documentation on GoCardless](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404501889677) +// + [Using Chargify.js with GoCardless - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-direct-debit-gocardless-gateway) +// + [Using Chargify.js with GoCardless - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-direct-debit-gocardless-gateway) +// ```json +// { +// "subscription": { +// "product_handle": "gold-product", +// "customer_attributes": { +// "first_name": "Jane", +// "last_name": "Doe", +// "email": "jd@chargify.test" +// }, +// "bank_account_attributes": { +// "bank_name": "Royal Bank of France", +// "bank_account_number": "0000000", +// "bank_routing_number": "0003", +// "bank_branch_code": "00006", +// "payment_type": "bank_account", +// "billing_address": "20 Place de la Gare", +// "billing_city": "Colombes", +// "billing_state": "Île-de-France", +// "billing_zip": "92700", +// "billing_country": "FR" +// } +// } +// } +// ``` +// ## Subscription using GoCardless IBAN Number +// ```json +// { +// "subscription": { +// "product_handle": "gold-product", +// "customer_attributes": { +// "first_name": "Jane", +// "last_name": "Doe", +// "email": "jd@chargify.test" +// }, +// "bank_account_attributes": { +// "bank_name": "French Bank", +// "bank_iban": "FR1420041010050500013M02606", +// "payment_type": "bank_account", +// "billing_address": "20 Place de la Gare", +// "billing_city": "Colombes", +// "billing_state": "Île-de-France", +// "billing_zip": "92700", +// "billing_country": "FR" +// } +// } +// } +// ``` +// ## Subscription using Stripe SEPA Direct Debit +// For more information on Stripe Direct Debit, please view the following two resources: +// + [Payment Profiles via API for Stripe SEPA Direct Debit](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#sepa-direct-debit) +// + [Full documentation on Stripe Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) +// + [Using Chargify.js with Stripe SEPA or BECS Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) +// + [Using Chargify.js with Stripe SEPA Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-sepa-direct-debit-stripe-gateway) +// ```json +// { +// "subscription": { +// "product_handle": "gold-product", +// "customer_attributes": { +// "first_name": "Jane", +// "last_name": "Doe", +// "email": "jd@chargify.test" +// }, +// "bank_account_attributes": { +// "bank_name": "Test Bank", +// "bank_iban": "DE89370400440532013000", +// "payment_type": "bank_account" +// } +// } +// } +// ``` +// ## Subscription using Stripe BECS Direct Debit +// For more information on Stripe Direct Debit, please view the following two resources: +// + [Payment Profiles via API for Stripe BECS Direct Debit](https://developers.chargify.com/docs/api-docs/1f10a4f170405-create-payment-profile#stripe-becs-direct-debit) +// + [Full documentation on Stripe Direct Debit](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405050826765-Stripe-SEPA-and-BECS-Direct-Debit) +// + [Using Chargify.js with Stripe SEPA or BECS Direct Debit - minimal example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#minimal-example-with-sepa-or-becs-direct-debit-stripe-gateway) +// + [Using Chargify.js with Stripe BECS Direct Debit - full example](https://developers.chargify.com/docs/developer-docs/ZG9jOjE0NjAzNDIy-examples#full-example-with-becs-direct-debit-stripe-gateway) +// ```json +// { +// "subscription": { +// "product_handle": "gold-product", +// "customer_attributes": { +// "first_name": "Jane", +// "last_name": "Doe", +// "email": "jd@chargify.test" +// }, +// "bank_account_attributes": { +// "bank_name": "Test Bank", +// "bank_branch_code": "000000", +// "bank_account_number": "000123456", +// "payment_type": "bank_account" +// } +// } +// } +// ``` +// ## 3D Secure - Stripe +// It may happen that a payment needs 3D Secure Authentication when the subscription is created; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: +// ```json +// { +// "errors": [ +// "Your card was declined. This transaction requires 3D secure authentication." +// ], +// "gateway_payment_id": "pi_1F0aGoJ2UDb3Q4av7zU3sHPh", +// "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", +// "action_link": "http://acme.chargify.com/3d-secure/pi_1F0aGoJ2UDb3Q4av7zU3sHPh?one_time_token_id=242" +// } +// ``` +// To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. +// Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: +// - whether the authentication was successful (`success`) +// - the gateway ID for the payment (`gateway_payment_id`) +// - the subscription ID (`subscription_id`) +// Lastly, you can also specify a `redirect_url` within the `action_link` URL if you’d like to redirect a customer back to your site. +// It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. +// The final URL that you send a customer to to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pi_1FCm4RKDeye4C0XfbqquXRYm?one_time_token_id=128&callback_url=https://localhost:4000&redirect_url=https://yourpage.com` +// ## 3D Secure - Checkout +// It may happen that a payment needs 3D Secure Authentication when the subscription is created; this is referred to in our help docs as a [post-authentication flow](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405177432077#psd2-flows-pre-authentication-and-post-authentication). The server returns `422 Unprocessable Entity` in this case with the following response: +// ```json +// { +// "errors": [ +// "Your card was declined. This transaction requires 3D secure authentication." +// ], +// "gateway_payment_id": "pay_6gjofv7dlyrkpizlolsuspvtiu", +// "description": "This card requires 3D secure authentication. Redirect the customer to the URL from the action_link attribute to authenticate. Attach callback_url param to this URL if you want to be notified about the result of 3D Secure authentication. Attach redirect_url param to this URL if you want to redirect a customer back to your page after 3D Secure authentication. Example: https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com will do a POST request to https://localhost:4000 after payment is authenticated and will redirect a customer to https://yourpage.com after 3DS authentication.", +// "action_link": "http://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123" +// } +// ``` +// To let the customer go through 3D Secure Authentication, they need to be redirected to the URL specified in `action_link`. +// Optionally, you can specify `callback_url` parameter in the `action_link` URL if you’d like to be notified about the result of 3D Secure Authentication. The `callback_url` will return the following information: +// - whether the authentication was successful (`success`) +// - the gateway ID for the payment (`gateway_payment_id`) +// - the subscription ID (`subscription_id`) +// Lastly, you can also specify a `redirect_url` parameter within the `action_link` URL if you’d like to redirect a customer back to your site. +// It is not possible to use `action_link` in an iframe inside a custom application. You have to redirect the customer directly to the `action_link`, then, to be notified about the result, use `redirect_url` or `callback_url`. +// The final URL that you send a customer to complete 3D Secure may resemble the following, where the first half is the `action_link` and the second half contains a `redirect_url` and `callback_url`: `https://mysite.chargify.com/3d-secure/pay_6gjofv7dlyrkpizlolsuspvtiu?one_time_token_id=123&callback_url=https://localhost:4000&redirect_url=https://yourpage.com` +// ### Example Redirect Flow +// You may wish to redirect customers to different pages depending on whether their SCA was performed successfully. Here's an example flow to use as a reference: +// 1. Create a subscription via API; it requires 3DS +// 2. You receive a `gateway_payment_id` in the `action_link` along other params in the response. +// 3. Use this `gateway_payment_id` to, for example, connect with your internal resources or generate a session_id +// 4. Include 1 of those attributes inside the `callback_url` and `redirect_url` to be aware which “session” this applies to +// 5. Redirect the customer to the `action_link` with `callback_url` and `redirect_url` applied +// 6. After the customer finishes 3DS authentication, we let you know the result by making a request to applied `callback_url`. +// 7. After that, we redirect the customer to the `redirect_url`; at this point the result of authentication is known +// 8. Optionally, you can use the applied "msg" param in the `redirect_url` to determine whether it was successful or not +// ## Subscriptions Import +// Subscriptions can be “imported” via the API to handle the following scenarios: +// + You already have existing subscriptions with specific start and renewal dates that you would like to import to Chargify +// + You already have credit cards stored in your provider’s vault and you would like to create subscriptions using those tokens +// Before importing, you should have already set up your products to match your offerings. Then, you can create Subscriptions via the API just like you normally would, but using a few special attributes. +// Full documentation on how import Subscriptions using the **import tool** in the Chargify UI can be located [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#imports-0-0). +// ### Important Notices and Disclaimers regarding Imports +// Before performing a bulk import of subscriptions via the API, we suggest reading the [Subscriptions Import](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404863655821#important-notices-and-disclaimers) instructions to understand the repurcussions of a large import. +// ### Subscription Input Attributes +// The following _additional_ attributes to the subscription input attributes make imports possible: `next_billing_at`, `previous_billing_at`, and `import_mrr`. +// ### Current Vault +// If you are using a Legacy gateway such as "eWAY Rapid (Legacy)" or "Stripe (Legacy)" then please contact Support for further instructions on subscription imports. +// ### Braintree Blue (Braintree v2) Imports +// Braintree Blue is Braintree’s newer (version 2) API. For this gateway, please provide the `vault_token` parameter with the value from Braintree’s “Customer ID” rather than the “Payment Profile Token”. At this time we do not use `current_vault_token` with the Braintree Blue gateway, and we only support a single payment profile per Braintree Customer. +// When importing PayPal type payment profiles, please set `payment_type` to `paypal_account`. +// ### Stripe ACH Imports +// If the bank account has already been verified, currently you will need to create the customer, create the payment profile in Chargify - setting verified=true, then create a subscription using the customer_id and payment_profile_id. +// ### Webhooks During Import +// If no `next_billing_at` is provided, webhooks will be fired as normal. If you do set a future `next_billing_at`, only a subset of the webhooks are fired when the subscription is created. Keep reading for more information as to what webhooks will be fired under which scenarios. +// #### Successful creation with Billing Date +// Scenario: If `next_billing_at` provided +// + `signup_success` +// + `billing_date_change` +// #### Successful creation without Billing Date +// Scenario: If no `next_billing_at` provided +// + `signup_success` +// + `payment_success` +// #### Unsuccessful creation +// Scenario: If card can’t be charged, and no `next_billing_at` provided +// + signup_failure +// #### Webhooks fired when next_billing_at is reached: +// + `renewal_success or renewal_failure` +// + `payment_success or payment_failure` +// ### Date and Time Formats +// We will attempt to parse any string you send as the value of next_billing_at in to a date or time. For best results, use a known format like described in “Date and Time Specification” of RFC 2822 or ISO 8601 . +// The following are all equivalent and will work as input to `next_billing_at`: +// ``` +// Aug 06 2030 11:34:00 -0400 +// Aug 06 2030 11:34 -0400 +// 2030-08-06T11:34:00-04:00 +// 8/6/2030 11:34:00 EDT +// 8/6/2030 8:34:00 PDT +// 2030-08-06T15:34:00Z +// ``` +// You may also pass just a date, in which case we will assume the time to be noon +// ``` +// 2010-08-06 +// ``` +// ## Subscription Hierarchies & WhoPays +// When subscription groups were first added to our Relationship Invoicing architecture, to group together invoices for related subscriptions and allow for complex customer hierarchies and WhoPays scenarios, they were designed to consist of a primary and a collection of group members. The primary would control many aspects of the group, such as when the consolidated invoice is generated. As of today, groups still function this way. +// In the future, the concept of a "primary" will be removed in order to offer more flexibility into group management and reduce confusion concerning what actions must be done on a primary level, rather than a member level. +// We have introduced a two scheme system as a bridge between these two group organizations. Scheme 1, which is relevant to all subscription groups today, marks the group as being "ruled" by a primary. +// When reading a subscription via API, they will return a top-level attribute called `group`, which will denote which scheme is being used. At this time, the `scheme` attribute will always be 1. +// ### Subscription in a Customer Hierarchy +// For sites making use of the [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) and [Customer Hierarchy](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404900384141) features, it is possible to create subscriptions within a customer hierarchy. This can be achieved through the API by passing group parameters in the **Create Subscription** request. +// + The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. +// When the `target` parameter specifies a customer that is already part of a hierarchy, the new subscription will become a member of the customer hierarchy as well. If the target customer is not part of a hierarchy, a new customer hierarchy will be created and both the target customer and the new subscription will become part of the hierarchy with the specified target customer set as the responsible payer for the hierarchy's subscriptions. +// Rather than specifying a customer, the `target` parameter could instead simply have a value of `self` which indicates the subscription will be paid for not by some other customer, but by the subscribing customer. This will be true whether the customer is being created new, is already part of a hierarchy, or already exists outside a hierarchy. A valid payment method must also be specified in the subscription parameters. +// Note that when creating subscriptions in a customer hierarchy, if the customer hierarchy does not already have a payment method, passing valid credit card attributes in the subscription parameters will also result in the payment method being established as the default payment method for the customer hierarchy irrespective of the responsible payer. +// The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the default subscription group in the customer hierarchy. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the default subscription group in the customer hierarchy also. +// ### Subscription in a Subscription Group +// For sites making use of [Relationship Billing](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405078794253-Introduction-to-Invoices) it may be desireable to create a subscription as part of a [subscription group](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405577356173) in order to rely on [invoice consolidation](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404980119949). This can be achieved through the API by passing group parameters in the Create Subscription request. The `group` parameters are optional and consist of the required `target` and optional `billing` parameters. +// The `target` parameters specify an existing subscription with which the newly created subscription should be grouped. If the target subscription is already part of a group, the new subscription will become a member of the group as well. If the target subscription is not part of a group, a new group will be created and both the target and the new subscription will become part of the group with the target as the group's primary subscription. +// The optional `billing` parameters specify how some aspects of the billing for the new subscription should be handled. Rather than capturing payment immediately, the `accrue` parameter can be included so that the new subscription charges accrue until the next assessment date. Regarding the date, the `align_date` parameter can be included so that the billing date of the new subscription matches up with the target subscription. When choosing to align the dates, the `prorate` parameter can also be specified so that the new subscription charges are prorated based on the billing period of the target subscription also. +// ## Providing Agreement Acceptance Params +// It is possible to provide a proof of customer's acceptance of terms and policies. +// We will be storing this proof in case it might be required (i.e. chargeback). +// Currently, we already keep it for subscriptions created via Public Signup Pages. +// In order to create a subscription with the proof of agreement acceptance, you must provide additional parameters `agreement acceptance` with `ip_address` and at least one url to the policy that was accepted: `terms_url` or `privacy_policy_url`. Additional urls that can be provided: `return_refund_policy_url`, `delivery_policy_url` and +// `secure_checkout_policy_url`. +// ```json +// "subscription": { +// "product_handle": "gold-product", +// "customer_attributes": { +// "first_name": "Jane", +// "last_name": "Doe", +// "email": "jd@chargify.test" +// }, +// "agreement_acceptance": { +// "ip_address": "1.2.3.4", +// "terms_url": "https://terms.url", +// "privacy_policy_url": "https://privacy_policy.url", +// "return_refund_policy_url": "https://return_refund_policy.url", +// "delivery_policy_url": "https://delivery_policy.url", +// "secure_checkout_policy_url": "https://secure_checkout_policy.url" +// } +// } +// } +// ``` +// **For Maxio Payments subscriptions, the agreement acceptance params are required, with at least terms_url provided.** +// ## Providing ACH Agreement params +// It is also possible to provide a proof that a customer authorized ACH agreement terms. +// The proof will be stored and the email will be sent to the customer with a copy of the terms (if enabled). +// In order to create a subscription with the proof of authorized ACH agreement terms, you must provide the additional parameter `ach_agreement` with the following nested parameters: `agreement_terms`, `authorizer_first_name`, `authorizer_last_name` and `ip_address`. +// Each of them is required. +// ```json +// "subscription": { +// "product_handle": "gold-product", +// "customer_attributes": { +// "first_name": "Jane", +// "last_name": "Doe", +// "email": "jd@chargify.test" +// }, +// "bank_account_attributes": { +// "bank_name": "Test Bank", +// "bank_routing_number": "021000089", +// "bank_account_number": "111111111111", +// "bank_account_type": "checking", +// "bank_account_holder_type": "business", +// "payment_type": "bank_account" +// }, +// "ach_agreement": { +// "agreement_terms": "ACH agreement terms", +// "authorizer_first_name": "Jane", +// "authorizer_last_name": "Doe", +// "ip_address": "1.2.3.4" +// } +// } // ``` func (s *SubscriptionsController) CreateSubscription( - ctx context.Context, - body *models.CreateSubscriptionRequest) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest(ctx, "POST", "/subscriptions.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.CreateSubscriptionRequest) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest(ctx, "POST", "/subscriptions.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err +} + +// ListSubscriptionsInput represents the input of the ListSubscriptions endpoint. +type ListSubscriptionsInput struct { + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The current state of the subscription + State *models.SubscriptionStateFilter + // The product id of the subscription. (Note that the product handle cannot be used.) + Product *int + // The ID of the product price point. If supplied, product is required + ProductPricePointId *int + // The numeric id of the coupon currently applied to the subscription. (This can be found in the URL when editing a coupon. Note that the coupon code cannot be used.) + Coupon *int + // The type of filter you'd like to apply to your search. Allowed Values: , current_period_ends_at, current_period_starts_at, created_at, activated_at, canceled_at, expires_at, trial_started_at, trial_ended_at, updated_at + DateField *models.SubscriptionDateField + // The start date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp at or after midnight (12:00:00 AM) in your site’s time zone on the date specified. Use in query `start_date=2022-07-01`. + StartDate *time.Time + // The end date (format YYYY-MM-DD) with which to filter the date_field. Returns subscriptions with a timestamp up to and including 11:59:59PM in your site’s time zone on the date specified. Use in query `end_date=2022-08-01`. + EndDate *time.Time + // The start date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or after exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of start_date. Use in query `start_datetime=2022-07-01 09:00:05`. + StartDatetime *time.Time + // The end date and time (format YYYY-MM-DD HH:MM:SS) with which to filter the date_field. Returns subscriptions with a timestamp at or before exact time provided in query. You can specify timezone in query - otherwise your site's time zone will be used. If provided, this parameter will be used instead of end_date. Use in query `end_datetime=2022-08-01 10:00:05`. + EndDatetime *time.Time + // The value of the metadata field specified in the parameter. Use in query `metadata[my-field]=value&metadata[other-field]=another_value`. + Metadata map[string]string + // Controls the order in which results are returned. + // Use in query `direction=asc`. + Direction *models.SortingDirection + // The attribute by which to sort + Sort *models.SubscriptionSort + // Allows including additional data in the response. Use in query: `include[]=self_service_page_token`. + Include []models.SubscriptionListInclude } -// ListSubscriptions takes context, page, perPage, state, product, productPricePointId, coupon, dateField, startDate, endDate, startDatetime, endDatetime, metadata, direction, sort, include as parameters and -// returns an models.ApiResponse with []models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// This method will return an array of subscriptions from a Site. Pay close attention to query string filters and pagination in order to control responses from the server. -// ## Search for a subscription -// Use the query strings below to search for a subscription using the criteria available. The return value will be an array. -// ## Self-Service Page token +// ListSubscriptions takes context, page, perPage, state, product, productPricePointId, coupon, dateField, startDate, endDate, startDatetime, endDatetime, metadata, direction, sort, include as parameters and +// returns an models.ApiResponse with []models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// This method will return an array of subscriptions from a Site. Pay close attention to query string filters and pagination in order to control responses from the server. +// ## Search for a subscription +// Use the query strings below to search for a subscription using the criteria available. The return value will be an array. +// ## Self-Service Page token // Self-Service Page token for the subscriptions is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. func (s *SubscriptionsController) ListSubscriptions( - ctx context.Context, - page *int, - perPage *int, - state *models.SubscriptionStateFilter, - product *int, - productPricePointId *int, - coupon *int, - dateField *models.SubscriptionDateField, - startDate *time.Time, - endDate *time.Time, - startDatetime *time.Time, - endDatetime *time.Time, - metadata map[string]string, - direction *models.SortingDirection, - sort *models.SubscriptionSort, - include []models.SubscriptionListInclude) ( - models.ApiResponse[[]models.SubscriptionResponse], - error) { - req := s.prepareRequest(ctx, "GET", "/subscriptions.json") - req.Authenticate(NewAuth("BasicAuth")) - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if state != nil { - req.QueryParam("state", *state) - } - if product != nil { - req.QueryParam("product", *product) - } - if productPricePointId != nil { - req.QueryParam("product_price_point_id", *productPricePointId) - } - if coupon != nil { - req.QueryParam("coupon", *coupon) - } - if dateField != nil { - req.QueryParam("date_field", *dateField) - } - if startDate != nil { - req.QueryParam("start_date", startDate.Format(models.DEFAULT_DATE)) - } - if endDate != nil { - req.QueryParam("end_date", endDate.Format(models.DEFAULT_DATE)) - } - if startDatetime != nil { - req.QueryParam("start_datetime", startDatetime.Format(time.RFC3339)) - } - if endDatetime != nil { - req.QueryParam("end_datetime", endDatetime.Format(time.RFC3339)) - } - if metadata != nil { - req.QueryParam("metadata", metadata) - } - if direction != nil { - req.QueryParam("direction", *direction) - } - if sort != nil { - req.QueryParam("sort", *sort) - } - if include != nil { - req.QueryParam("include[]", include) - } - var result []models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListSubscriptionsInput) ( + models.ApiResponse[[]models.SubscriptionResponse], + error) { + req := s.prepareRequest(ctx, "GET", "/subscriptions.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.State != nil { + req.QueryParam("state", *input.State) + } + if input.Product != nil { + req.QueryParam("product", *input.Product) + } + if input.ProductPricePointId != nil { + req.QueryParam("product_price_point_id", *input.ProductPricePointId) + } + if input.Coupon != nil { + req.QueryParam("coupon", *input.Coupon) + } + if input.DateField != nil { + req.QueryParam("date_field", *input.DateField) + } + if input.StartDate != nil { + req.QueryParam("start_date", input.StartDate.Format(models.DEFAULT_DATE)) + } + if input.EndDate != nil { + req.QueryParam("end_date", input.EndDate.Format(models.DEFAULT_DATE)) + } + if input.StartDatetime != nil { + req.QueryParam("start_datetime", input.StartDatetime.Format(time.RFC3339)) + } + if input.EndDatetime != nil { + req.QueryParam("end_datetime", input.EndDatetime.Format(time.RFC3339)) + } + if input.Metadata != nil { + req.QueryParam("metadata", input.Metadata) + } + if input.Direction != nil { + req.QueryParam("direction", *input.Direction) + } + if input.Sort != nil { + req.QueryParam("sort", *input.Sort) + } + if input.Include != nil { + req.QueryParam("include[]", input.Include) + } + var result []models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateSubscription takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// The subscription endpoint allows you to instantly update one or many attributes about a subscription in a single call. -// ## Update Subscription Payment Method -// Change the card that your Subscriber uses for their subscription. You can also use this method to simply change the expiration date of the card **if your gateway allows**. -// Note that partial card updates for **Authorize.Net** are not allowed via this endpoint. The existing Payment Profile must be directly updated instead. -// You also use this method to change the subscription to a different product by setting a new value for product_handle. A product change can be done in two different ways, **product change** or **delayed product change**. -// ## Product Change -// This endpoint may be used to change a subscription's product. The new payment amount is calculated and charged at the normal start of the next period. If you desire complex product changes or prorated upgrades and downgrades instead, please see the documentation on Migrating Subscription Products. -// To perform a product change, simply set either the `product_handle` or `product_id` attribute to that of a different product from the same site as the subscription. You can also change the price point by passing in either `product_price_point_id` or `product_price_point_handle` - otherwise the new product's default price point will be used. -// ### Delayed Product Change -// This method also changes the product and/or price point, and the new payment amount is calculated and charged at the normal start of the next period. -// This method schedules the product change to happen automatically at the subscription’s next renewal date. To perform a Delayed Product Change, set the `product_handle` attribute as you would in a regular product change, but also set the `product_change_delayed` attribute to `true`. No proration applies in this case. -// You can also perform a delayed change to the price point by passing in either `product_price_point_id` or `product_price_point_handle` -// **Note: To cancel a delayed product change, set `next_product_id` to an empty string.** -// ## Billing Date Changes -// ### Regular Billing Date Changes -// Send the `next_billing_at` to set the next billing date for the subscription. After that date passes and the subscription is processed, the following billing date will be set according to the subscription's product period. -// Note that if you pass an invalid date, we will automatically interpret and set the correct date. For example, when February 30 is entered, the next billing will be set to March 2nd in a non-leap year. -// The server response will not return data under the key/value pair of `next_billing`. Please view the key/value pair of `current_period_ends_at` to verify that the `next_billing` date has been changed successfully. -// ### Snap Day Changes -// For a subscription using Calendar Billing, setting the next billing date is a bit different. Send the `snap_day` attribute to change the calendar billing date for **a subscription using a product eligible for calendar billing**. +// UpdateSubscription takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// The subscription endpoint allows you to instantly update one or many attributes about a subscription in a single call. +// ## Update Subscription Payment Method +// Change the card that your Subscriber uses for their subscription. You can also use this method to simply change the expiration date of the card **if your gateway allows**. +// Note that partial card updates for **Authorize.Net** are not allowed via this endpoint. The existing Payment Profile must be directly updated instead. +// You also use this method to change the subscription to a different product by setting a new value for product_handle. A product change can be done in two different ways, **product change** or **delayed product change**. +// ## Product Change +// This endpoint may be used to change a subscription's product. The new payment amount is calculated and charged at the normal start of the next period. If you desire complex product changes or prorated upgrades and downgrades instead, please see the documentation on Migrating Subscription Products. +// To perform a product change, simply set either the `product_handle` or `product_id` attribute to that of a different product from the same site as the subscription. You can also change the price point by passing in either `product_price_point_id` or `product_price_point_handle` - otherwise the new product's default price point will be used. +// ### Delayed Product Change +// This method also changes the product and/or price point, and the new payment amount is calculated and charged at the normal start of the next period. +// This method schedules the product change to happen automatically at the subscription’s next renewal date. To perform a Delayed Product Change, set the `product_handle` attribute as you would in a regular product change, but also set the `product_change_delayed` attribute to `true`. No proration applies in this case. +// You can also perform a delayed change to the price point by passing in either `product_price_point_id` or `product_price_point_handle` +// **Note: To cancel a delayed product change, set `next_product_id` to an empty string.** +// ## Billing Date Changes +// ### Regular Billing Date Changes +// Send the `next_billing_at` to set the next billing date for the subscription. After that date passes and the subscription is processed, the following billing date will be set according to the subscription's product period. +// Note that if you pass an invalid date, we will automatically interpret and set the correct date. For example, when February 30 is entered, the next billing will be set to March 2nd in a non-leap year. +// The server response will not return data under the key/value pair of `next_billing`. Please view the key/value pair of `current_period_ends_at` to verify that the `next_billing` date has been changed successfully. +// ### Snap Day Changes +// For a subscription using Calendar Billing, setting the next billing date is a bit different. Send the `snap_day` attribute to change the calendar billing date for **a subscription using a product eligible for calendar billing**. // Note: If you change the product associated with a subscription that contains a `snap_date` and immediately `READ/GET` the subscription data, it will still contain evidence of the existing `snap_date`. This is due to the fact that a product change is instantanous and only affects the product associated with a subscription. After the `next_billing` date arrives, the `snap_day` associated with the subscription will return to `null.` Another way of looking at this is that you willl have to wait for the next billing cycle to arrive before the `snap_date` will reset to `null`. func (s *SubscriptionsController) UpdateSubscription( - ctx context.Context, - subscriptionId int, - body *models.UpdateSubscriptionRequest) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/subscriptions/%v.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.UpdateSubscriptionRequest) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/subscriptions/%v.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReadSubscription takes context, subscriptionId, include as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// Use this endpoint to find subscription details. -// ## Self-Service Page token +// ReadSubscription takes context, subscriptionId, include as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// Use this endpoint to find subscription details. +// ## Self-Service Page token // Self-Service Page token for the subscription is not returned by default. If this information is desired, the include[]=self_service_page_token parameter must be provided with the request. func (s *SubscriptionsController) ReadSubscription( - ctx context.Context, - subscriptionId int, - include []models.SubscriptionInclude) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "GET", - fmt.Sprintf("/subscriptions/%v.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - if include != nil { - req.QueryParam("include[]", include) - } - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + include []models.SubscriptionInclude) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "GET", + fmt.Sprintf("/subscriptions/%v.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + if include != nil { + req.QueryParamWithArraySerializationOption("include[]", include, https.Plain) + } + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// OverrideSubscription takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// This API endpoint allows you to set certain subscription fields that are usually managed for you automatically. Some of the fields can be set via the normal Subscriptions Update API, but others can only be set using this endpoint. -// This endpoint is provided for cases where you need to “align” Chargify data with data that happened in your system, perhaps before you started using Chargify. For example, you may choose to import your historical subscription data, and would like the activation and cancellation dates in Chargify to match your existing historical dates. Chargify does not backfill historical events (i.e. from the Events API), but some static data can be changed via this API. -// Why are some fields only settable from this endpoint, and not the normal subscription create and update endpoints? Because we want users of this endpoint to be aware that these fields are usually managed by Chargify, and using this API means **you are stepping out on your own.** -// Changing these fields will not affect any other attributes. For example, adding an expiration date will not affect the next assessment date on the subscription. -// If you regularly need to override the current_period_starts_at for new subscriptions, this can also be accomplished by setting both `previous_billing_at` and `next_billing_at` at subscription creation. See the documentation on [Importing Subscriptions](./b3A6MTQxMDgzODg-create-subscription#subscriptions-import) for more information. -// ## Limitations -// When passing `current_period_starts_at` some validations are made: -// 1. The subscription needs to be unbilled (no statements or invoices). -// 2. The value passed must be a valid date/time. We recommend using the iso 8601 format. -// 3. The value passed must be before the current date/time. +// OverrideSubscription takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// This API endpoint allows you to set certain subscription fields that are usually managed for you automatically. Some of the fields can be set via the normal Subscriptions Update API, but others can only be set using this endpoint. +// This endpoint is provided for cases where you need to “align” Chargify data with data that happened in your system, perhaps before you started using Chargify. For example, you may choose to import your historical subscription data, and would like the activation and cancellation dates in Chargify to match your existing historical dates. Chargify does not backfill historical events (i.e. from the Events API), but some static data can be changed via this API. +// Why are some fields only settable from this endpoint, and not the normal subscription create and update endpoints? Because we want users of this endpoint to be aware that these fields are usually managed by Chargify, and using this API means **you are stepping out on your own.** +// Changing these fields will not affect any other attributes. For example, adding an expiration date will not affect the next assessment date on the subscription. +// If you regularly need to override the current_period_starts_at for new subscriptions, this can also be accomplished by setting both `previous_billing_at` and `next_billing_at` at subscription creation. See the documentation on [Importing Subscriptions](./b3A6MTQxMDgzODg-create-subscription#subscriptions-import) for more information. +// ## Limitations +// When passing `current_period_starts_at` some validations are made: +// 1. The subscription needs to be unbilled (no statements or invoices). +// 2. The value passed must be a valid date/time. We recommend using the iso 8601 format. +// 3. The value passed must be before the current date/time. // If unpermitted parameters are sent, a 400 HTTP response is sent along with a string giving the reason for the problem. func (s *SubscriptionsController) OverrideSubscription( - ctx context.Context, - subscriptionId int, - body *models.OverrideSubscriptionRequest) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/subscriptions/%v/override.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subscriptionId int, + body *models.OverrideSubscriptionRequest) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/subscriptions/%v/override.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSingleErrorResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// FindSubscription takes context, reference as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. +// FindSubscription takes context, reference as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. // Use this endpoint to find a subscription by its reference. func (s *SubscriptionsController) FindSubscription( - ctx context.Context, - reference *string) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest(ctx, "GET", "/subscriptions/lookup.json") - req.Authenticate(NewAuth("BasicAuth")) - if reference != nil { - req.QueryParam("reference", *reference) - } - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + reference *string) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest(ctx, "GET", "/subscriptions/lookup.json") + req.Authenticate(NewAuth("BasicAuth")) + if reference != nil { + req.QueryParam("reference", *reference) + } + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// PurgeSubscription takes context, subscriptionId, ack, cascade as parameters and -// returns an models.ApiResponse with data and -// an error if there was an issue with the request or response. -// For sites in test mode, you may purge individual subscriptions. -// Provide the subscription ID in the url. To confirm, supply the customer ID in the query string `ack` parameter. You may also delete the customer record and/or payment profiles by passing `cascade` parameters. For example, to delete just the customer record, the query params would be: `?ack={customer_id}&cascade[]=customer` -// If you need to remove subscriptions from a live site, please contact support to discuss your use case. -// ### Delete customer and payment profile +// PurgeSubscription takes context, subscriptionId, ack, cascade as parameters and +// returns an models.ApiResponse with data and +// an error if there was an issue with the request or response. +// For sites in test mode, you may purge individual subscriptions. +// Provide the subscription ID in the url. To confirm, supply the customer ID in the query string `ack` parameter. You may also delete the customer record and/or payment profiles by passing `cascade` parameters. For example, to delete just the customer record, the query params would be: `?ack={customer_id}&cascade[]=customer` +// If you need to remove subscriptions from a live site, please contact support to discuss your use case. +// ### Delete customer and payment profile // The query params will be: `?ack={customer_id}&cascade[]=customer&cascade[]=payment_profile` func (s *SubscriptionsController) PurgeSubscription( - ctx context.Context, - subscriptionId int, - ack int, - cascade []models.SubscriptionPurgeType) ( - *http.Response, - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/purge.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.QueryParam("ack", ack) - if cascade != nil { - req.QueryParam("cascade[]", cascade) - } - - context, err := req.Call() - if err != nil { - return context.Response, err - } - return context.Response, err + ctx context.Context, + subscriptionId int, + ack int, + cascade []models.SubscriptionPurgeType) ( + *http.Response, + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/purge.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.QueryParamWithArraySerializationOption("ack", ack, https.Plain) + if cascade != nil { + req.QueryParamWithArraySerializationOption("cascade[]", cascade, https.Plain) + } + + context, err := req.Call() + if err != nil { + return context.Response, err + } + return context.Response, err } -// UpdatePrepaidSubscriptionConfiguration takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.PrepaidConfigurationResponse data and -// an error if there was an issue with the request or response. +// UpdatePrepaidSubscriptionConfiguration takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.PrepaidConfigurationResponse data and +// an error if there was an issue with the request or response. // Use this endpoint to update a subscription's prepaid configuration. func (s *SubscriptionsController) UpdatePrepaidSubscriptionConfiguration( - ctx context.Context, - subscriptionId int, - body *models.UpsertPrepaidConfigurationRequest) ( - models.ApiResponse[models.PrepaidConfigurationResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/prepaid_configurations.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.PrepaidConfigurationResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.PrepaidConfigurationResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.UpsertPrepaidConfigurationRequest) ( + models.ApiResponse[models.PrepaidConfigurationResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/prepaid_configurations.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.PrepaidConfigurationResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.PrepaidConfigurationResponse](decoder) + return models.NewApiResponse(result, resp), err } -// PreviewSubscription takes context, body as parameters and -// returns an models.ApiResponse with models.SubscriptionPreviewResponse data and -// an error if there was an issue with the request or response. -// The Chargify API allows you to preview a subscription by POSTing the same JSON or XML as for a subscription creation. -// The "Next Billing" amount and "Next Billing" date are represented in each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). -// ## Side effects -// A subscription will not be created by sending a POST to this endpoint. It is meant to serve as a prediction. -// ## Taxable Subscriptions -// This endpoint will preview taxes applicable to a purchase. In order for taxes to be previewed, the following conditions must be met: -// + Taxes must be configured on the subscription -// + The preview must be for the purchase of a taxable product or component, or combination of the two. -// + The subscription payload must contain a full billing or shipping address in order to calculate tax -// For more information about creating taxable previews, please see our documentation guide on how to create [taxable subscriptions.](https://chargify.zendesk.com/hc/en-us/articles/4407904217755#creating-taxable-subscriptions) -// You do **not** need to include a card number to generate tax information when you are previewing a subscription. However, please note that when you actually want to create the subscription, you must include the credit card information if you want the billing address to be stored in Chargify. The billing address and the credit card information are stored together within the payment profile object. Also, you may not send a billing address to Chargify without payment profile information, as the address is stored on the card. -// You can pass shipping and billing addresses and still decide not to calculate taxes. To do that, pass `skip_billing_manifest_taxes: true` attribute. -// ## Non-taxable Subscriptions +// PreviewSubscription takes context, body as parameters and +// returns an models.ApiResponse with models.SubscriptionPreviewResponse data and +// an error if there was an issue with the request or response. +// The Chargify API allows you to preview a subscription by POSTing the same JSON or XML as for a subscription creation. +// The "Next Billing" amount and "Next Billing" date are represented in each Subscriber's Summary. For more information, please see our documentation [here](https://chargify.zendesk.com/hc/en-us/articles/4407884887835#next-billing). +// ## Side effects +// A subscription will not be created by sending a POST to this endpoint. It is meant to serve as a prediction. +// ## Taxable Subscriptions +// This endpoint will preview taxes applicable to a purchase. In order for taxes to be previewed, the following conditions must be met: +// + Taxes must be configured on the subscription +// + The preview must be for the purchase of a taxable product or component, or combination of the two. +// + The subscription payload must contain a full billing or shipping address in order to calculate tax +// For more information about creating taxable previews, please see our documentation guide on how to create [taxable subscriptions.](https://chargify.zendesk.com/hc/en-us/articles/4407904217755#creating-taxable-subscriptions) +// You do **not** need to include a card number to generate tax information when you are previewing a subscription. However, please note that when you actually want to create the subscription, you must include the credit card information if you want the billing address to be stored in Chargify. The billing address and the credit card information are stored together within the payment profile object. Also, you may not send a billing address to Chargify without payment profile information, as the address is stored on the card. +// You can pass shipping and billing addresses and still decide not to calculate taxes. To do that, pass `skip_billing_manifest_taxes: true` attribute. +// ## Non-taxable Subscriptions // If you'd like to calculate subscriptions that do not include tax, please feel free to leave off the billing information. func (s *SubscriptionsController) PreviewSubscription( - ctx context.Context, - body *models.CreateSubscriptionRequest) ( - models.ApiResponse[models.SubscriptionPreviewResponse], - error) { - req := s.prepareRequest(ctx, "POST", "/subscriptions/preview.json") - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.SubscriptionPreviewResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionPreviewResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.CreateSubscriptionRequest) ( + models.ApiResponse[models.SubscriptionPreviewResponse], + error) { + req := s.prepareRequest(ctx, "POST", "/subscriptions/preview.json") + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.SubscriptionPreviewResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionPreviewResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ApplyCouponsToSubscription takes context, subscriptionId, code, body as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// An existing subscription can accommodate multiple discounts/coupon codes. This is only applicable if each coupon is stackable. For more information on stackable coupons, we recommend reviewing our [coupon documentation.](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#stackable-coupons) -// ## Query Parameters vs Request Body Parameters -// Passing in a coupon code as a query parameter will add the code to the subscription, completely replacing all existing coupon codes on the subscription. +// ApplyCouponsToSubscription takes context, subscriptionId, code, body as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// An existing subscription can accommodate multiple discounts/coupon codes. This is only applicable if each coupon is stackable. For more information on stackable coupons, we recommend reviewing our [coupon documentation.](https://chargify.zendesk.com/hc/en-us/articles/4407755909531#stackable-coupons) +// ## Query Parameters vs Request Body Parameters +// Passing in a coupon code as a query parameter will add the code to the subscription, completely replacing all existing coupon codes on the subscription. // For this reason, using this query parameter on this endpoint has been deprecated in favor of using the request body parameters as described below. When passing in request body parameters, the list of coupon codes will simply be added to any existing list of codes on the subscription. func (s *SubscriptionsController) ApplyCouponsToSubscription( - ctx context.Context, - subscriptionId int, - code *string, - body *models.AddCouponsRequest) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "POST", - fmt.Sprintf("/subscriptions/%v/add_coupon.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionAddCouponError}, - }) - req.Header("Content-Type", "application/json") - if code != nil { - req.QueryParam("code", *code) - } - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + code *string, + body *models.AddCouponsRequest) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "POST", + fmt.Sprintf("/subscriptions/%v/add_coupon.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionAddCouponError}, + }) + req.Header("Content-Type", "application/json") + if code != nil { + req.QueryParam("code", *code) + } + if body != nil { + req.Json(body) + } + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } -// RemoveCouponFromSubscription takes context, subscriptionId, couponCode as parameters and -// returns an models.ApiResponse with string data and -// an error if there was an issue with the request or response. -// Use this endpoint to remove a coupon from an existing subscription. +// RemoveCouponFromSubscription takes context, subscriptionId, couponCode as parameters and +// returns an models.ApiResponse with string data and +// an error if there was an issue with the request or response. +// Use this endpoint to remove a coupon from an existing subscription. // For more information on the expected behaviour of removing a coupon from a subscription, please see our documentation [here.](https://chargify.zendesk.com/hc/en-us/articles/4407896488987#removing-a-coupon) func (s *SubscriptionsController) RemoveCouponFromSubscription( - ctx context.Context, - subscriptionId int, - couponCode *string) ( - models.ApiResponse[string], - error) { - req := s.prepareRequest( - ctx, - "DELETE", - fmt.Sprintf("/subscriptions/%v/remove_coupon.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionRemoveCouponErrors}, - }) - if couponCode != nil { - req.QueryParam("coupon_code", *couponCode) - } - - str, resp, err := req.CallAsText() - var result string = str - - if err != nil { - return models.NewApiResponse(result, resp), err - } - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + couponCode *string) ( + models.ApiResponse[string], + error) { + req := s.prepareRequest( + ctx, + "DELETE", + fmt.Sprintf("/subscriptions/%v/remove_coupon.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewSubscriptionRemoveCouponErrors}, + }) + if couponCode != nil { + req.QueryParam("coupon_code", *couponCode) + } + + str, resp, err := req.CallAsText() + var result string = str + + if err != nil { + return models.NewApiResponse(result, resp), err + } + return models.NewApiResponse(result, resp), err } -// ActivateSubscription takes context, subscriptionId, body as parameters and -// returns an models.ApiResponse with models.SubscriptionResponse data and -// an error if there was an issue with the request or response. -// Chargify offers the ability to activate awaiting signup and trialing subscriptions. This feature is only available on the Relationship Invoicing architecture. Subscriptions in a group may not be activated immediately. -// For details on how the activation works, and how to activate subscriptions through the application, see [activation](#). -// The `revert_on_failure` parameter controls the behavior upon activation failure. -// - If set to `true` and something goes wrong i.e. payment fails, then Chargify will not change the subscription's state. The subscription’s billing period will also remain the same. -// - If set to `false` and something goes wrong i.e. payment fails, then Chargify will continue through with the activation and enter an end of life state. For trialing subscriptions, that will either be trial ended (if the trial is no obligation), past due (if the trial has an obligation), or canceled (if the site has no dunning strategy, or has a strategy that says to cancel immediately). For awaiting signup subscriptions, that will always be canceled. -// The default activation failure behavior can be configured per activation attempt, or you may set a default value under Config > Settings > Subscription Activation Settings. -// ## Activation Scenarios -// ### Activate Awaiting Signup subscription -// - Given you have a product without trial -// - Given you have a site without dunning strategy -// ```mermaid -// flowchart LR -// AS[Awaiting Signup] --> A{Activate} -// A -->|Success| Active -// A -->|Failure| ROF{revert_on_failure} -// ROF -->|true| AS -// ROF -->|false| Canceled -// ``` -// - Given you have a product with trial -// - Given you have a site with dunning strategy -// ```mermaid -// flowchart LR -// AS[Awaiting Signup] --> A{Activate} -// A -->|Success| Trialing -// A -->|Failure| ROF{revert_on_failure} -// ROF -->|true| AS -// ROF -->|false| PD[Past Due] -// ``` -// ### Activate Trialing subscription -// You can read more about the behavior of trialing subscriptions [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404494617357#trialing-subscriptions-0-0). +// ActivateSubscription takes context, subscriptionId, body as parameters and +// returns an models.ApiResponse with models.SubscriptionResponse data and +// an error if there was an issue with the request or response. +// Chargify offers the ability to activate awaiting signup and trialing subscriptions. This feature is only available on the Relationship Invoicing architecture. Subscriptions in a group may not be activated immediately. +// For details on how the activation works, and how to activate subscriptions through the application, see [activation](#). +// The `revert_on_failure` parameter controls the behavior upon activation failure. +// - If set to `true` and something goes wrong i.e. payment fails, then Chargify will not change the subscription's state. The subscription’s billing period will also remain the same. +// - If set to `false` and something goes wrong i.e. payment fails, then Chargify will continue through with the activation and enter an end of life state. For trialing subscriptions, that will either be trial ended (if the trial is no obligation), past due (if the trial has an obligation), or canceled (if the site has no dunning strategy, or has a strategy that says to cancel immediately). For awaiting signup subscriptions, that will always be canceled. +// The default activation failure behavior can be configured per activation attempt, or you may set a default value under Config > Settings > Subscription Activation Settings. +// ## Activation Scenarios +// ### Activate Awaiting Signup subscription +// - Given you have a product without trial +// - Given you have a site without dunning strategy +// ```mermaid +// flowchart LR +// AS[Awaiting Signup] --> A{Activate} +// A -->|Success| Active +// A -->|Failure| ROF{revert_on_failure} +// ROF -->|true| AS +// ROF -->|false| Canceled +// ``` +// - Given you have a product with trial +// - Given you have a site with dunning strategy +// ```mermaid +// flowchart LR +// AS[Awaiting Signup] --> A{Activate} +// A -->|Success| Trialing +// A -->|Failure| ROF{revert_on_failure} +// ROF -->|true| AS +// ROF -->|false| PD[Past Due] +// ``` +// ### Activate Trialing subscription +// You can read more about the behavior of trialing subscriptions [here](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404494617357#trialing-subscriptions-0-0). // When the `revert_on_failure` parameter is set to `true`, the subscription's state will remain as Trialing, we will void the invoice from activation and return any prepayments and credits applied to the invoice back to the subscription. func (s *SubscriptionsController) ActivateSubscription( - ctx context.Context, - subscriptionId int, - body *models.ActivateSubscriptionRequest) ( - models.ApiResponse[models.SubscriptionResponse], - error) { - req := s.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/subscriptions/%v/activate.json", subscriptionId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "400": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.SubscriptionResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + subscriptionId int, + body *models.ActivateSubscriptionRequest) ( + models.ApiResponse[models.SubscriptionResponse], + error) { + req := s.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/subscriptions/%v/activate.json", subscriptionId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "400": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorArrayMapResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.SubscriptionResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.SubscriptionResponse](decoder) + return models.NewApiResponse(result, resp), err } diff --git a/test/component_allocations_test.go b/test/component_allocations_test.go index 18bf8621..2ead52b3 100644 --- a/test/component_allocations_test.go +++ b/test/component_allocations_test.go @@ -38,17 +38,17 @@ func (s *ComponentAlocationSuite) TestComponentAllocations() { Name: strPtr(s.fkr.RandomStringWithLength(20)), Prices: []models.Price{ { - StartingQuantity: 1, - UnitPrice: 1, + StartingQuantity: models.PriceStartingQuantityContainer.FromNumber(1), + UnitPrice: models.PriceUnitPriceContainer.FromPrecision(1), }, }, }, }, - UnitPrice: interfacePtr("100"), + UnitPrice: models.ToPointer(models.OnOffComponentUnitPriceContainer.FromString("100")), Prices: []models.Price{ { - StartingQuantity: 1, - UnitPrice: 1, + StartingQuantity: models.PriceStartingQuantityContainer.FromNumber(1), + UnitPrice: models.PriceUnitPriceContainer.FromPrecision(1), }, }, }, @@ -72,13 +72,13 @@ func (s *ComponentAlocationSuite) TestComponentAllocations() { PricingScheme: toPtr[models.PricingScheme](models.PricingScheme_PERUNIT), Prices: []models.Price{ { - StartingQuantity: 1, - UnitPrice: 1, + StartingQuantity: models.PriceStartingQuantityContainer.FromNumber(1), + UnitPrice: models.PriceUnitPriceContainer.FromPrecision(1), }, }, }, }, - UnitPrice: interfacePtr("100"), + UnitPrice: models.ToPointer(models.QuantityBasedComponentUnitPriceContainer.FromString("100")), }, }, ) @@ -109,8 +109,12 @@ func (s *ComponentAlocationSuite) TestComponentAllocations() { s.Equal(http.StatusOK, response.Response.StatusCode) prevAllocations := response.Data.AllocationPreview.Allocations - s.Equal(float64(1), *prevAllocations[0].Quantity) - s.Equal(fmt.Sprintf("%.1f", expected[1].Quantity), *prevAllocations[1].Quantity) + q0, ok := prevAllocations[0].Quantity.AsNumber() + s.Equal(true, ok) + s.Equal(int(1), *q0) + q1, ok := prevAllocations[1].Quantity.AsString() + s.Equal(true, ok) + s.Equal(fmt.Sprintf("%.1f", expected[1].Quantity), *q1) allocationsResp, err := s.client.SubscriptionComponentsController().AllocateComponents( ctx, @@ -123,8 +127,12 @@ func (s *ComponentAlocationSuite) TestComponentAllocations() { s.Equal(http.StatusCreated, allocationsResp.Response.StatusCode) responseAllocations := allocationsResp.Data - s.Equal(float64(1), *responseAllocations[0].Allocation.Quantity) - s.Equal(fmt.Sprintf("%.1f", expected[1].Quantity), *responseAllocations[1].Allocation.Quantity) + r0, ok := responseAllocations[0].Allocation.Quantity.AsNumber() + s.Equal(true, ok) + s.Equal(int(1), *r0) + r1, ok := responseAllocations[1].Allocation.Quantity.AsString() + s.Equal(true, ok) + s.Equal(fmt.Sprintf("%.1f", expected[1].Quantity), *r1) }, }, { @@ -136,14 +144,14 @@ func (s *ComponentAlocationSuite) TestComponentAllocations() { }, }, assert: func(t *testing.T, response models.ApiResponse[models.AllocationPreviewResponse], input []models.CreateAllocation, err error) { - s.Equal("ComponentAllocationError occured: HTTP Response Not OK. Status code: 422. Response: " + - fmt.Sprintf("'{\"errors\":[{\"kind\":\"allocation\",\"component_id\":%d,\"on\":\"quantity\",", *onOffResp.Data.Component.Id) + - "\"message\":\"Quantity: must be either 1 (on) or 0 (off).\"}]}'.", - err.Error()) + s.Equal("ComponentAllocationError occured: HTTP Response Not OK. Status code: 422. Response: "+ + fmt.Sprintf("'{\"errors\":[{\"kind\":\"allocation\",\"component_id\":%d,\"on\":\"quantity\",", *onOffResp.Data.Component.Id)+ + "\"message\":\"Quantity: must be either 1 (on) or 0 (off).\"}]}'.", + err.Error()) - actualErr, ok := err.(*errors.ComponentAllocationError) - s.Equal(http.StatusUnprocessableEntity, actualErr.StatusCode) - s.True(ok) + actualErr, ok := err.(*errors.ComponentAllocationError) + s.Equal(http.StatusUnprocessableEntity, actualErr.StatusCode) + s.True(ok) }, }, } diff --git a/test/go.mod b/test/go.mod index 2eb11d13..9a962fba 100644 --- a/test/go.mod +++ b/test/go.mod @@ -3,7 +3,6 @@ module github.com/maxio-com/ab-golang-sdk/test go 1.21 require ( - github.com/apimatic/go-core-runtime v0.0.16 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/go-openapi/jsonpointer v0.20.2 // indirect github.com/go-openapi/swag v0.22.5 // indirect @@ -14,6 +13,7 @@ require ( ) require ( + github.com/apimatic/go-core-runtime v0.0.18 github.com/caarlos0/env/v10 v10.0.0 github.com/jaswdr/faker v1.19.1 github.com/maxio-com/ab-golang-sdk v0.0.1 diff --git a/test/go.sum b/test/go.sum index 5d04c46f..80de9af7 100644 --- a/test/go.sum +++ b/test/go.sum @@ -1,5 +1,5 @@ -github.com/apimatic/go-core-runtime v0.0.16 h1:tj14lVDfe03ukFv2krPLZO+9DZldWdyWnlHfG4gmoGc= -github.com/apimatic/go-core-runtime v0.0.16/go.mod h1:CqQWJAOScv0NLQQVBVKCRvw83iq7sygbvpZgVvWLiFw= +github.com/apimatic/go-core-runtime v0.0.18 h1:WlbvjWK88+RjlIrSDXqwPaT1/mKsBbl9MmHNPbZFfqs= +github.com/apimatic/go-core-runtime v0.0.18/go.mod h1:CqQWJAOScv0NLQQVBVKCRvw83iq7sygbvpZgVvWLiFw= github.com/caarlos0/env/v10 v10.0.0 h1:yIHUBZGsyqCnpTkbjk8asUlx6RFhhEs+h7TOBdgdzXA= github.com/caarlos0/env/v10 v10.0.0/go.mod h1:ZfulV76NvVPw3tm591U4SwL3Xx9ldzBP9aGxzeN7G18= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= diff --git a/test/invoice_test.go b/test/invoice_test.go index 5a8f7619..a27567c4 100644 --- a/test/invoice_test.go +++ b/test/invoice_test.go @@ -6,6 +6,7 @@ import ( "testing" "time" + advancedbilling "github.com/maxio-com/ab-golang-sdk" "github.com/maxio-com/ab-golang-sdk/errors" "github.com/maxio-com/ab-golang-sdk/models" "github.com/stretchr/testify/suite" @@ -44,8 +45,8 @@ func (s *InvoiceSuite) TestInvoice() { LineItems: []models.CreateInvoiceItem{ { Title: strPtr("A product"), - Quantity: interfacePtr(12), - UnitPrice: interfacePtr("150"), + Quantity: models.ToPointer(models.CreateInvoiceItemQuantityContainer.FromPrecision(12)), + UnitPrice: models.ToPointer(models.CreateInvoiceItemUnitPriceContainer.FromString("150")), }, }, IssueDate: timePtr(time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)), @@ -94,13 +95,9 @@ func (s *InvoiceSuite) TestInvoice() { events, err := s.client.InvoicesController().ListInvoiceEvents( ctx, - nil, - nil, - nil, - nil, - resp.Data.Invoice.Uid, - nil, - nil, // cant pass event types here. Server throws 500 + advancedbilling.ListInvoiceEventsInput{ + InvoiceUid: resp.Data.Invoice.Uid, // cant pass event types here. Server throws 500 + }, ) s.NoError(err) @@ -119,8 +116,8 @@ func (s *InvoiceSuite) TestInvoice() { LineItems: []models.CreateInvoiceItem{ { Title: strPtr("A product"), - Quantity: interfacePtr(12), - UnitPrice: interfacePtr("150"), + Quantity: models.ToPointer(models.CreateInvoiceItemQuantityContainer.FromPrecision(12)), + UnitPrice: models.ToPointer(models.CreateInvoiceItemUnitPriceContainer.FromString("150")), PeriodRangeStart: strPtr(dateFromTime(time.Now())), PeriodRangeEnd: strPtr(dateFromTime(time.Now().AddDate(-1, 0, 0))), }, @@ -137,8 +134,8 @@ func (s *InvoiceSuite) TestInvoice() { }, }, assert: func(t *testing.T, resp models.ApiResponse[models.InvoiceResponse], invoice models.CreateInvoice, err error) { - s.Equal(err.Error(), "ErrorArrayMapResponse occured: HTTP Response Not OK. Status code: 422. Response: " + - "'{\"errors\":{\"line_items[0].period_range_end\":[\"Must be greater or equal to period_range_start.\"]}}'.") + s.Equal(err.Error(), "ErrorArrayMapResponse occured: HTTP Response Not OK. Status code: 422. Response: "+ + "'{\"errors\":{\"line_items[0].period_range_end\":[\"Must be greater or equal to period_range_start.\"]}}'.") actualErr, ok := err.(*errors.ErrorArrayMapResponse) s.Equal(http.StatusUnprocessableEntity, actualErr.StatusCode) diff --git a/test/metafields_test.go b/test/metafields_test.go index b0b3661a..54b0ff5f 100644 --- a/test/metafields_test.go +++ b/test/metafields_test.go @@ -5,6 +5,7 @@ import ( "net/http" "testing" + advancedbilling "github.com/maxio-com/ab-golang-sdk" "github.com/maxio-com/ab-golang-sdk/models" "github.com/stretchr/testify/suite" ) @@ -49,18 +50,17 @@ func (s *MetafieldsSuite) TestMetafields() { "option 1", "option 2", } - cases := []struct { name string resourceType models.ResourceType - metafields interface{} + metafields models.CreateMetafieldsRequestMetafields assert func(t *testing.T, resp models.ApiResponse[[]models.Metafield], err error) afterTest func(t *testing.T, metafields []models.Metafield) }{ { name: "subscriptions", resourceType: models.ResourceType_SUBSCRIPTIONS, - metafields: []models.Metafield{ + metafields: models.CreateMetafieldsRequestMetafieldsContainer.FromArrayOfCreateMetafield([]models.CreateMetafield{ { Name: &dropdownFieldName, InputType: &dropdownInputType, @@ -68,12 +68,12 @@ func (s *MetafieldsSuite) TestMetafields() { PublicShow: toPtr[models.IncludeOption](models.IncludeOption_INCLUDE), PublicEdit: toPtr[models.IncludeOption](models.IncludeOption_INCLUDE), }, - Enum: models.NewOptional[interface{}](interfacePtr(enums)), + Enum: enums, }, { Name: &textFieldName, }, - }, + }), assert: func(t *testing.T, resp models.ApiResponse[[]models.Metafield], err error) { s.NoError(err) s.Contains([]int{http.StatusOK, http.StatusCreated}, resp.Response.StatusCode) @@ -120,23 +120,13 @@ func (s *MetafieldsSuite) TestMetafields() { rSubs, err := s.client.SubscriptionsController().ListSubscriptions( ctx, - nil, - nil, - nil, - product.Id, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - map[string]string{ - dropdownFieldName: enums[0], + advancedbilling.ListSubscriptionsInput{ + ProductPricePointId: product.ProductPricePointId, + Metadata: map[string]string{ + dropdownFieldName: enums[0], + }, + Include: []models.SubscriptionListInclude{}, }, - nil, - nil, - []models.SubscriptionListInclude{}, ) s.NoError(err) s.Equal(http.StatusOK, r.Response.StatusCode) @@ -160,16 +150,16 @@ func (s *MetafieldsSuite) TestMetafields() { { name: "customers", resourceType: models.ResourceType_CUSTOMERS, - metafields: metafield{ + metafields: models.CreateMetafieldsRequestMetafieldsContainer.FromCreateMetafield(models.CreateMetafield{ Name: &radioFieldName, - InputType: strPtr("radio"), + InputType: models.ToPointer(models.MetafieldInput_RADIO), Enum: enums, Scope: &models.MetafieldScope{ Csv: toPtr[models.IncludeOption](models.IncludeOption_INCLUDE), Invoices: toPtr[models.IncludeOption](models.IncludeOption_INCLUDE), Portal: toPtr[models.IncludeOption](models.IncludeOption_INCLUDE), }, - }, + }), assert: func(t *testing.T, resp models.ApiResponse[[]models.Metafield], err error) { s.NoError(err) s.Contains([]int{http.StatusOK, http.StatusCreated}, resp.Response.StatusCode) diff --git a/test/payment_profiles_test.go b/test/payment_profiles_test.go new file mode 100644 index 00000000..776b86a5 --- /dev/null +++ b/test/payment_profiles_test.go @@ -0,0 +1,60 @@ +package test + +import ( + "context" + "net/http" + "testing" + + "github.com/maxio-com/ab-golang-sdk/models" + + "github.com/stretchr/testify/suite" +) + +type PaymentProfilesSuite struct { + APISuite +} + +func TestPaymentProfilesSuite(t *testing.T) { + suite.Run(t, new(PaymentProfilesSuite)) +} + +func (s *PaymentProfilesSuite) TestPaymentProfiles() { + ctx := context.Background() + + customer := s.generateCustomer(ctx) + pf := s.generateProductFamily(ctx) + product := s.generateProduct(ctx, *pf.Id) + + paymentProfileRes, err := s.client.PaymentProfilesController().CreatePaymentProfile( + ctx, + &models.CreatePaymentProfileRequest{ + PaymentProfile: models.CreatePaymentProfile{ + CustomerId: customer.Id, + ExpirationMonth: models.ToPointer(models.CreatePaymentProfileExpirationMonthContainer.FromNumber(12)), + ExpirationYear: models.ToPointer(models.CreatePaymentProfileExpirationYearContainer.FromNumber(2030)), + FullNumber: models.ToPointer("4111111111111111"), + }, + }, + ) + s.NoError(err) + s.Equal(http.StatusCreated, paymentProfileRes.Response.StatusCode) + + payCred, ok := paymentProfileRes.Data.PaymentProfile.AsCreditCardPaymentProfile() + + s.Equal(true, ok) + + subscriptionRes, err := s.client.SubscriptionsController().CreateSubscription(ctx, &models.CreateSubscriptionRequest{ + Subscription: models.CreateSubscription{ + ProductId: product.Id, + CustomerId: customer.Id, + PaymentProfileId: payCred.Id, + }, + }) + s.NoError(err) + s.Equal(http.StatusCreated, paymentProfileRes.Response.StatusCode) + + paymentProfileNewRes, err := s.client.PaymentProfilesController().ChangeSubscriptionDefaultPaymentProfile(ctx, *subscriptionRes.Data.Subscription.Id, *payCred.Id) + s.Error(err) + s.NotNil(paymentProfileNewRes) + s.Equal(http.StatusUnprocessableEntity, paymentProfileNewRes.Response.StatusCode) +} diff --git a/test/site_test.go b/test/site_test.go index 8dbdc4d4..272387d5 100644 --- a/test/site_test.go +++ b/test/site_test.go @@ -5,8 +5,8 @@ import ( "net/http" "testing" + "github.com/apimatic/go-core-runtime/https" advancedbilling "github.com/maxio-com/ab-golang-sdk" - "github.com/apimatic/go-core-runtime/https" "github.com/maxio-com/ab-golang-sdk/models" "github.com/stretchr/testify/suite" ) @@ -32,7 +32,7 @@ func (s *SiteSuite) TestReadSite() { expectedErr: false, assert: func(t *testing.T, resp models.ApiResponse[models.SiteResponse], err error) { s.Equal(http.StatusOK, resp.Response.StatusCode, "status code") - s.NoError(err) + s.NoError(err) respSite := resp.Data.Site s.Equal(4718, *respSite.Id, "ID") @@ -81,10 +81,10 @@ func (s *SiteSuite) TestReadSite() { name: "unauthorized", client: s.unauthorizedClient, assert: func(t *testing.T, resp models.ApiResponse[models.SiteResponse], err error) { - s.Equal(err.Error(), "ApiError occured: HTTP Response Not OK. Status code: 401. Response: 'HTTP Basic: Access denied.\n'.") + s.Equal(err.Error(), "ApiError occured: HTTP Response Not OK. Status code: 401. Response: 'HTTP Basic: Access denied.\n'.") actualErr, ok := err.(https.ApiError) - s.Equal(http.StatusUnauthorized, actualErr.StatusCode) - s.True(ok) + s.Equal(http.StatusUnauthorized, actualErr.StatusCode) + s.True(ok) }, expectedErr: true, }, diff --git a/test/subscription_test.go b/test/subscription_test.go index 0c269141..e70cf284 100644 --- a/test/subscription_test.go +++ b/test/subscription_test.go @@ -6,8 +6,8 @@ import ( "testing" "time" + "github.com/apimatic/go-core-runtime/https" advancedbilling "github.com/maxio-com/ab-golang-sdk" - "github.com/apimatic/go-core-runtime/https" "github.com/maxio-com/ab-golang-sdk/errors" "github.com/maxio-com/ab-golang-sdk/models" "github.com/stretchr/testify/suite" @@ -45,7 +45,7 @@ func (s *SubscriptionSuite) TestSubscriptionCreate() { *coupon.Code, []models.CreateSubscriptionComponent{ { - ComponentId: interfacePtr(*component.Id), + ComponentId: models.ToPointer(models.CreateSubscriptionComponentComponentIdContainer.FromNumber(*component.Id)), Enabled: boolPtr(true), UnitBalance: intPtr(1), }, @@ -68,19 +68,9 @@ func (s *SubscriptionSuite) TestSubscriptionCreate() { listResp, err := s.client.SubscriptionComponentsController().ListSubscriptionComponents( ctx, - *createdSubscription.Id, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - nil, + advancedbilling.ListSubscriptionComponentsInput{ + SubscriptionId: *createdSubscription.Id, + }, ) s.NoError(err) @@ -116,13 +106,13 @@ func (s *SubscriptionSuite) TestSubscriptionCreate() { []models.CreateSubscriptionComponent{}, ), assert: func(t *testing.T, ar models.ApiResponse[models.SubscriptionResponse], subscription models.CreateSubscription, err error) { - s.Equal(string("ErrorListResponse occured: HTTP Response Not OK. Status code: 422. Response: " + - "'{\"errors\":[\"Coupon Code: 'invalid coupon code' - Coupon code could not be found.\"]}'."), - err.Error()) + s.Equal(string("ErrorListResponse occured: HTTP Response Not OK. Status code: 422. Response: "+ + "'{\"errors\":[\"Coupon Code: 'invalid coupon code' - Coupon code could not be found.\"]}'."), + err.Error()) - actualErr, ok := err.(*errors.ErrorListResponse) - s.Equal(http.StatusUnprocessableEntity, actualErr.StatusCode) - s.True(ok) + actualErr, ok := err.(*errors.ErrorListResponse) + s.Equal(http.StatusUnprocessableEntity, actualErr.StatusCode) + s.True(ok) }, }, { @@ -134,19 +124,19 @@ func (s *SubscriptionSuite) TestSubscriptionCreate() { *coupon.Code, []models.CreateSubscriptionComponent{ { - ComponentId: interfacePtr(*component.Id), + ComponentId: models.ToPointer(models.CreateSubscriptionComponentComponentIdContainer.FromNumber(*component.Id)), Enabled: boolPtr(true), UnitBalance: intPtr(1), }, }, ), assert: func(t *testing.T, ar models.ApiResponse[models.SubscriptionResponse], cs models.CreateSubscription, err error) { - s.Equal("ApiError occured: HTTP Response Not OK. Status code: 401. Response: 'HTTP Basic: Access denied.\n'.", - err.Error()) + s.Equal("ApiError occured: HTTP Response Not OK. Status code: 401. Response: 'HTTP Basic: Access denied.\n'.", + err.Error()) - actualErr, ok := err.(https.ApiError) - s.Equal(http.StatusUnauthorized, actualErr.StatusCode) - s.True(ok) + actualErr, ok := err.(https.ApiError) + s.Equal(http.StatusUnauthorized, actualErr.StatusCode) + s.True(ok) }, }, } @@ -184,8 +174,8 @@ func (s *APISuite) newSubscription( LastName: &s.baseBillingAddress.lastName, FullNumber: &s.baseBillingAddress.phone, CardType: toPtr[models.CardType](models.CardType_VISA), - ExpirationMonth: interfacePtr(1), - ExpirationYear: interfacePtr(time.Now().Year() + 1), + ExpirationMonth: models.ToPointer(models.PaymentProfileAttributesExpirationMonthContainer.FromNumber(1)), + ExpirationYear: models.ToPointer(models.PaymentProfileAttributesExpirationYearContainer.FromNumber(time.Now().Year() + 1)), BillingAddress: &s.baseBillingAddress.address, BillingCity: &s.baseBillingAddress.city, BillingState: &s.baseBillingAddress.state, diff --git a/test/suite.go b/test/suite.go index 14fa5ac5..657c769e 100644 --- a/test/suite.go +++ b/test/suite.go @@ -3,11 +3,11 @@ package test import ( "context" "fmt" + "github.com/caarlos0/env/v10" "math/rand" "net/http" "time" - "github.com/caarlos0/env/v10" "github.com/jaswdr/faker" advancedbilling "github.com/maxio-com/ab-golang-sdk" "github.com/maxio-com/ab-golang-sdk/models" @@ -57,23 +57,23 @@ func (s *APISuite) SetupTest() { } config := advancedbilling.CreateConfiguration( - advancedbilling.WithBasicAuthCredentials( - advancedbilling.NewBasicAuthCredentials( - cfg.APIKey, - cfg.Password, - ), - ), + advancedbilling.WithBasicAuthCredentials( + advancedbilling.NewBasicAuthCredentials( + cfg.APIKey, + cfg.Password, + ), + ), advancedbilling.WithDomain(cfg.Domain), advancedbilling.WithSubdomain(cfg.Subdomain), ) configUnauthorized := advancedbilling.CreateConfiguration( - advancedbilling.WithBasicAuthCredentials( - advancedbilling.NewBasicAuthCredentials( - "abc", - "abc", - ), - ), + advancedbilling.WithBasicAuthCredentials( + advancedbilling.NewBasicAuthCredentials( + "abc", + "abc", + ), + ), advancedbilling.WithDomain(cfg.Domain), advancedbilling.WithSubdomain(cfg.Subdomain), ) @@ -153,22 +153,22 @@ func (s *APISuite) generateProduct(ctx context.Context, productFamilyID int) mod } func (s *APISuite) generateCoupon(ctx context.Context, productFamilyID int) models.Coupon { - coupon := &models.Coupon{ - Name: strPtr(s.fkr.RandomStringWithLength(20)), - Code: strPtr("100OFF" + s.fkr.RandomStringWithLength(30)), + coupon := &models.CreateOrUpdatePercentageCoupon{ + Name: s.fkr.RandomStringWithLength(20), + Code: "100OFF" + s.fkr.RandomStringWithLength(30), Description: strPtr(s.fkr.RandomStringWithLength(20)), - Percentage: models.NewOptional[string](strPtr("50")), + Percentage: models.CreateOrUpdatePercentageCouponPercentageContainer.FromString("50"), AllowNegativeBalance: boolPtr(false), Recurring: boolPtr(false), - EndDate: models.NewOptional(timePtr(time.Now().AddDate(1, 0, 0))), - ProductFamilyId: &productFamilyID, + EndDate: timePtr(time.Now().AddDate(1, 0, 0)), + ProductFamilyId: models.ToPointer(fmt.Sprint(productFamilyID)), Stackable: boolPtr(false), ExcludeMidPeriodAllocations: boolPtr(true), ApplyOnCancelAtEndOfPeriod: boolPtr(true), } resp, err := s.client.CouponsController().CreateCoupon(ctx, productFamilyID, &models.CreateOrUpdateCoupon{ - Coupon: interfacePtr(coupon), + Coupon: models.ToPointer(models.CreateOrUpdateCouponCouponContainer.FromCreateOrUpdatePercentageCoupon(*coupon)), }) s.NoError(err) @@ -189,8 +189,8 @@ func (s *APISuite) generateMeteredComponent(ctx context.Context, productFamilyID PricingScheme: models.PricingScheme_STAIRSTEP, Prices: []models.Price{ { - StartingQuantity: 1, - UnitPrice: 1, + StartingQuantity: models.PriceStartingQuantityContainer.FromNumber(1), + UnitPrice: models.PriceUnitPriceContainer.FromPrecision(1), }, }, }, @@ -226,8 +226,8 @@ func (s *APISuite) generateSubscription( LastName: &s.baseBillingAddress.lastName, FullNumber: &s.baseBillingAddress.phone, CardType: toPtr[models.CardType](models.CardType_VISA), - ExpirationMonth: interfacePtr(1), - ExpirationYear: interfacePtr(time.Now().Year() + 1), + ExpirationMonth: models.ToPointer(models.PaymentProfileAttributesExpirationMonthContainer.FromNumber(1)), + ExpirationYear: models.ToPointer(models.PaymentProfileAttributesExpirationYearContainer.FromNumber(time.Now().Year() + 1)), BillingAddress: &s.baseBillingAddress.address, BillingCity: &s.baseBillingAddress.city, BillingState: &s.baseBillingAddress.state, diff --git a/webhooks_controller.go b/webhooks_controller.go index 6ae7eb06..8b0bcc26 100644 --- a/webhooks_controller.go +++ b/webhooks_controller.go @@ -1,218 +1,232 @@ package advancedbilling import ( - "context" - "fmt" - "github.com/apimatic/go-core-runtime/https" - "github.com/apimatic/go-core-runtime/utilities" - "github.com/maxio-com/ab-golang-sdk/errors" - "github.com/maxio-com/ab-golang-sdk/models" + "context" + "fmt" + "github.com/apimatic/go-core-runtime/https" + "github.com/apimatic/go-core-runtime/utilities" + "github.com/maxio-com/ab-golang-sdk/errors" + "github.com/maxio-com/ab-golang-sdk/models" ) // WebhooksController represents a controller struct. type WebhooksController struct { - baseController + baseController } -// NewWebhooksController creates a new instance of WebhooksController. +// NewWebhooksController creates a new instance of WebhooksController. // It takes a baseController as a parameter and returns a pointer to the WebhooksController. func NewWebhooksController(baseController baseController) *WebhooksController { - webhooksController := WebhooksController{baseController: baseController} - return &webhooksController + webhooksController := WebhooksController{baseController: baseController} + return &webhooksController } -// ListWebhooks takes context, status, sinceDate, untilDate, page, perPage, order, subscription as parameters and -// returns an models.ApiResponse with []models.WebhookResponse data and -// an error if there was an issue with the request or response. -// ## Webhooks Intro -// The Webhooks API allows you to view a list of all webhooks and to selectively resend individual or groups of webhooks. Webhooks will be sent on endpoints specified by you. Endpoints can be added via API or Web UI. There is also an option to enable / disable webhooks via API request. -// We recommend that you review Chargify's webhook documentation located in our help site. The following resources will help guide you on how to use webhooks in Chargify, in addition to these webhook endpoints: -// + [Adding/editing new webhooks](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404448450317#configure-webhook-url) -// + [Webhooks introduction and delivery information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405568068365#webhooks-introduction-0-0) -// + [Main webhook overview](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405357509645-Webhooks-Reference#webhooks-reference-0-0) -// + [Available webhooks and payloads](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405357509645-Webhooks-Reference#events) -// ## List Webhooks for a Site +// ListWebhooksInput represents the input of the ListWebhooks endpoint. +type ListWebhooksInput struct { + // Webhooks with matching status would be returned. + Status *models.WebhookStatus + // Format YYYY-MM-DD. Returns Webhooks with the created_at date greater than or equal to the one specified. + SinceDate *string + // Format YYYY-MM-DD. Returns Webhooks with the created_at date less than or equal to the one specified. + UntilDate *string + // Result records are organized in pages. By default, the first page of results is displayed. The page parameter specifies a page number of results to fetch. You can start navigating through the pages to consume the results. You do this by passing in a page parameter. Retrieve the next page by adding ?page=2 to the query string. If there are no results to return, then an empty result set will be returned. + // Use in query `page=1`. + Page *int + // This parameter indicates how many records to fetch in each request. Default value is 20. The maximum allowed values is 200; any per_page value over 200 will be changed to 200. + // Use in query `per_page=200`. + PerPage *int + // The order in which the Webhooks are returned. + Order *models.WebhookOrder + // The Chargify id of a subscription you'd like to filter for + Subscription *int +} + +// ListWebhooks takes context, status, sinceDate, untilDate, page, perPage, order, subscription as parameters and +// returns an models.ApiResponse with []models.WebhookResponse data and +// an error if there was an issue with the request or response. +// ## Webhooks Intro +// The Webhooks API allows you to view a list of all webhooks and to selectively resend individual or groups of webhooks. Webhooks will be sent on endpoints specified by you. Endpoints can be added via API or Web UI. There is also an option to enable / disable webhooks via API request. +// We recommend that you review Chargify's webhook documentation located in our help site. The following resources will help guide you on how to use webhooks in Chargify, in addition to these webhook endpoints: +// + [Adding/editing new webhooks](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404448450317#configure-webhook-url) +// + [Webhooks introduction and delivery information](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405568068365#webhooks-introduction-0-0) +// + [Main webhook overview](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405357509645-Webhooks-Reference#webhooks-reference-0-0) +// + [Available webhooks and payloads](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405357509645-Webhooks-Reference#events) +// ## List Webhooks for a Site // This method allows you to fetch data about webhooks. You can pass query parameters if you want to filter webhooks. func (w *WebhooksController) ListWebhooks( - ctx context.Context, - status *models.WebhookStatus, - sinceDate *string, - untilDate *string, - page *int, - perPage *int, - order *models.WebhookOrder, - subscription *int) ( - models.ApiResponse[[]models.WebhookResponse], - error) { - req := w.prepareRequest(ctx, "GET", "/webhooks.json") - req.Authenticate(NewAuth("BasicAuth")) - if status != nil { - req.QueryParam("status", *status) - } - if sinceDate != nil { - req.QueryParam("since_date", *sinceDate) - } - if untilDate != nil { - req.QueryParam("until_date", *untilDate) - } - if page != nil { - req.QueryParam("page", *page) - } - if perPage != nil { - req.QueryParam("per_page", *perPage) - } - if order != nil { - req.QueryParam("order", *order) - } - if subscription != nil { - req.QueryParam("subscription", *subscription) - } - var result []models.WebhookResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.WebhookResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + input ListWebhooksInput) ( + models.ApiResponse[[]models.WebhookResponse], + error) { + req := w.prepareRequest(ctx, "GET", "/webhooks.json") + req.Authenticate(NewAuth("BasicAuth")) + if input.Status != nil { + req.QueryParam("status", *input.Status) + } + if input.SinceDate != nil { + req.QueryParam("since_date", *input.SinceDate) + } + if input.UntilDate != nil { + req.QueryParam("until_date", *input.UntilDate) + } + if input.Page != nil { + req.QueryParam("page", *input.Page) + } + if input.PerPage != nil { + req.QueryParam("per_page", *input.PerPage) + } + if input.Order != nil { + req.QueryParam("order", *input.Order) + } + if input.Subscription != nil { + req.QueryParam("subscription", *input.Subscription) + } + var result []models.WebhookResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.WebhookResponse](decoder) + return models.NewApiResponse(result, resp), err } -// EnableWebhooks takes context, body as parameters and -// returns an models.ApiResponse with models.EnableWebhooksResponse data and -// an error if there was an issue with the request or response. +// EnableWebhooks takes context, body as parameters and +// returns an models.ApiResponse with models.EnableWebhooksResponse data and +// an error if there was an issue with the request or response. // This method allows you to enable webhooks via API for your site func (w *WebhooksController) EnableWebhooks( - ctx context.Context, - body *models.EnableWebhooksRequest) ( - models.ApiResponse[models.EnableWebhooksResponse], - error) { - req := w.prepareRequest(ctx, "PUT", "/webhooks/settings.json") - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.EnableWebhooksResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.EnableWebhooksResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.EnableWebhooksRequest) ( + models.ApiResponse[models.EnableWebhooksResponse], + error) { + req := w.prepareRequest(ctx, "PUT", "/webhooks/settings.json") + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.EnableWebhooksResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.EnableWebhooksResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ReplayWebhooks takes context, body as parameters and -// returns an models.ApiResponse with models.ReplayWebhooksResponse data and -// an error if there was an issue with the request or response. -// Posting to the replay endpoint does not immediately resend the webhooks. They are added to a queue and will be sent as soon as possible, depending on available system resources. +// ReplayWebhooks takes context, body as parameters and +// returns an models.ApiResponse with models.ReplayWebhooksResponse data and +// an error if there was an issue with the request or response. +// Posting to the replay endpoint does not immediately resend the webhooks. They are added to a queue and will be sent as soon as possible, depending on available system resources. // You may submit an array of up to 1000 webhook IDs to replay in the request. func (w *WebhooksController) ReplayWebhooks( - ctx context.Context, - body *models.ReplayWebhooksRequest) ( - models.ApiResponse[models.ReplayWebhooksResponse], - error) { - req := w.prepareRequest(ctx, "POST", "/webhooks/replay.json") - req.Authenticate(NewAuth("BasicAuth")) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.ReplayWebhooksResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.ReplayWebhooksResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.ReplayWebhooksRequest) ( + models.ApiResponse[models.ReplayWebhooksResponse], + error) { + req := w.prepareRequest(ctx, "POST", "/webhooks/replay.json") + req.Authenticate(NewAuth("BasicAuth")) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.ReplayWebhooksResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.ReplayWebhooksResponse](decoder) + return models.NewApiResponse(result, resp), err } -// CreateEndpoint takes context, body as parameters and -// returns an models.ApiResponse with models.EndpointResponse data and -// an error if there was an issue with the request or response. -// The Chargify API allows you to create an endpoint and assign a list of webhooks subscriptions (events) to it. -// You can check available events here. +// CreateEndpoint takes context, body as parameters and +// returns an models.ApiResponse with models.EndpointResponse data and +// an error if there was an issue with the request or response. +// The Chargify API allows you to create an endpoint and assign a list of webhooks subscriptions (events) to it. +// You can check available events here. // [Event keys](https://maxio-chargify.zendesk.com/hc/en-us/articles/5405357509645-Webhooks-Reference#example-payloads) func (w *WebhooksController) CreateEndpoint( - ctx context.Context, - body *models.CreateOrUpdateEndpointRequest) ( - models.ApiResponse[models.EndpointResponse], - error) { - req := w.prepareRequest(ctx, "POST", "/endpoints.json") - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - var result models.EndpointResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.EndpointResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + body *models.CreateOrUpdateEndpointRequest) ( + models.ApiResponse[models.EndpointResponse], + error) { + req := w.prepareRequest(ctx, "POST", "/endpoints.json") + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + var result models.EndpointResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.EndpointResponse](decoder) + return models.NewApiResponse(result, resp), err } -// ListEndpoints takes context as parameters and -// returns an models.ApiResponse with []models.Endpoint data and -// an error if there was an issue with the request or response. +// ListEndpoints takes context as parameters and +// returns an models.ApiResponse with []models.Endpoint data and +// an error if there was an issue with the request or response. // This method returns created endpoints for site. func (w *WebhooksController) ListEndpoints(ctx context.Context) ( - models.ApiResponse[[]models.Endpoint], - error) { - req := w.prepareRequest(ctx, "GET", "/endpoints.json") - req.Authenticate(NewAuth("BasicAuth")) - var result []models.Endpoint - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[[]models.Endpoint](decoder) - return models.NewApiResponse(result, resp), err + models.ApiResponse[[]models.Endpoint], + error) { + req := w.prepareRequest(ctx, "GET", "/endpoints.json") + req.Authenticate(NewAuth("BasicAuth")) + var result []models.Endpoint + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[[]models.Endpoint](decoder) + return models.NewApiResponse(result, resp), err } -// UpdateEndpoint takes context, endpointId, body as parameters and -// returns an models.ApiResponse with models.EndpointResponse data and -// an error if there was an issue with the request or response. -// You can update an Endpoint via the API with a PUT request to the resource endpoint. -// You can change the `url` of your endpoint which consumes webhooks or list of `webhook_subscriptions`. -// Check available [Event keys](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404448450317-Webhooks#configure-webhook-url). -// Always send a complete list of events which you want subscribe/watch. -// Sending an PUT request for existing endpoint with empty list of `webhook_subscriptions` will end with unsubscribe from all events. +// UpdateEndpoint takes context, endpointId, body as parameters and +// returns an models.ApiResponse with models.EndpointResponse data and +// an error if there was an issue with the request or response. +// You can update an Endpoint via the API with a PUT request to the resource endpoint. +// You can change the `url` of your endpoint which consumes webhooks or list of `webhook_subscriptions`. +// Check available [Event keys](https://maxio-chargify.zendesk.com/hc/en-us/articles/5404448450317-Webhooks#configure-webhook-url). +// Always send a complete list of events which you want subscribe/watch. +// Sending an PUT request for existing endpoint with empty list of `webhook_subscriptions` will end with unsubscribe from all events. // If you want unsubscribe from specific event, just send a list of `webhook_subscriptions` without the specific event key. func (w *WebhooksController) UpdateEndpoint( - ctx context.Context, - endpointId int, - body *models.CreateOrUpdateEndpointRequest) ( - models.ApiResponse[models.EndpointResponse], - error) { - req := w.prepareRequest( - ctx, - "PUT", - fmt.Sprintf("/endpoints/%v.json", endpointId), - ) - req.Authenticate(NewAuth("BasicAuth")) - req.AppendErrors(map[string]https.ErrorBuilder[error]{ - "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, - "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, - }) - req.Header("Content-Type", "application/json") - if body != nil { - req.Json(*body) - } - - var result models.EndpointResponse - decoder, resp, err := req.CallAsJson() - if err != nil { - return models.NewApiResponse(result, resp), err - } - - result, err = utilities.DecodeResults[models.EndpointResponse](decoder) - return models.NewApiResponse(result, resp), err + ctx context.Context, + endpointId int, + body *models.CreateOrUpdateEndpointRequest) ( + models.ApiResponse[models.EndpointResponse], + error) { + req := w.prepareRequest( + ctx, + "PUT", + fmt.Sprintf("/endpoints/%v.json", endpointId), + ) + req.Authenticate(NewAuth("BasicAuth")) + req.AppendErrors(map[string]https.ErrorBuilder[error]{ + "404": {TemplatedMessage: "Not Found:'{$response.body}'"}, + "422": {TemplatedMessage: "HTTP Response Not OK. Status code: {$statusCode}. Response: '{$response.body}'.", Unmarshaller: errors.NewErrorListResponse}, + }) + req.Header("Content-Type", "application/json") + if body != nil { + req.Json(body) + } + + var result models.EndpointResponse + decoder, resp, err := req.CallAsJson() + if err != nil { + return models.NewApiResponse(result, resp), err + } + + result, err = utilities.DecodeResults[models.EndpointResponse](decoder) + return models.NewApiResponse(result, resp), err }