|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# == Schema Information |
| 4 | +# |
| 5 | +# Table name: location_patients_exports |
| 6 | +# |
| 7 | +# id :bigint not null, primary key |
| 8 | +# academic_year :integer not null |
| 9 | +# filter_params :jsonb not null |
| 10 | +# created_at :datetime not null |
| 11 | +# updated_at :datetime not null |
| 12 | +# location_id :bigint not null |
| 13 | +# |
| 14 | +# Foreign Keys |
| 15 | +# |
| 16 | +# fk_rails_... (location_id => locations.id) |
| 17 | +# |
| 18 | +class LocationPatientsExport < ApplicationRecord |
| 19 | + belongs_to :location |
| 20 | + has_one :export, as: :exportable, touch: true |
| 21 | + delegate :team, to: :export, allow_nil: true |
| 22 | + |
| 23 | + def file_type = :xlsx |
| 24 | + |
| 25 | + def type_label = "Offline session" |
| 26 | + |
| 27 | + def name |
| 28 | + "#{location.name} offline session" |
| 29 | + end |
| 30 | + |
| 31 | + def filename |
| 32 | + "#{name} - exported on #{Date.current.to_fs(:long)}.xlsx" |
| 33 | + end |
| 34 | + |
| 35 | + def generate_file |
| 36 | + filter = |
| 37 | + PatientFilter.new(team:, academic_year:, **filter_params.symbolize_keys) |
| 38 | + patients, programmes = |
| 39 | + location.school? ? school_patients(filter) : clinic_patients(filter) |
| 40 | + Reports::OfflineExporter.from_patients( |
| 41 | + patients, |
| 42 | + team:, |
| 43 | + programmes:, |
| 44 | + academic_year: |
| 45 | + ) |
| 46 | + end |
| 47 | + |
| 48 | + private |
| 49 | + |
| 50 | + def school_patients(filter) |
| 51 | + scope = |
| 52 | + Patient |
| 53 | + .joins(:patient_locations) |
| 54 | + .where(patient_locations: { location:, academic_year: }) |
| 55 | + .where(school: location) |
| 56 | + .includes_statuses |
| 57 | + [filter.apply(scope), location.programmes] |
| 58 | + end |
| 59 | + |
| 60 | + def clinic_patients(filter) |
| 61 | + [filter.apply(Patient.includes_statuses), team.programmes] |
| 62 | + end |
| 63 | +end |
0 commit comments