Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[v3.1] Allow to extend user deletion logic #4472

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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