1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-01-29 18:52:22 +01:00

refactor payment process for sca

This commit is contained in:
Sylvain 2019-09-10 11:46:14 +02:00
parent e9e27663cd
commit a96050a2e9
10 changed files with 177 additions and 298 deletions

View File

@ -4,13 +4,21 @@
class API::PaymentsController < API::ApiController
before_action :authenticate_user!
##
# Client requests to confirm a card payment will ask this endpoint.
# It will check for the need of a strong customer authentication (SCA) to confirm the payment or confirm that the payment
# was successfully made. After the payment was made, the reservation/subscription will be created
##
def confirm_payment
begin
if params[:payment_method_id].present?
# Create the PaymentIntent
# TODO the client has to provide the reservation details. Then, we use Price.compute - user.walletAmount to get the amount
# currency is set in Rails.secrets
# Check the coupon
unless coupon_params[:coupon_code].nil?
coupon = Coupon.find_by(code: coupon_params[:coupon_code])
raise InvalidCouponError if coupon.nil? || coupon.status(current_user.id) != 'active'
end
# Compute the price
reservable = cart_items_params[:reservable_type].constantize.find(cart_items_params[:reservable_id])
price_details = Price.compute(false,
current_user,
@ -21,49 +29,51 @@ class API::PaymentsController < API::ApiController
cart_items_params[:tickets_attributes],
coupon_params[:coupon_code])
# Subtract wallet amount from total
total = price_details[:total]
wallet_debit = get_wallet_debit(current_user, total)
# Create the PaymentIntent
intent = Stripe::PaymentIntent.create(
payment_method: params[:payment_method_id],
amount: price_details[:total],
currency: 'eur',
amount: total - wallet_debit,
currency: Rails.application.secrets.stripe_currency,
confirmation_method: 'manual',
confirm: true
)
elsif params[:payment_intent_id].present?
intent = Stripe::PaymentIntent.confirm(params[:payment_intent_id])
end
rescue Stripe::CardError => e
# Display error on client
render status: 200, json: { error: e.message }
end
# TODO extract in subroutine
if intent.status == 'succeeded'
begin
user_id = params[:cart_items][:reservation][:user_id]
@reservation = Reservation.new(reservation_params)
is_reserve = Reservations::Reserve.new(user_id, current_user.invoicing_profile.id)
.pay_and_save(@reservation, :stripe, coupon_params[:coupon_code])
if is_reserve
SubscriptionExtensionAfterReservation.new(@reservation).extend_subscription_if_eligible
render('api/reservations/show', status: :created, location: @reservation) and return
else
render(json: @reservation.errors, status: :unprocessable_entity) and return
end
rescue InvalidCouponError
render(json: { coupon_code: 'wrong coupon code or expired' }, status: :unprocessable_entity) and return
end
end
render(on_payment_success) and return if intent.status == 'succeeded'
render generate_payment_response(intent)
end
private
def on_payment_success
# TODO create subscription is needed
user_id = params[:cart_items][:reservation][:user_id]
@reservation = Reservation.new(reservation_params)
is_reserve = Reservations::Reserve.new(user_id, current_user.invoicing_profile.id)
.pay_and_save(@reservation, coupon_params[:coupon_code])
if is_reserve
SubscriptionExtensionAfterReservation.new(@reservation).extend_subscription_if_eligible
{ template: 'api/reservations/show', status: :created, location: @reservation }
else
{ json: @reservation.errors, status: :unprocessable_entity }
end
rescue InvalidCouponError
{ json: { coupon_code: 'wrong coupon code or expired' }, status: :unprocessable_entity }
end
def generate_payment_response(intent)
if intent.status == 'requires_action' && intent.next_action.type == 'use_stripe_sdk'
# Tell the client to handle the action
@ -84,6 +94,11 @@ class API::PaymentsController < API::ApiController
end
end
def get_wallet_debit(user, total_amount)
wallet_amount = (user.wallet.amount * 100).to_i
wallet_amount >= total_amount ? total_amount : wallet_amount
end
def reservation_params
params[:cart_items].require(:reservation).permit(:reservable_id, :reservable_type, :plan_id, :nb_reserve_places,
tickets_attributes: %i[event_price_category_id booked],

View File

@ -28,7 +28,7 @@ class API::ReservationsController < API::ApiController
@reservation = Reservation.new(reservation_params)
is_reserve = Reservations::Reserve.new(user_id, current_user.invoicing_profile.id)
.pay_and_save(@reservation, :local, coupon_params[:coupon_code])
.pay_and_save(@reservation, coupon_params[:coupon_code])
if is_reserve
SubscriptionExtensionAfterReservation.new(@reservation).extend_subscription_if_eligible

View File

@ -2,8 +2,6 @@
# API Controller for resources of type Subscription
class API::SubscriptionsController < API::ApiController
include FablabConfiguration
before_action :set_subscription, only: %i[show edit update destroy]
before_action :authenticate_user!
@ -12,21 +10,18 @@ class API::SubscriptionsController < API::ApiController
end
def create
if fablab_plans_deactivated?
head 403
authorize Subscription
user_id = params[:subscription][:user_id]
@subscription = Subscription.new(subscription_params)
is_subscribe = Subscriptions::Subscribe.new(current_user.invoicing_profile.id, user_id)
.pay_and_save(@subscription, coupon_params[:coupon_code], true)
if is_subscribe
render :show, status: :created, location: @subscription
else
method = current_user.admin? ? :local : :stripe
user_id = current_user.admin? ? params[:subscription][:user_id] : current_user.id
@subscription = Subscription.new(subscription_params)
is_subscribe = Subscriptions::Subscribe.new(current_user.invoicing_profile.id, user_id)
.pay_and_save(@subscription, method, coupon_params[:coupon_code], true)
if is_subscribe
render :show, status: :created, location: @subscription
else
render json: @subscription.errors, status: :unprocessable_entity
end
render json: @subscription.errors, status: :unprocessable_entity
end
end

View File

@ -1,67 +1,67 @@
# frozen_string_literal: true
# Store customized price for various items (Machine, Space), depending on the group and on the plan
# Also provides a static helper method to compute the price details of a shopping cart
class Price < ActiveRecord::Base
belongs_to :group
belongs_to :plan
belongs_to :priceable, polymorphic: true
validates :priceable, :group_id, :amount, presence: true
validates :priceable_id, uniqueness: { scope: [:priceable_type, :plan_id, :group_id] }
validates :priceable_id, uniqueness: { scope: %i[priceable_type plan_id group_id] }
##
# @param admin {Boolean} true if the current user (ie.the user who requests the price) is an admin
# @param user {User} The user who's reserving (or selected if an admin is reserving)
# @param reservable {Machine|Training|Event} what the reservation is targeting
# @param slots {Array<Slot>} when did the reservation will occur
# @param [plan_id] {Number} if the user is subscribing to a plan at the same time of his reservation, specify the plan's ID here
# @param [nb_places] {Number} for _reservable_ of type Event, pass here the number of booked places
# @param [tickets] {Array<Ticket>} for _reservable_ of type Event, mapping of the number of seats booked per price's category
# @param [coupon_code] {String} Code of the coupon to apply to the total price
# @return {Hash} total and price detail
##
def self.compute(admin, user, reservable, slots, plan_id = nil, nb_places = nil, tickets = nil, coupon_code = nil)
_amount = 0
_elements = Hash.new
_elements[:slots] = Array.new
class << self
# initialize Plan
if user.subscribed_plan
plan = user.subscribed_plan
new_plan_being_bought = false
elsif plan_id
plan = Plan.find(plan_id)
new_plan_being_bought = true
else
plan = nil
new_plan_being_bought = false
end
##
# @param admin {Boolean} true if the current user (ie.the user who requests the price) is an admin
# @param user {User} The user who's reserving (or selected if an admin is reserving)
# @param reservable {Machine|Training|Event} what the reservation is targeting
# @param slots {Array<Slot>} when did the reservation will occur
# @param [plan_id] {Number} if the user is subscribing to a plan at the same time of his reservation, specify the plan's ID here
# @param [nb_places] {Number} for _reservable_ of type Event, pass here the number of booked places
# @param [tickets] {Array<Ticket>} for _reservable_ of type Event, mapping of the number of seats booked per price's category
# @param [coupon_code] {String} Code of the coupon to apply to the total price
# @return {Hash} total and price detail
##
def compute(admin, user, reservable, slots, plan_id = nil, nb_places = nil, tickets = nil, coupon_code = nil)
total_amount = 0
all_elements = {}
all_elements[:slots] = []
# === compute reservation price ===
# initialize Plan
if user.subscribed_plan
plan = user.subscribed_plan
new_plan_being_bought = false
elsif plan_id
plan = Plan.find(plan_id)
new_plan_being_bought = true
else
plan = nil
new_plan_being_bought = false
end
case reservable
# === compute reservation price ===
case reservable
# Machine reservation
when Machine
base_amount = reservable.prices.find_by(group_id: user.group_id, plan_id: plan.try(:id)).amount
if plan
space_credit = plan.machine_credits.select {|credit| credit.creditable_id == reservable.id}.first
space_credit = plan.machine_credits.select { |credit| credit.creditable_id == reservable.id }.first
if space_credit
hours_available = space_credit.hours
unless new_plan_being_bought
user_credit = user.users_credits.find_by(credit_id: space_credit.id)
if user_credit
hours_available = space_credit.hours - user_credit.hours_used
end
end
hours_available = credits_hours(space_credit, user, new_plan_being_bought)
slots.each_with_index do |slot, index|
_amount += get_slot_price(base_amount, slot, admin, _elements, (index < hours_available))
total_amount += get_slot_price(base_amount, slot, admin, all_elements, (index < hours_available))
end
else
slots.each do |slot|
_amount += get_slot_price(base_amount, slot, admin, _elements)
total_amount += get_slot_price(base_amount, slot, admin, all_elements)
end
end
else
slots.each do |slot|
_amount += get_slot_price(base_amount, slot, admin, _elements)
total_amount += get_slot_price(base_amount, slot, admin, all_elements)
end
end
@ -70,34 +70,30 @@ class Price < ActiveRecord::Base
amount = reservable.amount_by_group(user.group_id).amount
if plan
# Return True if the subscription link a training credit for training reserved by the user
space_is_creditable = plan.training_credits.select {|credit| credit.creditable_id == reservable.id}.size > 0
space_is_creditable = plan.training_credits.select { |credit| credit.creditable_id == reservable.id }.any?
# Training reserved by the user is free when :
# |-> the user already has a current subscription and if space_is_creditable is true and has at least one credit available.
if !new_plan_being_bought
if user.training_credits.size < plan.training_credit_nb and space_is_creditable
amount = 0
end
amount = 0 if user.training_credits.size < plan.training_credit_nb && space_is_creditable
# |-> the user buys a new subscription and if space_is_creditable is true.
else
if space_is_creditable
amount = 0
end
amount = 0 if space_is_creditable
end
end
slots.each do |slot|
_amount += get_slot_price(amount, slot, admin, _elements)
total_amount += get_slot_price(amount, slot, admin, all_elements)
end
# Event reservation
when Event
amount = reservable.amount * nb_places
tickets.each do |ticket|
tickets&.each do |ticket|
amount += ticket[:booked] * EventPriceCategory.find(ticket[:event_price_category_id]).amount
end unless tickets.nil?
end
slots.each do |slot|
_amount += get_slot_price(amount, slot, admin, _elements)
total_amount += get_slot_price(amount, slot, admin, all_elements)
end
# Space reservation
@ -105,62 +101,71 @@ class Price < ActiveRecord::Base
base_amount = reservable.prices.find_by(group_id: user.group_id, plan_id: plan.try(:id)).amount
if plan
space_credit = plan.space_credits.select {|credit| credit.creditable_id == reservable.id}.first
space_credit = plan.space_credits.select { |credit| credit.creditable_id == reservable.id }.first
if space_credit
hours_available = space_credit.hours
unless new_plan_being_bought
user_credit = user.users_credits.find_by(credit_id: space_credit.id)
if user_credit
hours_available = space_credit.hours - user_credit.hours_used
end
end
hours_available = credits_hours(space_credit, user, new_plan_being_bought)
slots.each_with_index do |slot, index|
_amount += get_slot_price(base_amount, slot, admin, _elements, (index < hours_available))
total_amount += get_slot_price(base_amount, slot, admin, all_elements, (index < hours_available))
end
else
slots.each do |slot|
_amount += get_slot_price(base_amount, slot, admin, _elements)
total_amount += get_slot_price(base_amount, slot, admin, all_elements)
end
end
else
slots.each do |slot|
_amount += get_slot_price(base_amount, slot, admin, _elements)
total_amount += get_slot_price(base_amount, slot, admin, all_elements)
end
end
# Unknown reservation type
else
raise NotImplementedError
end
# === compute Plan price if any ===
unless plan_id.nil?
all_elements[:plan] = plan.amount
total_amount += plan.amount
end
# === apply Coupon if any ===
_amount_no_coupon = total_amount
total_amount = CouponService.new.apply(total_amount, coupon_code)
# return result
{ elements: all_elements, total: total_amount, before_coupon: _amount_no_coupon }
end
# === compute Plan price if any ===
unless plan_id.nil?
_elements[:plan] = plan.amount
_amount += plan.amount
private
##
# Compute the price of a single slot, according to the base price and the ability for an admin
# to offer the slot.
# @param base_amount {Number} base price of a slot
# @param slot {Hash} Slot object
# @param is_admin {Boolean} true if the current user has the 'admin' role
# @param [elements] {Array} optional, if provided the resulting price will be append into elements.slots
# @param [has_credits] {Boolean} true if the user still has credits for the given slot
# @return {Number} price of the slot
##
def get_slot_price(base_amount, slot, is_admin, elements = nil, has_credits = false)
ii_amount = has_credits || (slot[:offered] && is_admin) ? 0 : base_amount
elements[:slots].push(start_at: slot[:start_at], price: ii_amount, promo: (ii_amount != base_amount)) unless elements.nil?
ii_amount
end
# === apply Coupon if any ===
_amount_no_coupon = _amount
_amount = CouponService.new.apply(_amount, coupon_code)
# return result
{elements: _elements, total: _amount, before_coupon: _amount_no_coupon}
end
private
##
# Compute the price of a single slot, according to the base price and the ability for an admin
# to offer the slot.
# @param base_amount {Number} base price of a slot
# @param slot {Hash} Slot object
# @param is_admin {Boolean} true if the current user has the 'admin' role
# @param [elements] {Array} optional, if provided the resulting price will be append into elements.slots
# @param [has_credits] {Boolean} true if the user still has credits for the given slot
# @return {Number} price of the slot
##
def self.get_slot_price(base_amount, slot, is_admin, elements = nil, has_credits = false)
ii_amount = (((has_credits) or (slot[:offered] and is_admin)) ? 0 : base_amount)
elements[:slots].push({start_at: slot[:start_at], price: ii_amount, promo: (ii_amount != base_amount)}) unless elements.nil?
ii_amount
##
# Compute the number of remaining hours in the users current credits (for machine or space)
##
def credits_hours(credits, user, new_plan_being_bought)
hours_available = credits.hours
unless new_plan_being_bought
user_credit = user.users_credits.find_by(credit_id: credits.id)
hours_available = credits.hours - user_credit.hours_used if user_credit
end
hours_available
end
end
end

View File

@ -170,95 +170,6 @@ class Reservation < ActiveRecord::Base
true
end
def save_with_payment(operator_profile_id, coupon_code = nil)
begin
build_invoice(invoicing_profile: user.invoicing_profile, statistic_profile: user.statistic_profile, operator_profile_id: operator_profile_id)
generate_invoice_items(false, coupon_code)
rescue StandardError => e
logger.error e
errors[:payment] << e.message
return false
end
return false unless valid?
# TODO: refactoring
customer = Stripe::Customer.retrieve(user.stp_customer_id)
if plan_id
self.subscription = Subscription.find_or_initialize_by(statistic_profile_id: statistic_profile_id)
subscription.attributes = { plan_id: plan_id, statistic_profile_id: statistic_profile_id, expiration_date: nil }
if subscription.save_with_payment(operator_profile_id, false)
# self.stp_invoice_id = invoice_items.first.refresh.invoice # save payment_intent_id instead of stp_invoice_id
# invoice.stp_invoice_id = invoice_items.first.refresh.invoice
invoice.invoice_items.push InvoiceItem.new(
amount: subscription.plan.amount,
description: subscription.plan.name,
subscription_id: subscription.id
)
set_total_and_coupon(coupon_code)
save!
#
# IMPORTANT NOTE: here, we don't have to create a stripe::invoice and pay it
# because subscription.create (in subscription.rb) will pay all waiting stripe invoice items
#
else
# error handling
# errors[:card] << subscription.errors[:card].join
# errors[:payment] << subscription.errors[:payment].join if subscription.errors[:payment]
return false
end
else
begin
set_total_and_coupon(coupon_code)
save!
rescue Stripe::CardError => card_error
clear_payment_info(card, stp_invoice)
logger.info card_error
errors[:card] << card_error.message
return false
rescue Stripe::InvalidRequestError => e
# Invalid parameters were supplied to Stripe's API
clear_payment_info(card, stp_invoice)
logger.error e
errors[:payment] << e.message
return false
rescue Stripe::AuthenticationError => e
# Authentication with Stripe's API failed
# (maybe you changed API keys recently)
clear_payment_info(card, stp_invoice)
logger.error e
errors[:payment] << e.message
return false
rescue Stripe::APIConnectionError => e
# Network communication with Stripe failed
clear_payment_info(card, stp_invoice)
logger.error e
errors[:payment] << e.message
return false
rescue Stripe::StripeError => e
# Display a very generic error to the user, and maybe send
# yourself an email
clear_payment_info(card, stp_invoice)
logger.error e
errors[:payment] << e.message
return false
rescue StandardError => e
# Something else happened, completely unrelated to Stripe
clear_payment_info(card, stp_invoice)
logger.error e
errors[:payment] << e.message
return false
end
end
UsersCredits::Manager.new(reservation: self).update_credits
true
end
# check reservation amount total and strip invoice total to pay is equal
# @param stp_invoice[Stripe::Invoice]
# @param coupon_code[String]
@ -290,7 +201,7 @@ class Reservation < ActiveRecord::Base
pending_invoice_items.each(&:delete)
end
def save_with_local_payment(operator_profile_id, coupon_code = nil)
def save_with_payment(operator_profile_id, coupon_code = nil)
build_invoice(
invoicing_profile: user.invoicing_profile,
statistic_profile: user.statistic_profile,
@ -303,7 +214,7 @@ class Reservation < ActiveRecord::Base
if plan_id
self.subscription = Subscription.find_or_initialize_by(statistic_profile_id: statistic_profile_id)
subscription.attributes = { plan_id: plan_id, statistic_profile_id: statistic_profile_id, expiration_date: nil }
if subscription.save_with_local_payment(operator_profile_id, false)
if subscription.save_with_payment(operator_profile_id, false)
invoice.invoice_items.push InvoiceItem.new(
amount: subscription.plan.amount,
description: subscription.plan.name,

View File

@ -1,3 +1,6 @@
# frozen_string_literal: true
# Subscription is an active or archived subscription of an User to a Plan
class Subscription < ActiveRecord::Base
include NotifyWith::NotificationAttachedObject
@ -17,57 +20,9 @@ class Subscription < ActiveRecord::Base
after_save :notify_admin_subscribed_plan
after_save :notify_partner_subscribed_plan, if: :of_partner_plan?
# Stripe subscription payment
# @param invoice if true then subscription pay itself, dont pay with reservation
# if false then subscription pay with reservation
def save_with_payment(operator_profile_id, invoice = true, coupon_code = nil)
return unless valid?
begin
invoice_items = []
unless coupon_code.nil?
@coupon = Coupon.find_by(code: coupon_code)
raise InvalidCouponError if @coupon.nil? || @coupon.status(user.id) != 'active'
total = plan.amount
end
# only add a wallet invoice item if pay subscription
# dont add if pay subscription + reservation
@wallet_amount_debit = get_wallet_amount_debit
self.canceled_at = nil
set_expiration_date
save!
UsersCredits::Manager.new(user: user).reset_credits
# generate invoice
if invoice
db_invoice = generate_invoice(operator_profile_id, coupon_code)
# debit wallet
wallet_transaction = debit_user_wallet
if wallet_transaction
db_invoice.wallet_amount = @wallet_amount_debit
db_invoice.wallet_transaction_id = wallet_transaction.id
end
db_invoice.save
end
# cancel subscription after create
cancel
return true
rescue StandardError => e
# Something else happened, completely unrelated to Stripe
logger.error e
errors[:payment] << e.message
return false
end
end
# @param invoice if true then only the subscription is payed, without reservation
# if false then the subscription is payed with reservation
def save_with_local_payment(operator_profile_id, invoice = true, coupon_code = nil)
def save_with_payment(operator_profile_id, invoice = true, coupon_code = nil)
return false unless valid?
set_expiration_date

View File

@ -1,4 +1,12 @@
# frozen_string_literal: true
# Check the access policies for API::SubscriptionsController
class SubscriptionPolicy < ApplicationPolicy
include FablabConfiguration
def create?
!fablab_plans_deactivated? && user.admin?
end
def show?
user.admin? or record.user_id == user.id
end

View File

@ -12,22 +12,20 @@ class CouponService
def apply(total, coupon, user_id = nil)
price = total
_coupon = nil
coupon_object = nil
if coupon.instance_of? Coupon
_coupon = coupon
coupon_object = coupon
elsif coupon.instance_of? String
_coupon = Coupon.find_by(code: coupon)
coupon_object = Coupon.find_by(code: coupon)
end
unless _coupon.nil?
if _coupon.status(user_id, total) == 'active'
if _coupon.type == 'percent_off'
price -= price * _coupon.percent_off / 100.00
elsif _coupon.type == 'amount_off'
unless coupon_object.nil?
if coupon_object.status(user_id, total) == 'active'
if coupon_object.type == 'percent_off'
price -= price * coupon_object.percent_off / 100.00
elsif coupon_object.type == 'amount_off'
# do not apply cash coupon unless it has a lower amount that the total price
if _coupon.amount_off <= price
price -= _coupon.amount_off
end
price -= coupon_object.amount_off if coupon_object.amount_off <= price
end
end
end
@ -56,4 +54,4 @@ class CouponService
end
price
end
end
end

View File

@ -9,12 +9,8 @@ class Reservations::Reserve
@operator_profile_id = operator_profile_id
end
def pay_and_save(reservation, payment_method, coupon)
def pay_and_save(reservation, coupon)
reservation.statistic_profile_id = StatisticProfile.find_by(user_id: user_id).id
if payment_method == :local
reservation.save_with_local_payment(operator_profile_id, coupon)
elsif payment_method == :stripe
reservation.save_with_payment(operator_profile_id, coupon)
end
reservation.save_with_payment(operator_profile_id, coupon)
end
end

View File

@ -9,15 +9,11 @@ class Subscriptions::Subscribe
@operator_profile_id = operator_profile_id
end
def pay_and_save(subscription, payment_method, coupon, invoice)
def pay_and_save(subscription, coupon, invoice)
return false if user_id.nil?
subscription.statistic_profile_id = StatisticProfile.find_by(user_id: user_id).id
if payment_method == :local
subscription.save_with_local_payment(operator_profile_id, invoice, coupon)
elsif payment_method == :stripe
subscription.save_with_payment(operator_profile_id, invoice, coupon)
end
subscription.save_with_payment(operator_profile_id, invoice, coupon)
end
def extend_subscription(subscription, new_expiration_date, free_days)