# 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_taxation_item import ExpandedTaxationItem
from typing import Optional, Set
from typing_extensions import Self

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

    invoice_id: Optional[StrictStr] = Field(default=None, alias="invoiceId")
    invoice_schedule_id: Optional[StrictStr] = Field(default=None, alias="invoiceScheduleId")
    invoice_schedule_item_id: Optional[StrictStr] = Field(default=None, alias="invoiceScheduleItemId")
    rate_plan_charge_id: Optional[StrictStr] = Field(default=None, alias="ratePlanChargeId")
    product_rate_plan_charge_id: Optional[StrictStr] = Field(default=None, alias="productRatePlanChargeId")
    accounting_code: Optional[StrictStr] = Field(default=None, alias="accountingCode")
    applied_to_invoice_item_id: Optional[StrictStr] = Field(default=None, alias="appliedToInvoiceItemId")
    charge_amount: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="chargeAmount")
    charge_date: Optional[StrictStr] = Field(default=None, alias="chargeDate")
    charge_name: Optional[StrictStr] = Field(default=None, alias="chargeName")
    charge_number: Optional[StrictStr] = Field(default=None, alias="chargeNumber")
    commitment_charge_number: Optional[StrictStr] = Field(default=None, alias="commitmentChargeNumber")
    commitment_charge_segment_number: Optional[StrictStr] = Field(default=None, alias="commitmentChargeSegmentNumber")
    description: Optional[StrictStr] = None
    discount_amount: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="discountAmount")
    exclude_item_billing_from_revenue_accounting: Optional[StrictBool] = Field(default=None, alias="excludeItemBillingFromRevenueAccounting")
    fulfillment_id: Optional[StrictStr] = Field(default=None, alias="fulfillmentId")
    item_ship_to_contact_id: Optional[StrictStr] = Field(default=None, alias="itemShipToContactId")
    item_sold_to_contact_id: Optional[StrictStr] = Field(default=None, alias="itemSoldToContactId")
    item_sold_to_contact_snapshot_id: Optional[StrictStr] = Field(default=None, alias="itemSoldToContactSnapshotId")
    processing_type: Optional[StrictStr] = Field(default=None, alias="processingType")
    quantity: Optional[Union[StrictFloat, StrictInt]] = None
    reflect_discount_in_net_amount: Optional[StrictBool] = Field(default=None, alias="reflectDiscountInNetAmount")
    rev_rec_start_date: Optional[date] = Field(default=None, alias="revRecStartDate")
    service_end_date: Optional[date] = Field(default=None, alias="serviceEndDate")
    service_start_date: Optional[date] = Field(default=None, alias="serviceStartDate")
    s_ku: Optional[StrictStr] = Field(default=None, alias="sKU")
    source_item_type: Optional[StrictStr] = Field(default=None, alias="sourceItemType")
    order_line_item_id: Optional[StrictStr] = Field(default=None, alias="orderLineItemId")
    subscription_id: Optional[StrictStr] = Field(default=None, alias="subscriptionId")
    subscription_number: Optional[StrictStr] = Field(default=None, alias="subscriptionNumber")
    tax_amount: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="taxAmount")
    tax_code: Optional[StrictStr] = Field(default=None, alias="taxCode")
    tax_exempt_amount: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="taxExemptAmount")
    tax_mode: Optional[StrictStr] = Field(default=None, alias="taxMode")
    unit_price: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="unitPrice")
    u_om: Optional[StrictStr] = Field(default=None, alias="uOM")
    balance: Optional[Union[StrictFloat, StrictInt]] = None
    number_of_deliveries: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="numberOfDeliveries")
    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_receivable_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="accountReceivableAccountingCodeId")
    recognized_revenue_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="recognizedRevenueAccountingCodeId")
    deferred_revenue_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="deferredRevenueAccountingCodeId")
    contract_asset_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="contractAssetAccountingCodeId")
    contract_liability_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="contractLiabilityAccountingCodeId")
    contract_recognized_revenue_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="contractRecognizedRevenueAccountingCodeId")
    unbilled_receivables_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="unbilledReceivablesAccountingCodeId")
    adjustment_revenue_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="adjustmentRevenueAccountingCodeId")
    adjustment_liability_accounting_code_id: Optional[StrictStr] = Field(default=None, alias="adjustmentLiabilityAccountingCodeId")
    journal_entry_id: Optional[StrictStr] = Field(default=None, alias="journalEntryId")
    account_id: Optional[StrictStr] = Field(default=None, alias="accountId")
    bill_to_contact_snapshot_id: Optional[StrictStr] = Field(default=None, alias="billToContactSnapshotId")
    sold_to_contact_snapshot_id: Optional[StrictStr] = Field(default=None, alias="soldToContactSnapshotId")
    ship_to_contact_snapshot_id: Optional[StrictStr] = Field(default=None, alias="shipToContactSnapshotId")
    parent_account_id: Optional[StrictStr] = Field(default=None, alias="parentAccountId")
    bill_to_contact_id: Optional[StrictStr] = Field(default=None, alias="billToContactId")
    sold_to_contact_id: Optional[StrictStr] = Field(default=None, alias="soldToContactId")
    ship_to_contact_id: Optional[StrictStr] = Field(default=None, alias="shipToContactId")
    default_payment_method_id: Optional[StrictStr] = Field(default=None, alias="defaultPaymentMethodId")
    rate_plan_id: Optional[StrictStr] = Field(default=None, alias="ratePlanId")
    amendment_id: Optional[StrictStr] = Field(default=None, alias="amendmentId")
    product_rate_plan_id: Optional[StrictStr] = Field(default=None, alias="productRatePlanId")
    product_id: Optional[StrictStr] = Field(default=None, alias="productId")
    subscription_owner_id: Optional[StrictStr] = Field(default=None, alias="subscriptionOwnerId")
    booking_reference: Optional[StrictStr] = Field(default=None, alias="bookingReference")
    item_type: Optional[StrictStr] = Field(default=None, alias="itemType")
    purchase_order_number: Optional[StrictStr] = Field(default=None, alias="purchaseOrderNumber")
    rev_rec_code: Optional[StrictStr] = Field(default=None, alias="revRecCode")
    rev_rec_trigger_condition: Optional[StrictStr] = Field(default=None, alias="revRecTriggerCondition")
    revenue_recognition_rule_name: Optional[StrictStr] = Field(default=None, alias="revenueRecognitionRuleName")
    invoice: Optional[ExpandedInvoice] = None
    subscription: Optional[ExpandedSubscription] = None
    subscription_owner: Optional[ExpandedAccount] = Field(default=None, alias="subscriptionOwner")
    taxation_items: Optional[List[ExpandedTaxationItem]] = Field(default=None, alias="taxationItems")
    rate_plan_charge: Optional[ExpandedRatePlanCharge] = Field(default=None, alias="ratePlanCharge")
    order_line_item: Optional[ExpandedOrderLineItem] = Field(default=None, alias="orderLineItem")
    additional_properties: Dict[str, Any] = {}
    __properties: ClassVar[List[str]] = ["invoiceId", "invoiceScheduleId", "invoiceScheduleItemId", "ratePlanChargeId", "productRatePlanChargeId", "accountingCode", "appliedToInvoiceItemId", "chargeAmount", "chargeDate", "chargeName", "chargeNumber", "commitmentChargeNumber", "commitmentChargeSegmentNumber", "description", "discountAmount", "excludeItemBillingFromRevenueAccounting", "fulfillmentId", "itemShipToContactId", "itemSoldToContactId", "itemSoldToContactSnapshotId", "processingType", "quantity", "reflectDiscountInNetAmount", "revRecStartDate", "serviceEndDate", "serviceStartDate", "sKU", "sourceItemType", "orderLineItemId", "subscriptionId", "subscriptionNumber", "taxAmount", "taxCode", "taxExemptAmount", "taxMode", "unitPrice", "uOM", "balance", "numberOfDeliveries", "id", "createdById", "createdDate", "updatedById", "updatedDate", "accountReceivableAccountingCodeId", "recognizedRevenueAccountingCodeId", "deferredRevenueAccountingCodeId", "contractAssetAccountingCodeId", "contractLiabilityAccountingCodeId", "contractRecognizedRevenueAccountingCodeId", "unbilledReceivablesAccountingCodeId", "adjustmentRevenueAccountingCodeId", "adjustmentLiabilityAccountingCodeId", "journalEntryId", "accountId", "billToContactSnapshotId", "soldToContactSnapshotId", "shipToContactSnapshotId", "parentAccountId", "billToContactId", "soldToContactId", "shipToContactId", "defaultPaymentMethodId", "ratePlanId", "amendmentId", "productRatePlanId", "productId", "subscriptionOwnerId", "bookingReference", "itemType", "purchaseOrderNumber", "revRecCode", "revRecTriggerCondition", "revenueRecognitionRuleName", "invoice", "subscription", "subscriptionOwner", "taxationItems", "ratePlanCharge", "orderLineItem"]

    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 ExpandedInvoiceItem 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 invoice
        if self.invoice:
            _dict['invoice'] = self.invoice.to_dict()
        # override the default output from pydantic by calling `to_dict()` of subscription
        if self.subscription:
            _dict['subscription'] = self.subscription.to_dict()
        # override the default output from pydantic by calling `to_dict()` of subscription_owner
        if self.subscription_owner:
            _dict['subscriptionOwner'] = self.subscription_owner.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in taxation_items (list)
        _items = []
        if self.taxation_items:
            for _item_taxation_items in self.taxation_items:
                if _item_taxation_items:
                    _items.append(_item_taxation_items.to_dict())
            _dict['taxationItems'] = _items
        # override the default output from pydantic by calling `to_dict()` of rate_plan_charge
        if self.rate_plan_charge:
            _dict['ratePlanCharge'] = self.rate_plan_charge.to_dict()
        # override the default output from pydantic by calling `to_dict()` of order_line_item
        if self.order_line_item:
            _dict['orderLineItem'] = self.order_line_item.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 ExpandedInvoiceItem 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 {
            "invoiceId": obj.get("invoiceId"),
            "invoiceScheduleId": obj.get("invoiceScheduleId"),
            "invoiceScheduleItemId": obj.get("invoiceScheduleItemId"),
            "ratePlanChargeId": obj.get("ratePlanChargeId"),
            "productRatePlanChargeId": obj.get("productRatePlanChargeId"),
            "accountingCode": obj.get("accountingCode"),
            "appliedToInvoiceItemId": obj.get("appliedToInvoiceItemId"),
            "chargeAmount": obj.get("chargeAmount"),
            "chargeDate": obj.get("chargeDate"),
            "chargeName": obj.get("chargeName"),
            "chargeNumber": obj.get("chargeNumber"),
            "commitmentChargeNumber": obj.get("commitmentChargeNumber"),
            "commitmentChargeSegmentNumber": obj.get("commitmentChargeSegmentNumber"),
            "description": obj.get("description"),
            "discountAmount": obj.get("discountAmount"),
            "excludeItemBillingFromRevenueAccounting": obj.get("excludeItemBillingFromRevenueAccounting"),
            "fulfillmentId": obj.get("fulfillmentId"),
            "itemShipToContactId": obj.get("itemShipToContactId"),
            "itemSoldToContactId": obj.get("itemSoldToContactId"),
            "itemSoldToContactSnapshotId": obj.get("itemSoldToContactSnapshotId"),
            "processingType": obj.get("processingType"),
            "quantity": obj.get("quantity"),
            "reflectDiscountInNetAmount": obj.get("reflectDiscountInNetAmount"),
            "revRecStartDate": obj.get("revRecStartDate"),
            "serviceEndDate": obj.get("serviceEndDate"),
            "serviceStartDate": obj.get("serviceStartDate"),
            "sKU": obj.get("sKU"),
            "sourceItemType": obj.get("sourceItemType"),
            "orderLineItemId": obj.get("orderLineItemId"),
            "subscriptionId": obj.get("subscriptionId"),
            "subscriptionNumber": obj.get("subscriptionNumber"),
            "taxAmount": obj.get("taxAmount"),
            "taxCode": obj.get("taxCode"),
            "taxExemptAmount": obj.get("taxExemptAmount"),
            "taxMode": obj.get("taxMode"),
            "unitPrice": obj.get("unitPrice"),
            "uOM": obj.get("uOM"),
            "balance": obj.get("balance"),
            "numberOfDeliveries": obj.get("numberOfDeliveries"),
            "id": obj.get("id"),
            "createdById": obj.get("createdById"),
            "createdDate": obj.get("createdDate"),
            "updatedById": obj.get("updatedById"),
            "updatedDate": obj.get("updatedDate"),
            "accountReceivableAccountingCodeId": obj.get("accountReceivableAccountingCodeId"),
            "recognizedRevenueAccountingCodeId": obj.get("recognizedRevenueAccountingCodeId"),
            "deferredRevenueAccountingCodeId": obj.get("deferredRevenueAccountingCodeId"),
            "contractAssetAccountingCodeId": obj.get("contractAssetAccountingCodeId"),
            "contractLiabilityAccountingCodeId": obj.get("contractLiabilityAccountingCodeId"),
            "contractRecognizedRevenueAccountingCodeId": obj.get("contractRecognizedRevenueAccountingCodeId"),
            "unbilledReceivablesAccountingCodeId": obj.get("unbilledReceivablesAccountingCodeId"),
            "adjustmentRevenueAccountingCodeId": obj.get("adjustmentRevenueAccountingCodeId"),
            "adjustmentLiabilityAccountingCodeId": obj.get("adjustmentLiabilityAccountingCodeId"),
            "journalEntryId": obj.get("journalEntryId"),
            "accountId": obj.get("accountId"),
            "billToContactSnapshotId": obj.get("billToContactSnapshotId"),
            "soldToContactSnapshotId": obj.get("soldToContactSnapshotId"),
            "shipToContactSnapshotId": obj.get("shipToContactSnapshotId"),
            "parentAccountId": obj.get("parentAccountId"),
            "billToContactId": obj.get("billToContactId"),
            "soldToContactId": obj.get("soldToContactId"),
            "shipToContactId": obj.get("shipToContactId"),
            "defaultPaymentMethodId": obj.get("defaultPaymentMethodId"),
            "ratePlanId": obj.get("ratePlanId"),
            "amendmentId": obj.get("amendmentId"),
            "productRatePlanId": obj.get("productRatePlanId"),
            "productId": obj.get("productId"),
            "subscriptionOwnerId": obj.get("subscriptionOwnerId"),
            "bookingReference": obj.get("bookingReference"),
            "itemType": obj.get("itemType"),
            "purchaseOrderNumber": obj.get("purchaseOrderNumber"),
            "revRecCode": obj.get("revRecCode"),
            "revRecTriggerCondition": obj.get("revRecTriggerCondition"),
            "revenueRecognitionRuleName": obj.get("revenueRecognitionRuleName"),
            "invoice": ExpandedInvoice.from_dict(obj["invoice"]) if obj.get("invoice") is not None else None,
            "subscription": ExpandedSubscription.from_dict(obj["subscription"]) if obj.get("subscription") is not None else None,
            "subscriptionOwner": ExpandedAccount.from_dict(obj["subscriptionOwner"]) if obj.get("subscriptionOwner") is not None else None,
            "taxationItems": [ExpandedTaxationItem.from_dict(_item) for _item in obj["taxationItems"]] if obj.get("taxationItems") is not None else None,
            "ratePlanCharge": ExpandedRatePlanCharge.from_dict(obj["ratePlanCharge"]) if obj.get("ratePlanCharge") is not None else None,
            "orderLineItem": ExpandedOrderLineItem.from_dict(obj["orderLineItem"]) if obj.get("orderLineItem") is not None else None
        }
        return _obj
from zuora_sdk.models.expanded_account import ExpandedAccount
from zuora_sdk.models.expanded_invoice import ExpandedInvoice
from zuora_sdk.models.expanded_order_line_item import ExpandedOrderLineItem
from zuora_sdk.models.expanded_rate_plan_charge import ExpandedRatePlanCharge
from zuora_sdk.models.expanded_subscription import ExpandedSubscription
# TODO: Rewrite to not use raise_errors
ExpandedInvoiceItem.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:])
