2023-04-07 16:02:13 +02:00
|
|
|
class Migrations::NormalizeCommunesJob < ApplicationJob
|
|
|
|
def perform(ids)
|
|
|
|
Champs::CommuneChamp.where(id: ids).find_each do |champ|
|
|
|
|
next if champ.external_id.blank?
|
|
|
|
|
|
|
|
value_json = champ.value_json || {}
|
|
|
|
|
2023-04-27 11:56:45 +02:00
|
|
|
if !champ.departement? || champ.code_departement == 'undefined'
|
2023-04-07 16:02:13 +02:00
|
|
|
metro_code = champ.external_id[0..1]
|
|
|
|
drom_com_code = champ.external_id[0..2]
|
|
|
|
|
|
|
|
if metro_code == '97' || metro_code == '98'
|
|
|
|
value_json[:code_departement] = drom_com_code
|
|
|
|
else
|
|
|
|
value_json[:code_departement] = metro_code
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-04-11 10:49:01 +02:00
|
|
|
if !champ.code_postal? && code_postal_with_fallback(champ).present?
|
|
|
|
value_json[:code_postal] = code_postal_with_fallback(champ)
|
2023-04-07 16:02:13 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
if value_json.present?
|
|
|
|
champ.update_column(:value_json, value_json)
|
|
|
|
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
|