Skip to content

Commit

Permalink
Allow to extend user deletion logic
Browse files Browse the repository at this point in the history
Currently we restrict to delete a user with an exception if
the user has any orders. Some businesses might want to
allow to delete users with incomplete orders.

This allows to override the can_be_deleted? method in the user
class.

Refs #3138
  • Loading branch information
tvdeyen committed Jul 26, 2022
1 parent 51b1a68 commit ef40441
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
2 changes: 1 addition & 1 deletion backend/app/views/spree/admin/users/index.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
<% if can?(:edit, user) %>
<%= link_to_edit user, no_text: true %>
<% end %>
<% if can?(:destroy, user) && user.orders.none? %>
<% if can?(:destroy, user) && user.can_be_deleted? %>
<%= link_to_delete user, no_text: true %>
<% end %>
</td>
Expand Down
21 changes: 20 additions & 1 deletion core/app/models/concerns/spree/user_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ module UserMethods
has_many :stock_locations, through: :user_stock_locations

has_many :spree_orders, foreign_key: "user_id", class_name: "Spree::Order"
has_many :orders, foreign_key: "user_id", class_name: "Spree::Order", dependent: :restrict_with_exception
has_many :orders, foreign_key: "user_id", class_name: "Spree::Order"

has_many :store_credits, -> { includes(:credit_type) }, foreign_key: "user_id", class_name: "Spree::StoreCredit"
has_many :store_credit_events, through: :store_credits
Expand All @@ -27,6 +27,7 @@ module UserMethods
has_many :wallet_payment_sources, foreign_key: 'user_id', class_name: 'Spree::WalletPaymentSource', inverse_of: :user

after_create :auto_generate_spree_api_key
before_destroy :check_for_deletion

include Spree::RansackableAttributes unless included_modules.include?(Spree::RansackableAttributes)

Expand Down Expand Up @@ -76,5 +77,23 @@ def display_available_store_credit_total(currency:)
currency: currency,
)
end

# Restrict to delete users with existing orders
#
# Override this in your user model class to add another logic.
#
# Ie. to allow to delete users with incomplete orders add:
#
# orders.complete.none?
#
def can_be_deleted?
orders.none?
end

private

def check_for_deletion
raise ActiveRecord::DeleteRestrictionError unless can_be_deleted?
end
end
end

0 comments on commit ef40441

Please sign in to comment.