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 Feb 8, 2018
1 parent 8e3b64b commit ca6c568
Show file tree
Hide file tree
Showing 14 changed files with 258 additions and 87 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)

10 changes: 10 additions & 0 deletions chargebee/models/credit_note.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ class Allocation(Model):
"sub_total", "round_off_amount", "line_items", "discounts", "line_item_discounts", "taxes", \
"line_item_taxes", "linked_refunds", "allocations", "deleted"]

sub_types = {
'line_items': LineItem,
'discounts': Discount,
'line_item_discounts': LineItemDiscount,
'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 @@ -30,6 +30,14 @@ class Balance(Model):
"unbilled_charges", "refundable_credits", "excess_payments", "balances", "meta_data", "deleted", \
"registered_for_gst"]

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
16 changes: 16 additions & 0 deletions chargebee/models/invoice.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,22 @@ class BillingAddress(Model):
"taxes", "line_item_taxes", "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,
'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
7 changes: 7 additions & 0 deletions chargebee/models/invoice_estimate.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,10 @@ class LineItemDiscount(Model):
fields = ["recurring", "price_type", "currency_code", "sub_total", "total", "credits_applied", \
"amount_paid", "amount_due", "line_items", "discounts", "taxes", "line_item_taxes", "line_item_discounts"]

sub_types = {
'line_items': LineItem,
'discounts': Discount,
'taxes': Tax,
'line_item_taxes': LineItemTax,
'line_item_discounts': LineItemDiscount,
}
7 changes: 7 additions & 0 deletions chargebee/models/payment_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ class Paypal(Model):
fields = ["id", "customer_id", "type", "reference_id", "status", "gateway", "gateway_account_id", \
"ip_address", "issuing_country", "card", "bank_account", "amazon_payment", "paypal"]

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
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
7 changes: 7 additions & 0 deletions chargebee/models/subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ class ReferralInfo(Model):
"base_currency_code", "addons", "coupon", "coupons", "shipping_address", "referral_info", "invoice_notes", \
"meta_data", "deleted"]

sub_types = {
'addons': Addon,
'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 @@ -11,3 +11,6 @@ class ShippingAddress(Model):

fields = ["id", "currency_code", "status", "next_billing_at", "shipping_address"]

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

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


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

0 comments on commit ca6c568

Please sign in to comment.