def call(
ods_code:,
start_date: nil,
end_date: nil,
workgroup: nil,
academic_year: nil,
output: "tmp/automated_export.csv",
**
)
MavisCLI.load_rails
organisation = Organisation.find_by(ods_code:)
if organisation.nil?
warn "Could not find organisation with ODS code '#{ods_code}'"
return
end
teams = organisation.teams
teams = teams.where(workgroup:) if workgroup
if teams.empty?
warn(
if workgroup
"Could not find team '#{workgroup}' for organisation '#{ods_code}'"
else
"Organisation '#{ods_code}' has no teams."
end
)
return
end
if workgroup.nil? && teams.many?
warn "Organisation '#{ods_code}' has multiple teams. Specify --workgroup."
return
end
team = teams.sole
unless team.careplus_enabled?
warn "Team '#{team.name}' does not have CarePlus enabled."
return
end
parsed_start_date =
if start_date
begin
Date.parse(start_date)
rescue ArgumentError
warn "Invalid start_date '#{start_date}'. Expected YYYY-MM-DD format."
return
end
else
Time.zone.today
end
parsed_end_date =
if end_date
begin
Date.parse(end_date)
rescue ArgumentError
warn "Invalid end_date '#{end_date}'. Expected YYYY-MM-DD format."
return
end
else
Time.zone.today
end
academic_year_value = academic_year&.to_i || AcademicYear.current
records =
::Reports::AutomatedCareplusExporter.vaccination_records_scope(
team:,
academic_year: academic_year_value,
start_date: parsed_start_date,
end_date: parsed_end_date
)
programme_types =
records.unscope(:order).distinct.pluck(:programme_type)
csv =
::Reports::AutomatedCareplusExporter.from_records(
team:,
academic_year: academic_year_value,
vaccination_records: records
)
if records.none?
puts "No records found. No CarePlus report was created."
return
end
now = Time.current
ActiveRecord::Base.transaction do
careplus_report =
CareplusReport.create!(
team:,
academic_year: academic_year_value,
date_from: parsed_start_date,
date_to: parsed_end_date,
programme_types:,
scheduled_at: now,
sent_at: now,
status: :sent,
csv_filename: File.basename(output),
csv_data: csv
)
now_iso = now.iso8601(6)
CareplusReportVaccinationRecord.insert_all!(
records.map do |record|
{
careplus_report_id: careplus_report.id,
vaccination_record_id: record.id,
change_type: 0,
created_at: now_iso,
updated_at: now_iso
}
end
)
end
File.write(output, csv)
puts "Exported to #{output}"
end