Skip to content

Commit

Permalink
fix(subscriptions): fix edit subscription attached to parent plan (#1711
Browse files Browse the repository at this point in the history
)

* fix edit subscription attached to parent plan

* fix linter issues
  • Loading branch information
lovrocolic authored Feb 22, 2024
1 parent 6387623 commit 47989ac
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
23 changes: 19 additions & 4 deletions app/services/subscriptions/update_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,10 @@ def call
subscription.ending_at = params[:ending_at] if params.key?(:ending_at)

if params.key?(:plan_overrides)
plan_result = Plans::UpdateService.call(
plan: subscription.plan,
params: params[:plan_overrides].to_h.with_indifferent_access,
)
plan_result = handle_plan_override
return plan_result unless plan_result.success?

subscription.plan = plan_result.plan
end

if subscription.starting_in_the_future? && params.key?(:subscription_at)
Expand Down Expand Up @@ -61,6 +60,22 @@ def process_subscription_at_change(subscription)
BillSubscriptionJob.perform_later([subscription], Time.current.to_i)
end

def handle_plan_override
current_plan = subscription.plan

if current_plan.parent_id
Plans::UpdateService.call(
plan: current_plan,
params: params[:plan_overrides].to_h.with_indifferent_access,
)
else
Plans::OverrideService.call(
plan: current_plan,
params: params[:plan_overrides].to_h.with_indifferent_access,
)
end
end

def valid?(args)
Subscriptions::ValidateService.new(result, **args).valid?
end
Expand Down
21 changes: 19 additions & 2 deletions spec/services/subscriptions/update_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@
end

context 'when plan_overrides' do
let(:plan) { create(:plan, organization: membership.organization) }
let(:subscription) { create(:subscription, plan:, subscription_at: Time.current - 1.year) }
let(:params) do
{
plan_overrides: {
Expand All @@ -119,8 +121,23 @@

around { |test| lago_premium!(&test) }

it 'updates the plan accordingly' do
expect { update_service.call }.to change { subscription.plan.reload.name }.to('new name')
it 'creates the new plan accordingly' do
update_service.call

expect(subscription.plan.reload.name).to eq('new name')
expect(subscription.plan_id).not_to eq(plan.id)
end

context 'with overriden plan' do
let(:parent_plan) { create(:plan, organization: membership.organization) }
let(:plan) { create(:plan, organization: membership.organization, parent_id: parent_plan.id) }

it 'updates the plan accordingly' do
update_service.call

expect(subscription.plan.reload.name).to eq('new name')
expect(subscription.plan_id).to eq(plan.id)
end
end
end

Expand Down

0 comments on commit 47989ac

Please sign in to comment.