|
3 | 3 | class BulkRemoveParentRelationshipsJob < ApplicationJob |
4 | 4 | queue_as :imports |
5 | 5 |
|
6 | | - def perform(import_global_id, consent_ids, user_id, remove_option) |
| 6 | + def perform( |
| 7 | + import_global_id, |
| 8 | + parent_relationship_ids_batch, |
| 9 | + user_id, |
| 10 | + remove_option |
| 11 | + ) |
7 | 12 | import = GlobalID::Locator.locate(import_global_id) |
8 | | - consents = Consent.where(id: consent_ids) |
9 | | - |
10 | | - if remove_option == "unconsented_only" |
11 | | - import.destroy_parent_relationships_without_consent!(consents) |
12 | | - else |
13 | | - import.destroy_parent_relationships_and_invalidate_consents!( |
14 | | - User.find(user_id), |
15 | | - consents |
16 | | - ) |
| 13 | + user = User.find(user_id) |
| 14 | + |
| 15 | + ActiveRecord::Base.transaction do |
| 16 | + parent_relationships = |
| 17 | + import |
| 18 | + .parent_relationships |
| 19 | + .where(id: parent_relationship_ids_batch) |
| 20 | + .includes(:parent, :patient) |
| 21 | + |
| 22 | + consents = |
| 23 | + import.parent_relationship_consents(scope: parent_relationships) |
| 24 | + |
| 25 | + parent_relationships_to_remove = |
| 26 | + if remove_option == "unconsented_only" |
| 27 | + consented_pairs = consents.pluck(:patient_id, :parent_id).to_set |
| 28 | + |
| 29 | + parent_relationships.reject do |pr| |
| 30 | + consented_pairs.include?([pr.patient_id, pr.parent_id]) |
| 31 | + end |
| 32 | + else |
| 33 | + parent_relationships |
| 34 | + end |
| 35 | + |
| 36 | + invalidate_consents!(user, consents) if remove_option == "all" |
| 37 | + |
| 38 | + parents_to_check = parent_relationships_to_remove.map(&:parent) |
| 39 | + patient_ids = parent_relationships_to_remove.map(&:patient_id) |
| 40 | + |
| 41 | + parent_relationships_to_remove.each(&:destroy!) |
| 42 | + |
| 43 | + parents_to_check.each do |parent| |
| 44 | + next if parent.destroyed? |
| 45 | + next if parent.parent_relationships.exists? |
| 46 | + next if parent.consents.exists? |
| 47 | + |
| 48 | + parent.destroy! |
| 49 | + end |
| 50 | + |
| 51 | + StatusUpdaterJob.perform_bulk(patient_ids.zip) |
17 | 52 | end |
18 | 53 |
|
| 54 | + mark_complete_if_finished(import, remove_option) |
| 55 | + end |
| 56 | + |
| 57 | + private |
| 58 | + |
| 59 | + def invalidate_consents!(user, consents) |
| 60 | + timestamp = Time.current.to_fs(:long) |
| 61 | + invalidation_note = |
| 62 | + "Consent invalidated on #{timestamp} " \ |
| 63 | + "because #{user.full_name} removed all parent-child relationships from an import." |
| 64 | + |
| 65 | + consents.update_all(notes: invalidation_note, invalidated_at: Time.current) |
| 66 | + end |
| 67 | + |
| 68 | + def mark_complete_if_finished(import, remove_option) |
| 69 | + return unless import.remaining_parent_relationships(remove_option:).empty? |
| 70 | + |
19 | 71 | import.update!(status: :processed) |
20 | 72 | end |
21 | 73 | end |
0 commit comments