diff --git a/app/controllers/payments_controller.rb b/app/controllers/payments_controller.rb new file mode 100644 index 00000000..161d2101 --- /dev/null +++ b/app/controllers/payments_controller.rb @@ -0,0 +1,48 @@ +class PaymentsController < ApplicationController + before_action :authenticate_user! + load_and_authorize_resource + load_resource :conference, find_by: :short_title + authorize_resource :conference_registrations, class: Registration + + def index + @payments = current_user.payments + end + + def new + @total_amount_to_pay = Ticket.total_price(@conference, current_user, paid: false) + @unpaid_ticket_purchases = current_user.ticket_purchases.unpaid.by_conference(@conference) + end + + def create + @unpaid_ticket_purchases = current_user.ticket_purchases.unpaid.by_conference(@conference) + @total_amount_to_pay = Ticket.total_price(@conference, current_user, paid: false) + + customer = Stripe::Customer.create( + :email => params[:stripeEmail], + :source => params[:stripeToken] + ) + + gateway_response = Stripe::Charge.create( + :customer => customer.id, + :amount => @total_amount_to_pay.cents, + :description => 'Rails Stripe customer', + :currency => @conference.tickets.first.price_currency + ) + + payment = Payment.purchase(gateway_response, current_user, @conference) + update_purchased_ticket_purchases(payment) + + redirect_to conference_conference_registration_path(@conference.short_title), + flash: { success: 'Thanks! You have purchased your tickets successfully.' } + + rescue Stripe::CardError => e + flash[:error] = e.message + render 'new' + end + +private + + def update_purchased_ticket_purchases(payment) + current_user.ticket_purchases.by_conference(@conference).unpaid.update_all(paid: true, payment_id: payment.id) + end +end diff --git a/app/models/ability.rb b/app/models/ability.rb index 2210a7cd..74b1e47d 100644 --- a/app/models/ability.rb +++ b/app/models/ability.rb @@ -81,6 +81,7 @@ class Ability can :index, Ticket can :manage, TicketPurchase, user_id: user.id + can [:new], Payment, user_id: user.id can [:create, :destroy], Subscription, user_id: user.id diff --git a/config/routes.rb b/config/routes.rb index 25c253e5..d1b79617 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -112,6 +112,7 @@ Osem::Application.routes.draw do resource :conference_registration, path: 'register' resources :tickets, only: [:index] resources :ticket_purchases, only: [:create, :destroy] + resources :payments, only: [:index, :new, :create] resource :subscriptions, only: [:create, :destroy] resource :schedule, only: [:show] do member do