Skip to content

Commit

Permalink
Refactor model construction from results.
Browse files Browse the repository at this point in the history
* move sub type & dependent type declarations to the model classes
* dependent_sub_types moves to the sub type classes themselves
* simplify construct/init_* methods
  • Loading branch information
rcoup committed May 24, 2019
1 parent c4dda08 commit 8a1e4b5
Show file tree
Hide file tree
Showing 21 changed files with 306 additions and 98 deletions.
37 changes: 13 additions & 24 deletions chargebee/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,11 @@
class Model(object):
fields = [] # field list
repr_field = None # field to use for repr(), default is fields[0]
sub_types = {} # mapping {attr: type}
dependant_types = {} # mapping {attr: type}. If type is a 1-tuple, indicates it's a list.

def __init__(self, values, sub_types=None, dependant_types=None):
if sub_types is None:
sub_types = {}
if dependant_types is None:
dependant_types = {}

def __init__(self, values):
self.values = values
self.sub_types = sub_types
self.dependant_types = dependant_types
for field in self.fields:
setattr(self, field, None)

Expand Down Expand Up @@ -49,21 +44,15 @@ def __getattr__(self, name):
raise AttributeError("Attribute %s not found " % name)

@classmethod
def construct(cls, values, sub_types=None, dependant_types=None):
obj = cls(values, sub_types, dependant_types)
def construct(cls, values):
obj = cls(values)
obj.load(values)
for k, dependent_type in cls.dependant_types.items():
if values.get(k) is not None:
if isinstance(dependent_type, tuple):
# dependent type being a 1-tuple indicates a list
set_val = [dependent_type[0].construct(v) for v in values[k]]
else:
set_val = dependent_type.construct(values[k])
setattr(obj, k, set_val)
return obj

def init_dependant(self, obj, type, sub_types={}):
if obj.get(type) != None:
if isinstance(obj, dict) and type in self.dependant_types:
dependant_obj = self.dependant_types[type].construct(obj[type], sub_types)
setattr(self, type, dependant_obj)

def init_dependant_list(self, obj, type, sub_types={}):
if obj.get(type) != None:
if isinstance(obj[type],(list, tuple)) and type in self.dependant_types:
if(self.dependant_types != None):
set_val = [self.dependant_types[type].construct(dt, sub_types) for dt in obj[type]]
setattr(self, type, set_val)

3 changes: 3 additions & 0 deletions chargebee/models/addon.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ class Tier(Model):
"shipping_frequency_period_unit", "resource_version", "updated_at", "invoice_notes", "taxable", \
"tax_profile_id", "meta_data", "tiers"]

sub_types = {
'tiers' : Tier,
}

@staticmethod
def create(params, env=None, headers=None):
Expand Down
11 changes: 11 additions & 0 deletions chargebee/models/credit_note.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@ class Allocation(Model):
"sub_total", "round_off_amount", "line_items", "discounts", "line_item_discounts", "line_item_tiers", \
"taxes", "line_item_taxes", "linked_refunds", "allocations", "deleted"]

sub_types = {
'line_items': LineItem,
'discounts': Discount,
'line_item_discounts': LineItemDiscount,
'line_item_tiers' : LineItemTier,
'taxes': Tax,
'line_item_taxes': LineItemTax,
'linked_refunds': LinkedRefund,
'allocations': Allocation,
}


@staticmethod
def create(params, env=None, headers=None):
Expand Down
8 changes: 8 additions & 0 deletions chargebee/models/customer.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ class Balance(Model):
"unbilled_charges", "refundable_credits", "excess_payments", "balances", "meta_data", "deleted", \
"registered_for_gst", "customer_type"]

sub_types = {
'billing_address': BillingAddress,
'referral_urls': ReferralUrl,
'contacts': Contact,
'payment_method': PaymentMethod,
'balances': Balance,
}


@staticmethod
def create(params=None, env=None, headers=None):
Expand Down
15 changes: 15 additions & 0 deletions chargebee/models/estimate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,26 @@
from chargebee import request
from chargebee import APIError

from chargebee.models.credit_note_estimate import CreditNoteEstimate
from chargebee.models.invoice_estimate import InvoiceEstimate
from chargebee.models.subscription_estimate import SubscriptionEstimate
from chargebee.models.unbilled_charge import UnbilledCharge


class Estimate(Model):

fields = ["created_at", "subscription_estimate", "invoice_estimate", "invoice_estimates", \
"next_invoice_estimate", "credit_note_estimates", "unbilled_charge_estimates"]

dependant_types = {
'subscription_estimate': SubscriptionEstimate,
'invoice_estimate': InvoiceEstimate,
'next_invoice_estimate': InvoiceEstimate,
'invoice_estimates': (InvoiceEstimate,),
'credit_note_estimates': (CreditNoteEstimate,),
'unbilled_charge_estimates': (UnbilledCharge,),
}


@staticmethod
def create_subscription(params, env=None, headers=None):
Expand Down
11 changes: 8 additions & 3 deletions chargebee/models/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ class Webhook(Model):
fields = ["id", "occurred_at", "source", "user", "webhook_status", "webhook_failure_reason", \
"webhooks", "event_type", "api_version"]

sub_types = {
'webhooks': Webhook,
}


@property
def content(self):
from chargebee import Content
Expand All @@ -23,12 +28,12 @@ def deserialize(json_data):
webhook_data = json.loads(json_data)
except (TypeError, ValueError) as ex:
raise Exception("The passed json_data is not JSON formatted . " + ex.message)

api_version = webhook_data.get('api_version', None)
env_version = Environment.API_VERSION
if api_version != None and api_version.upper() != env_version.upper():
if api_version != None and api_version.upper() != env_version.upper():
raise Exception("API version [" + api_version.upper() + "] in response does not match "
+ "with client library API version [" + env_version.upper() + "]")
+ "with client library API version [" + env_version.upper() + "]")
return Event.construct(webhook_data)

@staticmethod
Expand Down
5 changes: 5 additions & 0 deletions chargebee/models/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ class Download(Model):
pass

fields = ["id", "operation_type", "mime_type", "status", "created_at", "download"]

sub_types = {
'download': Download,
}

def wait_for_export_completion(self):
return wait_for_export_completion()

Expand Down
5 changes: 5 additions & 0 deletions chargebee/models/gift.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ class GiftTimeline(Model):
fields = ["id", "status", "scheduled_at", "auto_claim", "claim_expiry_date", "resource_version", \
"updated_at", "gifter", "gift_receiver", "gift_timelines"]

sub_types = {
'gifter': Gifter,
'gift_receiver': GiftReceiver,
'gift_timelines': GiftTimeline,
}

@staticmethod
def create(params, env=None, headers=None):
Expand Down
17 changes: 17 additions & 0 deletions chargebee/models/invoice.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,23 @@ class BillingAddress(Model):
"line_item_tiers", "linked_payments", "applied_credits", "adjustment_credit_notes", "issued_credit_notes", \
"linked_orders", "notes", "shipping_address", "billing_address", "deleted"]

sub_types = {
'line_items': LineItem,
'discounts': Discount,
'line_item_discounts': LineItemDiscount,
'taxes': Tax,
'line_item_taxes': LineItemTax,
'line_item_tiers' : LineItemTier,
'linked_payments': LinkedPayment,
'applied_credits': AppliedCredit,
'adjustment_credit_notes': AdjustmentCreditNote,
'issued_credit_notes': IssuedCreditNote,
'linked_orders': LinkedOrder,
'notes': Note,
'shipping_address': ShippingAddress,
'billing_address': BillingAddress,
}


@staticmethod
def create(params, env=None, headers=None):
Expand Down
8 changes: 8 additions & 0 deletions chargebee/models/invoice_estimate.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,11 @@ class LineItemDiscount(Model):
"amount_paid", "amount_due", "line_items", "discounts", "taxes", "line_item_taxes", "line_item_tiers", \
"line_item_discounts", "round_off_amount"]

sub_types = {
'line_items': LineItem,
'discounts': Discount,
'taxes': Tax,
'line_item_taxes': LineItemTax,
'line_item_tiers' : LineItemTier,
'line_item_discounts': LineItemDiscount,
}
8 changes: 8 additions & 0 deletions chargebee/models/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ class LinkedCreditNote(Model):
"line_item_taxes", "line_item_discounts", "linked_credit_notes", "deleted", "currency_code", \
"is_gifted", "gift_note", "gift_id"]

sub_types = {
'order_line_items': OrderLineItem,
'shipping_address': ShippingAddress,
'billing_address': BillingAddress,
'line_item_taxes': LineItemTax,
'line_item_discounts': LineItemDiscount,
'linked_credit_notes': LinkedCreditNote,
}

@staticmethod
def create(params, env=None, headers=None):
Expand Down
7 changes: 7 additions & 0 deletions chargebee/models/payment_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ class Paypal(Model):
"reference_id", "status", "gateway", "gateway_account_id", "ip_address", "issuing_country", \
"card", "bank_account", "amazon_payment", "paypal", "deleted"]

sub_types = {
'card': Card,
'bank_account': BankAccount,
'amazon_payment': AmazonPayment,
'paypal': Paypal,
}


@staticmethod
def create_using_temp_token(params, env=None, headers=None):
Expand Down
6 changes: 6 additions & 0 deletions chargebee/models/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ class EventBasedAddon(Model):
"resource_version", "updated_at", "giftable", "claim_url", "invoice_notes", "taxable", "tax_profile_id", \
"meta_data", "tiers", "applicable_addons", "attached_addons", "event_based_addons"]

sub_types = {
'tiers': Tier,
'applicable_addons': ApplicableAddon,
'attached_addons': AttachedAddon,
'event_based_addons': EventBasedAddon,
}

@staticmethod
def create(params, env=None, headers=None):
Expand Down
4 changes: 4 additions & 0 deletions chargebee/models/portal_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ class LinkedCustomer(Model):
fields = ["id", "token", "access_url", "redirect_url", "status", "created_at", "expires_at", \
"customer_id", "login_at", "logout_at", "login_ipaddress", "logout_ipaddress", "linked_customers"]

sub_types = {
'linked_customers': LinkedCustomer
}


@staticmethod
def create(params, env=None, headers=None):
Expand Down
9 changes: 9 additions & 0 deletions chargebee/models/quote.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ class BillingAddress(Model):
"amount_due", "resource_version", "updated_at", "currency_code", "line_items", "discounts", \
"line_item_discounts", "taxes", "line_item_taxes", "shipping_address", "billing_address"]

sub_types = {
'line_items': LineItem,
'discounts': Discount,
'line_item_discounts': LineItemDiscount,
'taxes': Tax,
'line_item_taxes': LineItemTax,
'shipping_address': ShippingAddress,
'billing_address': BillingAddress,
}

@staticmethod
def retrieve(id, env=None, headers=None):
Expand Down
9 changes: 9 additions & 0 deletions chargebee/models/subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ class ReferralInfo(Model):
"addons", "event_based_addons", "charged_event_based_addons", "coupon", "coupons", "shipping_address", \
"referral_info", "invoice_notes", "meta_data", "deleted"]

sub_types = {
'addons': Addon,
'event_based_addons' : EventBasedAddon,
'charged_event_based_addons' : ChargedEventBasedAddon,
'coupons': Coupon,
'shipping_address': ShippingAddress,
'referral_info': ReferralInfo,
}


@staticmethod
def create(params, env=None, headers=None):
Expand Down
3 changes: 3 additions & 0 deletions chargebee/models/subscription_estimate.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@ class ShippingAddress(Model):
fields = ["id", "currency_code", "status", "next_billing_at", "pause_date", "resume_date", \
"shipping_address"]

sub_types = {
'shipping_address': ShippingAddress,
}
7 changes: 7 additions & 0 deletions chargebee/models/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ class LinkedPayment(Model):
"reversal_transaction_id", "linked_invoices", "linked_credit_notes", "linked_refunds", "linked_payments", \
"deleted"]

sub_types = {
'linked_invoices': LinkedInvoice,
'linked_credit_notes': LinkedCreditNote,
'linked_refunds': LinkedRefund,
'linked_payments': LinkedPayment,
}


@staticmethod
def create_authorization(params, env=None, headers=None):
Expand Down
3 changes: 3 additions & 0 deletions chargebee/models/unbilled_charge.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ class Tier(Model):
"pricing_model", "quantity", "amount", "currency_code", "discount_amount", "description", "entity_type", \
"entity_id", "is_voided", "voided_at", "tiers", "deleted"]

sub_types = {
'tiers' : Tier,
}

@staticmethod
def invoice_unbilled_charges(params=None, env=None, headers=None):
Expand Down
Loading

0 comments on commit 8a1e4b5

Please sign in to comment.