# 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, StrictFloat, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from zuora_sdk.models.expanded_contact import ExpandedContact
from typing import Optional, Set
from typing_extensions import Self

class ExpandedAccount(BaseModel):
    """
    ExpandedAccount
    """ # 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)

    id: Optional[StrictStr] = None
    created_by_id: Optional[StrictStr] = Field(default=None, alias="createdById")
    created_date: Optional[StrictStr] = Field(default=None, alias="createdDate")
    updated_by_id: Optional[StrictStr] = Field(default=None, alias="updatedById")
    updated_date: Optional[StrictStr] = Field(default=None, alias="updatedDate")
    account_number: Optional[StrictStr] = Field(default=None, alias="accountNumber")
    additional_email_addresses: Optional[StrictStr] = Field(default=None, alias="additionalEmailAddresses")
    allow_invoice_edit: Optional[StrictBool] = Field(default=None, alias="allowInvoiceEdit")
    auto_pay: Optional[StrictBool] = Field(default=None, alias="autoPay")
    balance: Optional[Union[StrictFloat, StrictInt]] = None
    batch: Optional[StrictStr] = None
    bcd_setting_option: Optional[StrictStr] = Field(default=None, alias="bcdSettingOption")
    bill_cycle_day: Optional[StrictInt] = Field(default=None, alias="billCycleDay")
    bill_to_id: Optional[StrictStr] = Field(default=None, alias="billToId")
    communication_profile_id: Optional[StrictStr] = Field(default=None, alias="communicationProfileId")
    credit_balance: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="creditBalance")
    crm_id: Optional[StrictStr] = Field(default=None, alias="crmId")
    currency: Optional[StrictStr] = None
    customer_service_rep_name: Optional[StrictStr] = Field(default=None, alias="customerServiceRepName")
    default_payment_method_id: Optional[StrictStr] = Field(default=None, alias="defaultPaymentMethodId")
    e_invoice_profile_id: Optional[StrictStr] = Field(default=None, alias="eInvoiceProfileId")
    invoice_delivery_prefs_email: Optional[StrictBool] = Field(default=None, alias="invoiceDeliveryPrefsEmail")
    invoice_delivery_prefs_print: Optional[StrictBool] = Field(default=None, alias="invoiceDeliveryPrefsPrint")
    invoice_template_id: Optional[StrictStr] = Field(default=None, alias="invoiceTemplateId")
    last_invoice_date: Optional[date] = Field(default=None, alias="lastInvoiceDate")
    last_metrics_update: Optional[StrictStr] = Field(default=None, alias="lastMetricsUpdate")
    name: Optional[StrictStr] = None
    notes: Optional[StrictStr] = None
    organization_id: Optional[StrictStr] = Field(default=None, alias="organizationId")
    parent_id: Optional[StrictStr] = Field(default=None, alias="parentId")
    partner_account: Optional[StrictBool] = Field(default=None, alias="partnerAccount")
    payment_method_cascading_consent: Optional[StrictBool] = Field(default=None, alias="paymentMethodCascadingConsent")
    purchase_order_number: Optional[StrictStr] = Field(default=None, alias="purchaseOrderNumber")
    sales_rep_name: Optional[StrictStr] = Field(default=None, alias="salesRepName")
    sequence_set_id: Optional[StrictStr] = Field(default=None, alias="sequenceSetId")
    ship_to_id: Optional[StrictStr] = Field(default=None, alias="shipToId")
    sold_to_id: Optional[StrictStr] = Field(default=None, alias="soldToId")
    status: Optional[StrictStr] = None
    tax_company_code: Optional[StrictStr] = Field(default=None, alias="taxCompanyCode")
    tax_exempt_certificate_id: Optional[StrictStr] = Field(default=None, alias="taxExemptCertificateID")
    tax_exempt_certificate_type: Optional[StrictStr] = Field(default=None, alias="taxExemptCertificateType")
    tax_exempt_description: Optional[StrictStr] = Field(default=None, alias="taxExemptDescription")
    tax_exempt_effective_date: Optional[date] = Field(default=None, alias="taxExemptEffectiveDate")
    tax_exempt_entity_use_code: Optional[StrictStr] = Field(default=None, alias="taxExemptEntityUseCode")
    tax_exempt_expiration_date: Optional[date] = Field(default=None, alias="taxExemptExpirationDate")
    tax_exempt_issuing_jurisdiction: Optional[StrictStr] = Field(default=None, alias="taxExemptIssuingJurisdiction")
    tax_exempt_status: Optional[StrictStr] = Field(default=None, alias="taxExemptStatus")
    total_invoice_balance: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="totalInvoiceBalance")
    unapplied_balance: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="unappliedBalance")
    v_atid: Optional[StrictStr] = Field(default=None, alias="vATId")
    mrr: Optional[Union[StrictFloat, StrictInt]] = None
    total_debit_memo_balance: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="totalDebitMemoBalance")
    unapplied_credit_memo_amount: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="unappliedCreditMemoAmount")
    credit_memo_template_id: Optional[StrictStr] = Field(default=None, alias="creditMemoTemplateId")
    debit_memo_template_id: Optional[StrictStr] = Field(default=None, alias="debitMemoTemplateId")
    payment_gateway: Optional[StrictStr] = Field(default=None, alias="paymentGateway")
    payment_term: Optional[StrictStr] = Field(default=None, alias="paymentTerm")
    bill_to: Optional[ExpandedContact] = Field(default=None, alias="billTo")
    sold_to: Optional[ExpandedContact] = Field(default=None, alias="soldTo")
    ship_to: Optional[ExpandedContact] = Field(default=None, alias="shipTo")
    default_payment_method: Optional[ExpandedPaymentMethod] = Field(default=None, alias="defaultPaymentMethod")
    subscriptions: Optional[List[ExpandedSubscription]] = None
    payments: Optional[List[ExpandedPayment]] = None
    refunds: Optional[List[ExpandedRefund]] = None
    credit_memos: Optional[List[ExpandedCreditMemo]] = Field(default=None, alias="creditMemos")
    debit_memos: Optional[List[ExpandedDebitMemo]] = Field(default=None, alias="debitMemos")
    invoices: Optional[List[ExpandedInvoice]] = None
    usages: Optional[List[ExpandedUsage]] = None
    payment_methods: Optional[List[ExpandedPaymentMethod]] = Field(default=None, alias="paymentMethods")
    additional_properties: Dict[str, Any] = {}
    __properties: ClassVar[List[str]] = ["id", "createdById", "createdDate", "updatedById", "updatedDate", "accountNumber", "additionalEmailAddresses", "allowInvoiceEdit", "autoPay", "balance", "batch", "bcdSettingOption", "billCycleDay", "billToId", "communicationProfileId", "creditBalance", "crmId", "currency", "customerServiceRepName", "defaultPaymentMethodId", "eInvoiceProfileId", "invoiceDeliveryPrefsEmail", "invoiceDeliveryPrefsPrint", "invoiceTemplateId", "lastInvoiceDate", "lastMetricsUpdate", "name", "notes", "organizationId", "parentId", "partnerAccount", "paymentMethodCascadingConsent", "purchaseOrderNumber", "salesRepName", "sequenceSetId", "shipToId", "soldToId", "status", "taxCompanyCode", "taxExemptCertificateID", "taxExemptCertificateType", "taxExemptDescription", "taxExemptEffectiveDate", "taxExemptEntityUseCode", "taxExemptExpirationDate", "taxExemptIssuingJurisdiction", "taxExemptStatus", "totalInvoiceBalance", "unappliedBalance", "vATId", "mrr", "totalDebitMemoBalance", "unappliedCreditMemoAmount", "creditMemoTemplateId", "debitMemoTemplateId", "paymentGateway", "paymentTerm", "billTo", "soldTo", "shipTo", "defaultPaymentMethod", "subscriptions", "payments", "refunds", "creditMemos", "debitMemos", "invoices", "usages", "paymentMethods"]

    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 ExpandedAccount 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 bill_to
        if self.bill_to:
            _dict['billTo'] = self.bill_to.to_dict()
        # override the default output from pydantic by calling `to_dict()` of sold_to
        if self.sold_to:
            _dict['soldTo'] = self.sold_to.to_dict()
        # override the default output from pydantic by calling `to_dict()` of ship_to
        if self.ship_to:
            _dict['shipTo'] = self.ship_to.to_dict()
        # override the default output from pydantic by calling `to_dict()` of default_payment_method
        if self.default_payment_method:
            _dict['defaultPaymentMethod'] = self.default_payment_method.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in subscriptions (list)
        _items = []
        if self.subscriptions:
            for _item_subscriptions in self.subscriptions:
                if _item_subscriptions:
                    _items.append(_item_subscriptions.to_dict())
            _dict['subscriptions'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in payments (list)
        _items = []
        if self.payments:
            for _item_payments in self.payments:
                if _item_payments:
                    _items.append(_item_payments.to_dict())
            _dict['payments'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in refunds (list)
        _items = []
        if self.refunds:
            for _item_refunds in self.refunds:
                if _item_refunds:
                    _items.append(_item_refunds.to_dict())
            _dict['refunds'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in credit_memos (list)
        _items = []
        if self.credit_memos:
            for _item_credit_memos in self.credit_memos:
                if _item_credit_memos:
                    _items.append(_item_credit_memos.to_dict())
            _dict['creditMemos'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in debit_memos (list)
        _items = []
        if self.debit_memos:
            for _item_debit_memos in self.debit_memos:
                if _item_debit_memos:
                    _items.append(_item_debit_memos.to_dict())
            _dict['debitMemos'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in invoices (list)
        _items = []
        if self.invoices:
            for _item_invoices in self.invoices:
                if _item_invoices:
                    _items.append(_item_invoices.to_dict())
            _dict['invoices'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in usages (list)
        _items = []
        if self.usages:
            for _item_usages in self.usages:
                if _item_usages:
                    _items.append(_item_usages.to_dict())
            _dict['usages'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in payment_methods (list)
        _items = []
        if self.payment_methods:
            for _item_payment_methods in self.payment_methods:
                if _item_payment_methods:
                    _items.append(_item_payment_methods.to_dict())
            _dict['paymentMethods'] = _items
        # puts key-value pairs in additional_properties in the top level
        if self.additional_properties is not None:
            for _key, _value in self.additional_properties.items():
                _dict[_key] = _value

        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of ExpandedAccount 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 {
            "id": obj.get("id"),
            "createdById": obj.get("createdById"),
            "createdDate": obj.get("createdDate"),
            "updatedById": obj.get("updatedById"),
            "updatedDate": obj.get("updatedDate"),
            "accountNumber": obj.get("accountNumber"),
            "additionalEmailAddresses": obj.get("additionalEmailAddresses"),
            "allowInvoiceEdit": obj.get("allowInvoiceEdit"),
            "autoPay": obj.get("autoPay"),
            "balance": obj.get("balance"),
            "batch": obj.get("batch"),
            "bcdSettingOption": obj.get("bcdSettingOption"),
            "billCycleDay": obj.get("billCycleDay"),
            "billToId": obj.get("billToId"),
            "communicationProfileId": obj.get("communicationProfileId"),
            "creditBalance": obj.get("creditBalance"),
            "crmId": obj.get("crmId"),
            "currency": obj.get("currency"),
            "customerServiceRepName": obj.get("customerServiceRepName"),
            "defaultPaymentMethodId": obj.get("defaultPaymentMethodId"),
            "eInvoiceProfileId": obj.get("eInvoiceProfileId"),
            "invoiceDeliveryPrefsEmail": obj.get("invoiceDeliveryPrefsEmail"),
            "invoiceDeliveryPrefsPrint": obj.get("invoiceDeliveryPrefsPrint"),
            "invoiceTemplateId": obj.get("invoiceTemplateId"),
            "lastInvoiceDate": obj.get("lastInvoiceDate"),
            "lastMetricsUpdate": obj.get("lastMetricsUpdate"),
            "name": obj.get("name"),
            "notes": obj.get("notes"),
            "organizationId": obj.get("organizationId"),
            "parentId": obj.get("parentId"),
            "partnerAccount": obj.get("partnerAccount"),
            "paymentMethodCascadingConsent": obj.get("paymentMethodCascadingConsent"),
            "purchaseOrderNumber": obj.get("purchaseOrderNumber"),
            "salesRepName": obj.get("salesRepName"),
            "sequenceSetId": obj.get("sequenceSetId"),
            "shipToId": obj.get("shipToId"),
            "soldToId": obj.get("soldToId"),
            "status": obj.get("status"),
            "taxCompanyCode": obj.get("taxCompanyCode"),
            "taxExemptCertificateID": obj.get("taxExemptCertificateID"),
            "taxExemptCertificateType": obj.get("taxExemptCertificateType"),
            "taxExemptDescription": obj.get("taxExemptDescription"),
            "taxExemptEffectiveDate": obj.get("taxExemptEffectiveDate"),
            "taxExemptEntityUseCode": obj.get("taxExemptEntityUseCode"),
            "taxExemptExpirationDate": obj.get("taxExemptExpirationDate"),
            "taxExemptIssuingJurisdiction": obj.get("taxExemptIssuingJurisdiction"),
            "taxExemptStatus": obj.get("taxExemptStatus"),
            "totalInvoiceBalance": obj.get("totalInvoiceBalance"),
            "unappliedBalance": obj.get("unappliedBalance"),
            "vATId": obj.get("vATId"),
            "mrr": obj.get("mrr"),
            "totalDebitMemoBalance": obj.get("totalDebitMemoBalance"),
            "unappliedCreditMemoAmount": obj.get("unappliedCreditMemoAmount"),
            "creditMemoTemplateId": obj.get("creditMemoTemplateId"),
            "debitMemoTemplateId": obj.get("debitMemoTemplateId"),
            "paymentGateway": obj.get("paymentGateway"),
            "paymentTerm": obj.get("paymentTerm"),
            "billTo": ExpandedContact.from_dict(obj["billTo"]) if obj.get("billTo") is not None else None,
            "soldTo": ExpandedContact.from_dict(obj["soldTo"]) if obj.get("soldTo") is not None else None,
            "shipTo": ExpandedContact.from_dict(obj["shipTo"]) if obj.get("shipTo") is not None else None,
            "defaultPaymentMethod": ExpandedPaymentMethod.from_dict(obj["defaultPaymentMethod"]) if obj.get("defaultPaymentMethod") is not None else None,
            "subscriptions": [ExpandedSubscription.from_dict(_item) for _item in obj["subscriptions"]] if obj.get("subscriptions") is not None else None,
            "payments": [ExpandedPayment.from_dict(_item) for _item in obj["payments"]] if obj.get("payments") is not None else None,
            "refunds": [ExpandedRefund.from_dict(_item) for _item in obj["refunds"]] if obj.get("refunds") is not None else None,
            "creditMemos": [ExpandedCreditMemo.from_dict(_item) for _item in obj["creditMemos"]] if obj.get("creditMemos") is not None else None,
            "debitMemos": [ExpandedDebitMemo.from_dict(_item) for _item in obj["debitMemos"]] if obj.get("debitMemos") is not None else None,
            "invoices": [ExpandedInvoice.from_dict(_item) for _item in obj["invoices"]] if obj.get("invoices") is not None else None,
            "usages": [ExpandedUsage.from_dict(_item) for _item in obj["usages"]] if obj.get("usages") is not None else None,
            "paymentMethods": [ExpandedPaymentMethod.from_dict(_item) for _item in obj["paymentMethods"]] if obj.get("paymentMethods") is not None else None
        }
        return _obj
from zuora_sdk.models.expanded_credit_memo import ExpandedCreditMemo
from zuora_sdk.models.expanded_debit_memo import ExpandedDebitMemo
from zuora_sdk.models.expanded_invoice import ExpandedInvoice
from zuora_sdk.models.expanded_payment import ExpandedPayment
from zuora_sdk.models.expanded_payment_method import ExpandedPaymentMethod
from zuora_sdk.models.expanded_refund import ExpandedRefund
from zuora_sdk.models.expanded_subscription import ExpandedSubscription
from zuora_sdk.models.expanded_usage import ExpandedUsage
# TODO: Rewrite to not use raise_errors
ExpandedAccount.model_rebuild(raise_errors=False)


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:])
