Created
September 9, 2019 13:37
-
-
Save al3rez/d7f549bac2f1220cb0751a3d7a1177af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class ChangePackage | |
include Failable | |
attr_reader :subscription, :package, :expire_date, :package_history | |
private *delegate :store_campagin!, :upcoming_package_change? | |
:current_invoice, to: :subscription | |
def initialize(subscription, package) | |
@subscription = subscription | |
@package = package | |
@expire_date = Subscription::CaculateLastCycle.call(subscription) | |
@package_history = PackageHistory.new( | |
package: package, | |
subscription: subscription, | |
expire_date: expire_date | |
) | |
@cdrator = Cdrator::ChangePackage.new( | |
cdrator_id: subscription.cdrator_id, | |
product_id: package.cdrator_product_id, | |
rate_plan_id: package.cdrator_rate_plan_id, | |
new_campaigns: package_history.request_params, | |
expire_campaigns: package_history.expire_campaigns | |
) | |
end | |
def call | |
check_invoice | |
check_upcoming_package_change | |
change_package! | |
cancel_extend_package! | |
create_package_history! | |
update_subscription_previous_campaigns! | |
end | |
def check_invoice | |
fail!('invoice.not_opened') unless invoice_open? | |
end | |
def check_upcoming_package_change | |
fail!(:upcoming_package_change_exists) if upcoming_package_change? | |
end | |
def change_package | |
fail!(cdrator.result) unless cdrator.call | |
end | |
def cancel_extend_package! | |
return unless extending_package? | |
Subscription::CancelExtendPackageJob.perform_later(subscription) | |
end | |
def create_package_history! | |
package_history.update!(cdrator_response: cdrator.result) | |
rescue ActiveRecord::RecordInvalid => failure | |
fail!(failure) | |
end | |
def store_campagin! | |
store_campagin! | |
rescue ActiveRecord::RecordInvalid => failure | |
fail!(failure) | |
end | |
private def invoice_open? | |
current_invoice&.open? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment