1
0
Fork 0
forked from OpenNeo/impress
impress/app/models/donation.rb

72 lines
1.7 KiB
Ruby
Raw Normal View History

2014-09-09 19:06:38 -07:00
class Donation < ActiveRecord::Base
2014-09-09 21:16:02 -07:00
FEATURE_COST = 500 # in cents = $5.00
attr_accessible :donor_name
2014-09-11 15:40:37 -07:00
belongs_to :campaign
2014-09-09 19:06:38 -07:00
belongs_to :user
2014-09-09 21:16:02 -07:00
has_many :features, class_name: 'DonationFeature'
2014-09-09 19:06:38 -07:00
def to_param
"#{id}-#{secret}"
end
2014-09-11 15:40:37 -07:00
def self.create_from_charge(campaign, user, params)
2014-09-09 19:06:38 -07:00
amount = (BigDecimal.new(params[:amount]) * 100).floor
2014-09-11 15:40:37 -07:00
campaign.progress += amount
2014-12-23 20:22:15 -08:00
charge_params = {
amount: amount,
description: 'Donation (thank you!)',
currency: 'usd'
}
if params[:stripe_token_type] == 'card'
customer = Stripe::Customer.create(
card: params[:stripe_token]
)
charge_params[:customer] = customer.id
elsif params[:stripe_token_type] == 'bitcoin_receiver'
charge_params[:card] = params[:stripe_token]
else
raise ArgumentError, "unexpected stripe token type #{params[:stripe_token_type]}"
end
charge = Stripe::Charge.create(charge_params)
2014-09-09 19:06:38 -07:00
2014-09-11 15:40:37 -07:00
donation = campaign.donations.build
2014-09-09 19:06:38 -07:00
donation.amount = amount
donation.charge_id = charge.id
2014-09-11 15:40:37 -07:00
donation.user = user
donation.donor_name = user.try(:name)
2014-09-10 12:32:54 -07:00
donation.donor_email = params[:donor_email]
donation.secret = new_secret
2014-09-09 21:16:02 -07:00
num_features = amount / FEATURE_COST
features = []
num_features.times do
features << donation.features.new
end
Donation.transaction do
2014-09-11 15:40:37 -07:00
campaign.save!
2014-09-09 21:16:02 -07:00
donation.save!
features.each(&:save!)
end
2014-09-09 19:06:38 -07:00
DonationMailer.thank_you_email(donation, donation.donor_email).deliver
2014-09-10 12:32:54 -07:00
2014-09-09 19:06:38 -07:00
donation
end
def self.new_secret
SecureRandom.urlsafe_base64 8
end
def self.from_param(param)
id, secret = param.split('-', 2)
self.where(secret: secret).find(id)
end
2014-09-09 19:06:38 -07:00
end