Commit 09c949fb authored by Zsolt Benke's avatar Zsolt Benke
Browse files

Client is destroyable

- Client can be softdeleted when no assignments associated with it.
- Deleted assignments also taken into account.
parent 2457e5e7
Pipeline #21493 passed with stage
in 32 minutes and 17 seconds
......@@ -46,6 +46,8 @@ class Client < ApplicationRecord
Bitte sicherstellen, dass alle Einsätze komplett abgeschlossen sind.'
}, unless: :terminatable?
before_destroy :check_if_destroyable!
scope :with_assignments, (-> { distinct.joins(:assignments) })
scope :with_active_assignments, (-> { with_assignments.merge(Assignment.active) })
......@@ -118,4 +120,25 @@ class Client < ApplicationRecord
def inactive?
accepted? && assignments.active.blank?
end
def destroyable?
assignments.unscoped.blank?
end
private
def check_if_destroyable!
raise NotDestroyableError.new(self) unless destroyable?
end
class NotDestroyableError < StandardError
attr_reader :client
def initialize(client)
@client = client
assignment_ids = @client.assignments.unscoped.pluck(:id).join(', ')
message = "There are one or more assignment associated: #{assignment_ids}"
super(message)
end
end
end
......@@ -106,4 +106,48 @@ class ClientTest < ActiveSupport::TestCase
assignment.update period_end: 5.days.ago
assert_not @client.active?
end
test 'client is destroyable' do
client = create :client
assert client.destroyable?
assignment = create :assignment, client: client
refute client.destroyable?
assignment.destroy
refute_nil assignment.deleted_at
refute client.destroyable?
end
test 'destroying a client' do
client = create :client
assert_nil client.deleted_at
client.destroy!
refute_nil client.reload.deleted_at
client = create :client, :with_relatives
assert_nil client.deleted_at
client.destroy!
refute_nil client.reload.deleted_at
client.relatives.each do |relative|
assert_nil relative.deleted_at
end
client = create :client
assignment = create :assignment, client: client
assignment_ids = client.assignments.pluck(:id).join(', ')
message = "There are one or more assignment associated: #{assignment_ids}"
exception = assert_raise Client::NotDestroyableError do
client.destroy!
end
assert_equal message, exception.message
assignment.destroy
exception = assert_raise Client::NotDestroyableError do
client.destroy!
end
assert_equal message, exception.message
end
end
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment