feat(dossier): add methods to upsert champ values

This commit is contained in:
Paul Chavard 2024-03-27 11:31:41 +01:00
parent c479d46b47
commit 0c7bc6b555
4 changed files with 369 additions and 39 deletions

View file

@ -39,6 +39,46 @@ module DossierChampsConcern
end
end
def find_type_de_champ_by_stable_id(stable_id, scope = nil)
case scope
when :public
revision.types_de_champ.public_only
when :private
revision.types_de_champ.private_only
else
revision.types_de_champ
end.find_by!(stable_id:)
end
def champs_for_prefill(stable_ids)
revision
.types_de_champ
.filter { _1.stable_id.in?(stable_ids) }
.filter { !revision.child?(_1) }
.map { champ_for_update(_1, nil) }
end
def champ_for_update(type_de_champ, row_id)
champ, attributes = champ_with_attributes_for_update(type_de_champ, row_id)
champ.assign_attributes(attributes)
champ
end
def update_champs_attributes(attributes, scope)
# TODO: remove after one deploy
if attributes.present? && attributes.values.filter { _1.key?(:with_public_id) }.empty?
assign_attributes("champs_#{scope}_all_attributes".to_sym => attributes)
@champs_by_public_id = nil
return
end
champs_attributes = attributes.to_h.map do |public_id, attributes|
champ_attributes_by_public_id(public_id, attributes, scope)
end
assign_attributes(champs_attributes:)
end
private
def champs_by_public_id
@ -53,4 +93,39 @@ module DossierChampsConcern
champ
end
end
def champ_attributes_by_public_id(public_id, attributes, scope)
stable_id, row_id = public_id.split('-')
type_de_champ = find_type_de_champ_by_stable_id(stable_id, scope)
champ_with_attributes_for_update(type_de_champ, row_id).last.merge(attributes)
end
def champ_with_attributes_for_update(type_de_champ, row_id)
attributes = type_de_champ.params_for_champ
# TODO: Once we have the right index in place, we should change this to use `create_or_find_by` instead of `find_or_create_by`
champ = champs
.create_with(type_de_champ:, **attributes)
.find_or_create_by!(stable_id: type_de_champ.stable_id, row_id:)
attributes[:id] = champ.id
# Needed when a revision change the champ type in this case, we reset the champ data
if champ.type != attributes[:type]
attributes[:value] = nil
attributes[:value_json] = nil
attributes[:external_id] = nil
attributes[:data] = nil
end
parent = revision.parent_of(type_de_champ)
if parent.present?
attributes[:parent] = champs.find { _1.type_de_champ_id == parent.id }
else
attributes[:parent] = nil
end
@champs_by_public_id = nil
[champ, attributes]
end
end

View file

@ -13,8 +13,4 @@ module DossierPrefillableConcern
assign_attributes(attributes)
save(validate: false)
end
def find_champs_by_stable_ids(stable_ids)
champs.joins(:type_de_champ).where(types_de_champ: { stable_id: stable_ids.compact.uniq })
end
end