feat(Maintenance.communes): backfill missing external_id for communes champs in error

This commit is contained in:
mfo 2024-09-05 18:43:45 +02:00
parent 99b31b0cc8
commit 657fb0ebf4
No known key found for this signature in database
GPG key ID: 7CE3E1F5B794A8EC
4 changed files with 202 additions and 0 deletions

View file

@ -0,0 +1,69 @@
# frozen_string_literal: true
module Maintenance
# some of our Champs::CommuneChamp had been corrupted, ie: missing external_id
# this tasks fix this issue
class FixChampsCommuneHavingValueButNotExternalIdTask < MaintenanceTasks::Task
DEFAULT_INSTRUCTEUR_EMAIL = ENV.fetch('DEFAULT_INSTRUCTEUR_EMAIL') { CONTACT_EMAIL }
def collection
Champs::CommuneChamp.where.not(value: nil)
end
def process(champ)
return if !fixable?(champ)
response = APIGeoService.commune_by_name_or_postal_code(champ.value)
if !response.success?
notify("Strange case of existing commune not requestable", champ)
else
results = JSON.parse(response.body, symbolize_names: true)
formated_results = APIGeoService.format_commune_response(results, true)
case formated_results.size
when 1
champ.code = formated_results.first[:value]
champ.save!
else # otherwise, we can't find the expected departement
champ.code_departement = nil
champ.code_postal = nil
champ.external_id = nil
champ.value = nil
champ.save(validate: false)
ask_user_correction(champ)
end
end
end
def count
# 2.4M champs, count is not an option
end
private
def ask_user_correction(champ)
dossier = champ.dossier
commentaire = CommentaireService.build(current_instructeur, dossier, { body: "Suite à un problème technique, Veuillez re-remplir le champs : #{champ.libelle}" })
dossier.flag_as_pending_correction!(commentaire, :incomplete)
end
def current_instructeur
user = User.find_by(email: DEFAULT_INSTRUCTEUR_EMAIL)
user ||= User.create(email: DEFAULT_INSTRUCTEUR_EMAIL,
password: Random.srand,
confirmed_at: Time.zone.now,
email_verified_at: Time.zone.now)
instructeur = user.instructeur
instructeur ||= user.create_instructeur!
instructeur
end
def fixable?(champ)
champ.value.present? && [champ.dossier.en_instruction? || champ.dossier.en_construction?]
end
def notify(message, champ) = Sentry.capture_message(message, extra: { champ: })
end
end