diff --git a/app/models/customer.rb b/app/models/customer.rb index ec4d78235c..de37b5094a 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -10,7 +10,7 @@ class Customer < ApplicationRecord belongs_to :enterprise belongs_to :user, class_name: "Spree::User" has_many :orders, class_name: "Spree::Order" - before_destroy :check_for_orders + before_destroy :update_orders_and_delete_canceled_subscriptions belongs_to :bill_address, class_name: "Spree::Address" alias_attribute :billing_address, :bill_address @@ -52,10 +52,12 @@ class Customer < ApplicationRecord self.user = user || Spree::User.find_by(email: email) end - def check_for_orders - return true unless orders.any? - - errors.add(:base, I18n.t('admin.customers.destroy.has_associated_orders')) - throw :abort + def update_orders_and_delete_canceled_subscriptions + if Subscription.where(customer_id: id).not_canceled.any? + errors.add(:base, I18n.t('admin.customers.destroy.has_associated_subscriptions')) + throw :abort + end + Subscription.where(customer_id: id).destroy_all + orders.update_all(customer_id: nil) end end diff --git a/app/models/subscription.rb b/app/models/subscription.rb index ce87b1dd57..d930f7a2b3 100644 --- a/app/models/subscription.rb +++ b/app/models/subscription.rb @@ -17,7 +17,7 @@ class Subscription < ApplicationRecord belongs_to :payment_method, class_name: 'Spree::PaymentMethod' belongs_to :bill_address, class_name: "Spree::Address" belongs_to :ship_address, class_name: "Spree::Address" - has_many :subscription_line_items, inverse_of: :subscription + has_many :subscription_line_items, inverse_of: :subscription, dependent: :destroy has_many :order_cycles, through: :schedule has_many :proxy_orders has_many :orders, through: :proxy_orders diff --git a/config/locales/en.yml b/config/locales/en.yml index b0a60ad58c..40fcbde7ca 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -607,7 +607,7 @@ en: balance_due: "Balance Due" destroy: has_associated_orders: "Delete failed: customer has associated orders with his shop" - + has_associated_subscriptions: "Delete failed: customer has active associated subscriptions with shops" contents: edit: title: Content