Created
March 8, 2013 18:01
-
-
Save Jimgerneer/5118464 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Bill < ActiveRecord::Base | |
attr_accessible :invoice, :amount, :initiated_by_id, :payer_id, :origin_id, :destination_id ,:accepted, :paid, :auto, :frequency, :payments_left | |
belongs_to :initiated_by, class_name: 'Member', foreign_key: :initiated_by_id | |
belongs_to :payer, class_name: 'Member', foreign_key: :payer_id | |
belongs_to :origin, class_name: 'Account', foreign_key: 'origin_id' | |
belongs_to :destination, class_name: 'Account', foreign_key: 'destination_id' | |
validates_numericality_of :amount, greater_than_or_equal_to: 0.01 | |
validates :amount, :presence => {message: "cannot be blank"} | |
scope :recent, order('created_at DESC') | |
before_save :valid_destination? | |
before_save :valid_funds?, on :update | |
before_save :pay, on :update | |
before_save :auto_bill, on :update | |
def pay | |
if accepted == true | |
balance_accounts | |
end | |
end | |
def auto_bill | |
if auto == true && accepted == true && payments_left > 0 | |
self.class.create(attributes.update(payments_left: payments_left - 1)) | |
end | |
end | |
def balance_accounts | |
destination_new_balance = destination.balance + amount | |
destination.update_attributes(:balance => destination_new_balance) | |
origin_new_balance = origin.balance - amount | |
origin.update_attributes(:balance => origin_new_balance) | |
end | |
def valid_funds? | |
return true if amount <= origin.balance | |
errors[:base] << "Sorry, you do not have enough funds" | |
return false | |
end | |
def valid_destination? | |
#different test needed for users of account | |
return true if initiated_by.id != destination.owner_id | |
errors[:base] << "Sorry, you can not send funds to the same account" | |
return false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment