summaryrefslogtreecommitdiff
path: root/billing/app/helpers/billing_helper.rb
blob: 68ed5b85fc229076ace6353fed755fa44bac47af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module BillingHelper

  def braintree_form_for(object, options = {}, &block)
    options.reverse_merge! params: @result && @result.params[object],
      errors: @result && @result.errors.for(object),
      builder: BraintreeFormHelper::BraintreeFormBuilder,
      url: Braintree::TransparentRedirect.url

    form_for object, options, &block
  end

  def billing_top_link(user)
    # for admins, top link will show special admin information, which has link to show their own customer information
    if (admin? and user == current_user)
      billing_admin_path
    else
      show_or_new_customer_link(user)
    end
  end

  def show_or_new_customer_link(user)
    # Link to show if user is admin viewing another user, or user is already a customer.
    # Otherwise link to create a new customer.
    if (admin? and (user != current_user)) or ((customer = Customer.find_by_user_id(user.id)) and customer.has_payment_info?)
      show_customer_path(user)
    else
      new_customer_path
    end
  end

  # a bit strange to put here, but we don't have a subscription model
  def user_for_subscription(subscription)

    if (transaction = subscription.transactions.first)
      # much quicker, but will only work if there is already a transaction associated with subscription (should generally be)
      braintree_customer = transaction.customer_details
    else
      search_results = Braintree::Customer.search do |search|
        search.payment_method_token.is subscription.payment_method_token
      end
      braintree_customer = search_results.first
    end

    customer = Customer.find_by_braintree_customer_id(braintree_customer.id)
    user = User.find(customer.user_id)

  end

  def show_set_user_subscriptions(set)
    if set.empty?
      return t(:none)
    else
      subscriptions_to_display = ''
      set.each do |past_due_subscription|
        subscriptions_to_display += render :partial => "subscriptions/subscription_details", :locals => {:subscription => past_due_subscription, :show_user => user_for_subscription(past_due_subscription)}
      end
     subscriptions_to_display.html_safe
    end
  end


end