Upgraded Rails
[monkeycharger.git] / app / models / authorization.rb
blobb394e818ea333af5399342f8b96d2339be814b99
1 class Authorization < ActiveRecord::Base
2   attr_accessor :passphrase
4   has_many    :refunds
5   has_one     :capture
6   has_one     :void, :as => :voidee
7   belongs_to  :credit_card
9   validate :authorize!
11   validates_presence_of :transaction_id
12   validates_presence_of :last_four_digits
14   after_validation :remove_other_error_messages
15   
16   def initialize attributes
17     super(attributes)
18     # Do an authorization on an existing credit card
19     if credit_card_id = attributes[:credit_card_id]
20       self.credit_card = CreditCard.find(credit_card_id).decrypt!(attributes[:passphrase])
21     end
22   end
25   alias_method :set_credit_card_association, :credit_card=
27   def credit_card= card
28     if card.is_a?(Hash)
29       card =  CreditCard.new(:number => card['number'], :month => card['month'], :year => card['year'], :name => card['name'])
30       set_credit_card_association card
31       self.last_four_digits = card.last_four_digits
32     else
33       set_credit_card_association card
34     end
35   end
37   private
39   def authorize! 
40     response = $gateway.authorize(self.amount.to_cents, self.credit_card)
41     if response.success?
42       self.transaction_id = response.authorization
43       self.last_four_digits = self.credit_card.last_four_digits
44     else
45       logger.info "Bad authorization!"
46       logger.info response.message
47       errors.add_to_base(response.message)
48     end
49   end
51   # There might be a better way to do this, but I don't want ActiveRecord
52   # adding error messages for when the transaction_id or last_four_digits
53   # is missing as a result of a failed authorization.  The only error 
54   # message should be from the credit card processor.
55   def remove_other_error_messages
56     base_error_msg = errors.on(:base)
57     errors.clear
58     errors.add_to_base(base_error_msg) if base_error_msg
59   end
60 end