|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module MavisCLI |
| 4 | + module VaccinationRecords |
| 5 | + class CreateFromFHIR < Dry::CLI::Command |
| 6 | + desc "Create a vaccination record from a FHIR Immunization JSON" |
| 7 | + |
| 8 | + argument :patient_id, |
| 9 | + required: true, |
| 10 | + desc: "ID of the patient to attach the vaccination record to" |
| 11 | + argument :team_id, |
| 12 | + required: false, |
| 13 | + desc: "ID of the team (optional, used for batch association)" |
| 14 | + |
| 15 | + option :file, |
| 16 | + type: :string, |
| 17 | + required: false, |
| 18 | + desc: "Path to a file containing the FHIR Immunization JSON" |
| 19 | + option :json, |
| 20 | + type: :string, |
| 21 | + required: false, |
| 22 | + desc: "Raw FHIR Immunization JSON string" |
| 23 | + |
| 24 | + def call(patient_id:, team_id: nil, file: nil, json: nil, **) |
| 25 | + MavisCLI.load_rails |
| 26 | + |
| 27 | + if file.nil? && json.nil? |
| 28 | + puts "Error: Provide either --file PATH or --json STRING" |
| 29 | + return |
| 30 | + end |
| 31 | + |
| 32 | + if file && json |
| 33 | + puts "Error: Provide only one of --file or --json" |
| 34 | + return |
| 35 | + end |
| 36 | + |
| 37 | + patient = ::Patient.find_by(id: patient_id) |
| 38 | + if patient.nil? |
| 39 | + puts "Error: Patient with ID #{patient_id} not found" |
| 40 | + return |
| 41 | + end |
| 42 | + |
| 43 | + team = team_id.present? ? ::Team.find_by(id: team_id) : nil |
| 44 | + if team_id.present? && team.nil? |
| 45 | + puts "Error: Team with ID #{team_id} not found" |
| 46 | + return |
| 47 | + end |
| 48 | + |
| 49 | + begin |
| 50 | + payload = file ? File.read(file) : json |
| 51 | + data = JSON.parse(payload) |
| 52 | + rescue Errno::ENOENT |
| 53 | + puts "Error: File not found: #{file}" |
| 54 | + return |
| 55 | + rescue JSON::ParserError => e |
| 56 | + puts "Error: Invalid JSON - #{e.message}" |
| 57 | + return |
| 58 | + end |
| 59 | + |
| 60 | + begin |
| 61 | + fhir_record = FHIR::Immunization.new(data) |
| 62 | + rescue StandardError => e |
| 63 | + puts "Error: Could not build FHIR::Immunization - #{e.message}" |
| 64 | + return |
| 65 | + end |
| 66 | + |
| 67 | + begin |
| 68 | + record = FHIRMapper::VaccinationRecord.from_fhir_record( |
| 69 | + fhir_record, |
| 70 | + patient: patient, |
| 71 | + team: team |
| 72 | + ) |
| 73 | + |
| 74 | + record.save! |
| 75 | + puts "Created vaccination record #{record.id}" |
| 76 | + rescue ActiveRecord::RecordInvalid => e |
| 77 | + puts "Error: Could not save VaccinationRecord - #{e.record.errors.full_messages.join(', ')}" |
| 78 | + rescue StandardError => e |
| 79 | + puts "Error: #{e.message}" |
| 80 | + end |
| 81 | + end |
| 82 | + end |
| 83 | + end |
| 84 | + |
| 85 | + register "vaccination-records" do |prefix| |
| 86 | + prefix.register "create-from-fhir", VaccinationRecords::CreateFromFHIR |
| 87 | + end |
| 88 | +end |
0 commit comments