module ActiveRecord module Acts #:nodoc: module MuckCommerceUser # :nodoc: def self.included(base) base.extend(ClassMethods) end module ClassMethods # +acts_as_muck_commerce_user+ ties a user into the muck commerce system and adds order, carts, etc. # Access cart using: # @user.cart # Access default billing information: # @user.billing_information # Each user can have a referral code which can be accessed using: # @user.referral_code def acts_as_muck_commerce_user has_one :cart, :as => :cartable, :dependent => :destroy has_many :billing_informations, :as => :billable, :dependent => :destroy has_many :order_transactions, :as => :transactionable, :dependent => :destroy has_many :orders, :as => :orderable has_many :subscriptions, :dependent => :destroy has_one :referral_coupon_code, :class_name => 'Coupon' include ActiveRecord::Acts::MuckCommerceUser::InstanceMethods extend ActiveRecord::Acts::MuckCommerceUser::SingletonMethods end end # class methods module SingletonMethods end module InstanceMethods # This is the description that will be passed to the CIM system def cim_description self.display_name end def subscription @default_subscription ||= self.subscriptions.default.first end # Get the user's default billing information def billing_information bi = self.billing_informations.default.first # In case this is a new user the above call will return nil. Try to get billing information object from array: bi ||= self.billing_informations.first if self.billing_informations.length == 1 bi end # Setup or update billing information for the user def create_update_billing_information!(billing_information) if self.billing_information @default_billing_information = self.billing_information @default_billing_information.update_attributes!(billing_information) else @default_billing_information = BillingInformation.create!(billing_information.merge(:default => true)) self.billing_informations << @default_billing_information end @default_billing_information.update_remote_storage @default_billing_information end # Build but do not save billing information for the user def build_billing_information(billing_information) BillingInformation.new(billing_information.merge(:default => true, :user_id => self.id)) end def referral_code self.referral_coupon_code ||= Coupon.create(:code => Coupon.random_code, :unlimited => true, :coupon_type => CouponType.user_referral) end end end end end