2024-04-29 00:17:15 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2023-04-07 16:02:13 +02:00
|
|
|
class Migrations::NormalizeCommunesJob < ApplicationJob
|
|
|
|
def perform(ids)
|
|
|
|
Champs::CommuneChamp.where(id: ids).find_each do |champ|
|
2023-11-10 10:31:15 +01:00
|
|
|
if champ.external_id.blank?
|
|
|
|
champ.value = nil
|
|
|
|
champ.value_json = {}
|
|
|
|
champ.save!
|
|
|
|
else
|
|
|
|
value_json = champ.value_json || {}
|
2023-04-07 16:02:13 +02:00
|
|
|
|
2023-11-10 10:31:15 +01:00
|
|
|
if !champ.departement? || champ.code_departement == 'undefined' || champ.code_departement == '99'
|
|
|
|
metro_code = champ.external_id[0..1]
|
|
|
|
drom_com_code = champ.external_id[0..2]
|
2023-04-07 16:02:13 +02:00
|
|
|
|
2023-11-10 10:31:15 +01:00
|
|
|
if metro_code == '97' || metro_code == '98'
|
|
|
|
value_json[:code_departement] = drom_com_code
|
|
|
|
else
|
|
|
|
value_json[:code_departement] = metro_code
|
|
|
|
end
|
2023-04-07 16:02:13 +02:00
|
|
|
end
|
|
|
|
|
2023-11-10 10:31:15 +01:00
|
|
|
if !champ.code_postal? && code_postal_with_fallback(champ).present?
|
|
|
|
value_json[:code_postal] = code_postal_with_fallback(champ)
|
|
|
|
end
|
2023-04-07 16:02:13 +02:00
|
|
|
|
2023-11-10 10:31:15 +01:00
|
|
|
if value_json.present?
|
|
|
|
champ.update_column(:value_json, value_json)
|
|
|
|
end
|
2023-04-07 16:02:13 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2023-04-11 10:49:01 +02:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
# We try to extract the postal code from the value, which is the name of the commune and the
|
|
|
|
# postal code in brackets.
|
|
|
|
def code_postal_with_fallback(champ)
|
|
|
|
if champ.value.present?
|
|
|
|
match = champ.value.match(/[^(]\(([^\)]*)\)$/)
|
|
|
|
match[1] if match.present?
|
|
|
|
else
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
end
|
2023-04-07 16:02:13 +02:00
|
|
|
end
|