2019-07-30 21:29:24 +00:00
# frozen_string_literal: true
2018-03-25 16:15:39 +00:00
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
2018-03-25 17:30:42 +00:00
module CancelBillingSubscription
# @param [Nonprofit] nonprofit
# @return [BillingSubscription] new billing subscription for the nonprofit
2019-07-30 21:29:24 +00:00
def self . with_stripe ( nonprofit )
2018-03-25 17:30:42 +00:00
begin
2019-07-30 21:29:24 +00:00
ParamValidation . new ( { nonprofit : nonprofit } ,
nonprofit : { required : true , is_a : Nonprofit } )
2018-03-25 17:30:42 +00:00
rescue ParamValidation :: ValidationError = > e
2019-07-30 21:29:24 +00:00
return { json : { error : " Validation error \n #{ e . message } " , errors : e . data } , status : :unprocessable_entity }
2018-03-25 17:30:42 +00:00
end
2019-07-30 21:29:24 +00:00
np_card = nonprofit . active_card
billing_subscription = nonprofit . billing_subscription
return { json : { error : 'We don\'t have a subscription for your non-profit. Please contact support.' } , status : :unprocessable_entity } if np_card . nil? || billing_subscription . nil? # stripe_customer_id on Card object
2018-03-25 17:30:42 +00:00
# Cancel and delete the subscription on Stripe
begin
customer = Stripe :: Customer . retrieve ( np_card . stripe_customer_id )
stripe_subscription = customer . subscriptions . retrieve ( billing_subscription . stripe_subscription_id )
s = stripe_subscription . delete ( at_period_end : false )
rescue Stripe :: StripeError = > e
2019-07-30 21:29:24 +00:00
return { json : { error : " Oops! There was an error processing your subscription cancellation. Error: #{ e } " } , status : :unprocessable_entity }
2018-03-25 17:30:42 +00:00
end
billing_plan_id = Settings . default_bp . id
2019-07-30 21:29:24 +00:00
billing_subscription . update_attributes (
2018-03-25 17:30:42 +00:00
billing_plan_id : billing_plan_id ,
status : 'active'
2019-07-30 21:29:24 +00:00
)
2018-03-25 17:30:42 +00:00
2019-07-30 21:29:24 +00:00
{ json : { } , status : :ok }
end
2018-03-25 17:30:42 +00:00
end