|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +class TeamCachedCounts |
| 4 | + def initialize(team) |
| 5 | + @team = team |
| 6 | + end |
| 7 | + |
| 8 | + def import_issues |
| 9 | + return nil if current_user.nil? |
| 10 | + |
| 11 | + Rails |
| 12 | + .cache |
| 13 | + .fetch(import_issues_key) do |
| 14 | + vaccination_records_with_issues = |
| 15 | + VaccinationRecordPolicy::Scope |
| 16 | + .new(current_user, VaccinationRecord) |
| 17 | + .resolve |
| 18 | + .with_pending_changes |
| 19 | + .pluck(:patient_id) |
| 20 | + |
| 21 | + patients_with_issues = |
| 22 | + PatientPolicy::Scope |
| 23 | + .new(current_user, Patient) |
| 24 | + .resolve |
| 25 | + .with_pending_changes |
| 26 | + .pluck(:id) |
| 27 | + |
| 28 | + (vaccination_records_with_issues + patients_with_issues).uniq.length |
| 29 | + end |
| 30 | + end |
| 31 | + |
| 32 | + def reset_import_issues! |
| 33 | + Rails.cache.delete(import_issues_key) |
| 34 | + end |
| 35 | + |
| 36 | + def school_moves |
| 37 | + return nil if current_user.nil? |
| 38 | + |
| 39 | + Rails |
| 40 | + .cache |
| 41 | + .fetch(school_moves_key) do |
| 42 | + SchoolMovePolicy::Scope.new(current_user, SchoolMove).resolve.count |
| 43 | + end |
| 44 | + end |
| 45 | + |
| 46 | + def reset_school_moves! |
| 47 | + Rails.cache.delete(school_moves_key) |
| 48 | + end |
| 49 | + |
| 50 | + def unmatched_consent_responses |
| 51 | + return nil if current_user.nil? |
| 52 | + |
| 53 | + Rails |
| 54 | + .cache |
| 55 | + .fetch(unmatched_consent_responses_key) do |
| 56 | + ConsentFormPolicy::Scope |
| 57 | + .new(current_user, ConsentForm) |
| 58 | + .resolve |
| 59 | + .unmatched |
| 60 | + .recorded |
| 61 | + .not_archived |
| 62 | + .count |
| 63 | + end |
| 64 | + end |
| 65 | + |
| 66 | + def reset_unmatched_consent_responses! |
| 67 | + Rails.cache.delete(unmatched_consent_responses_key) |
| 68 | + end |
| 69 | + |
| 70 | + private |
| 71 | + |
| 72 | + attr_reader :team |
| 73 | + |
| 74 | + def import_issues_key = cache_key("import-issues") |
| 75 | + |
| 76 | + def school_moves_key = cache_key("school-moves") |
| 77 | + |
| 78 | + def unmatched_consent_responses_key = cache_key("unmatched-consent-responses") |
| 79 | + |
| 80 | + def current_user |
| 81 | + # We can't use the policy_scope helper here as we're not in a controller. |
| 82 | + # Instead, we can mock what a `User` looks like from the perspective of a |
| 83 | + # controller to satisfy the policy scopes. |
| 84 | + @current_user ||= |
| 85 | + if team && (organisation = team.organisation) |
| 86 | + OpenStruct.new(selected_team: team, selected_organisation: organisation) |
| 87 | + end |
| 88 | + end |
| 89 | + |
| 90 | + def cache_key(type) = "cached-counts/#{type}/#{team.id}" |
| 91 | +end |
0 commit comments