# coding: utf-8

"""
    Zuora API Reference

    REST API reference for the Zuora Billing, Payments, and Central Platform! Check out the [REST API Overview](https://www.zuora.com/developer/api-references/api/overview/).

    The version of the OpenAPI document: 2024-05-20
    Contact: docs@zuora.com
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from datetime import date
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from zuora_sdk.models.billing_document_status import BillingDocumentStatus
from zuora_sdk.models.create_account_contact import CreateAccountContact
from zuora_sdk.models.create_invoice_item import CreateInvoiceItem
from zuora_sdk.models.custom_rates import CustomRates
from zuora_sdk.models.transferred_to_accounting_status import TransferredToAccountingStatus
from typing import Optional, Set
from typing_extensions import Self

class CreateInvoiceRequest(BaseModel):
    """
    CreateInvoiceRequest
    """ # noqa: E501
    # avoid validation
    def __init__(self, **kwargs):
        # Directly assign values without validation using `construct()`
        model = self.construct(**kwargs)
        self.__dict__.update(model.__dict__)

        _dict_all = convert_snake_dict_to_camel(kwargs, self.model_fields, self.__properties)

        _dict = self.to_alias_dict(_dict_all)
        for field_name, field_info in self.model_fields.items():
            alias = field_info.alias or field_name
            if alias in _dict:
                self.__dict__[field_name] = _dict.get(alias)
        self.update_additional_properties(self, _dict_all)
        pass

    def __setattr__(self, name, value):
        # Override setattr to bypass validation when setting attributes
        object.__setattr__(self, name, value)

    integration_id__ns: Optional[Annotated[str, Field(strict=True, max_length=255)]] = Field(default=None, description="ID of the corresponding object in NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). ", alias="IntegrationId__NS")
    integration_status__ns: Optional[Annotated[str, Field(strict=True, max_length=255)]] = Field(default=None, description="Status of the invoice's synchronization with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). ", alias="IntegrationStatus__NS")
    sync_date__ns: Optional[Annotated[str, Field(strict=True, max_length=255)]] = Field(default=None, description="Date when the invoice was synchronized with NetSuite. Only available if you have installed the [Zuora Connector for NetSuite](https://www.zuora.com/connect/app/?appId=265). ", alias="SyncDate__NS")
    account_id: Optional[StrictStr] = Field(default=None, description="The ID of the account associated with the invoice.   You must specify either `accountNumber` or `accountId` for a customer account. If both of them are specified, they must refer to the same customer account. ", alias="accountId")
    account_number: Optional[StrictStr] = Field(default=None, description="The Number of the account associated with the invoice. You must specify either `accountNumber` or `accountId` for a customer account. If both of them are specified, they must refer to the same customer account.", alias="accountNumber")
    auto_pay: Optional[StrictBool] = Field(default=False, description="Whether invoices are automatically picked up for processing in the corresponding payment run.", alias="autoPay")
    comments: Optional[StrictStr] = Field(default=None, description="Comments about the invoice.")
    custom_rates: Optional[Annotated[List[CustomRates], Field(max_length=2)]] = Field(default=None, description="It contains Home currency and Reporting currency custom rates currencies. The maximum number of items is 2 (you can pass the Home currency item or Reporting currency item or both).        **Note**: The API custom rate feature is permission controlled. ", alias="customRates")
    due_date: Optional[date] = Field(default=None, description="The date by which the payment for this invoice is due, in `yyyy-mm-dd` format. ", alias="dueDate")
    invoice_date: date = Field(description="The date that appears on the invoice being created, in `yyyy-mm-dd` format. The value cannot fall in a closed accounting period.", alias="invoiceDate")
    invoice_items: List[CreateInvoiceItem] = Field(description="Container for invoice items. The maximum number of invoice items is 1,000.", alias="invoiceItems")
    invoice_number: Optional[StrictStr] = Field(default=None, description="A customized invoice number with the following format requirements: - Max length: 32 characters - Acceptable characters: a-z,A-Z,0-9,-,_,  The value must be unique in the system, otherwise it may cause issues with bill runs and subscribe/amend. Check out [things to note and troubleshooting steps](https://knowledgecenter.zuora.com/Billing/Billing_and_Payments/IA_Invoices/Unified_Invoicing/Import_external_invoices_as_standalone_invoices?#Customizing_invoice_number).  ", alias="invoiceNumber")
    status: Optional[StrictStr] = None
    bill_to_contact_id: Optional[StrictStr] = Field(default=None, description="The ID of the bill-to contact associated with the invoice.", alias="billToContactId")
    payment_term: Optional[StrictStr] = Field(default=None, description="The name of payment term associated with the invoice.", alias="paymentTerm")
    sequence_set: Optional[StrictStr] = Field(default=None, description="The ID or name of the sequence set associated with the invoice.", alias="sequenceSet")
    sold_to_contact_id: Optional[StrictStr] = Field(default=None, description="The ID of the sold-to contact associated with the invoice.", alias="soldToContactId")
    bill_to_contact: Optional[CreateAccountContact] = Field(default=None, alias="billToContact")
    sold_to_contact: Optional[CreateAccountContact] = Field(default=None, alias="soldToContact")
    sold_to_same_as_bill_to: Optional[StrictBool] = Field(default=None, description="Whether the sold-to contact and bill-to contact are the same entity.  The created invoice has the same bill-to contact and sold-to contact entity only when all the following conditions are met in the request body: - This field is set to `true`.  - A bill-to contact is specified. - No sold-to contact is specified. ", alias="soldToSameAsBillTo")
    template_id: Optional[StrictStr] = Field(default=None, description="The ID of the invoice template. **Note**: This field requires Flexible Billing Attribute.", alias="templateId")
    transferred_to_accounting: Optional[StrictStr] = Field(default=None, alias="transferredToAccounting")
    ship_to_contact_id: Optional[StrictStr] = Field(default=None, description="The ID of the ship-to contact associated with the invoice.", alias="shipToContactId")
    ship_to_contact: Optional[CreateAccountContact] = Field(default=None, alias="shipToContact")
    ship_to_same_as_bill_to: Optional[StrictBool] = Field(default=None, description="Whether the ship-to contact and bill-to contact are the same entity.  The created invoice has the same bill-to contact and ship-to contact entity only when all the following conditions are met in the request body: - This field is set to `true`.  - A bill-to contact is specified. - No ship-to contact is specified. ", alias="shipToSameAsBillTo")
    additional_properties: Dict[str, Any] = {}
    __properties: ClassVar[List[str]] = ["IntegrationId__NS", "IntegrationStatus__NS", "SyncDate__NS", "accountId", "accountNumber", "autoPay", "comments", "customRates", "dueDate", "invoiceDate", "invoiceItems", "invoiceNumber", "status", "billToContactId", "paymentTerm", "sequenceSet", "soldToContactId", "billToContact", "soldToContact", "soldToSameAsBillTo", "templateId", "transferredToAccounting", "shipToContactId", "shipToContact", "shipToSameAsBillTo"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of CreateInvoiceRequest from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        * Fields in `self.additional_properties` are added to the output dict.
        """
        excluded_fields: Set[str] = set([
            "additional_properties",
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of each item in custom_rates (list)
        _items = []
        if self.custom_rates:
            for _item_custom_rates in self.custom_rates:
                if _item_custom_rates:
                    _items.append(_item_custom_rates.to_dict())
            _dict['customRates'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in invoice_items (list)
        _items = []
        if self.invoice_items:
            for _item_invoice_items in self.invoice_items:
                if _item_invoice_items:
                    _items.append(_item_invoice_items.to_dict())
            _dict['invoiceItems'] = _items
        # override the default output from pydantic by calling `to_dict()` of bill_to_contact
        if self.bill_to_contact:
            _dict['billToContact'] = self.bill_to_contact.to_dict()
        # override the default output from pydantic by calling `to_dict()` of sold_to_contact
        if self.sold_to_contact:
            _dict['soldToContact'] = self.sold_to_contact.to_dict()
        # override the default output from pydantic by calling `to_dict()` of ship_to_contact
        if self.ship_to_contact:
            _dict['shipToContact'] = self.ship_to_contact.to_dict()
        # puts key-value pairs in additional_properties in the top level
        if self.additional_properties is not None:
            for _key, _value in self.additional_properties.items():
                _dict[_key] = _value

        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of CreateInvoiceRequest from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        obj = convert_snake_dict_to_camel(obj, cls.model_fields, cls.__properties)

        _obj = cls.model_validate(cls.to_alias_dict(obj))
        return cls.update_additional_properties(_obj, obj)

    @classmethod
    def update_additional_properties(cls, obj, _dict: Optional[Dict[str, Any]]):
        # store additional fields in additional_properties

        # store additional fields in additional_properties
        for _key in _dict.keys():
            if _key not in cls.__properties:
                obj.additional_properties[_key] = _dict.get(_key)


        return obj
        pass

    @classmethod
    def to_alias_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        return {
            "IntegrationId__NS": obj.get("IntegrationId__NS"),
            "IntegrationStatus__NS": obj.get("IntegrationStatus__NS"),
            "SyncDate__NS": obj.get("SyncDate__NS"),
            "accountId": obj.get("accountId"),
            "accountNumber": obj.get("accountNumber"),
            "autoPay": obj.get("autoPay") if obj.get("autoPay") is not None else False,
            "comments": obj.get("comments"),
            "customRates": [CustomRates.from_dict(_item) for _item in obj["customRates"]] if obj.get("customRates") is not None else None,
            "dueDate": obj.get("dueDate"),
            "invoiceDate": obj.get("invoiceDate"),
            "invoiceItems": [CreateInvoiceItem.from_dict(_item) for _item in obj["invoiceItems"]] if obj.get("invoiceItems") is not None else None,
            "invoiceNumber": obj.get("invoiceNumber"),
            "status": obj.get("status"),
            "billToContactId": obj.get("billToContactId"),
            "paymentTerm": obj.get("paymentTerm"),
            "sequenceSet": obj.get("sequenceSet"),
            "soldToContactId": obj.get("soldToContactId"),
            "billToContact": CreateAccountContact.from_dict(obj["billToContact"]) if obj.get("billToContact") is not None else None,
            "soldToContact": CreateAccountContact.from_dict(obj["soldToContact"]) if obj.get("soldToContact") is not None else None,
            "soldToSameAsBillTo": obj.get("soldToSameAsBillTo"),
            "templateId": obj.get("templateId"),
            "transferredToAccounting": obj.get("transferredToAccounting"),
            "shipToContactId": obj.get("shipToContactId"),
            "shipToContact": CreateAccountContact.from_dict(obj["shipToContact"]) if obj.get("shipToContact") is not None else None,
            "shipToSameAsBillTo": obj.get("shipToSameAsBillTo")
        }
        return _obj


def convert_snake_dict_to_camel(_dict: dict, model_fields, properties):
    if not isinstance(_dict, dict):
        return _dict
    new_dict = {}
    for k, v in _dict.items():
        if k in model_fields:
            # model_fields: key is attribute name like bill_to_contact,
            alias = model_fields.get(k).alias or k
            new_dict[alias] = v
            pass
        else:
            new_key = snake_to_camel(k)
            if properties is not None and isinstance(properties, list) and new_key in properties:
                new_dict[new_key] = v
            else:
                new_dict[k] = v
    return new_dict
    pass


def snake_to_camel(name):
    if name is None or '_' not in name:
        return name
    components = name.split('_')
    return components[0] + ''.join(x.title() for x in components[1:])
