From e38999efda23ca135c8a2bddbcd9844b75f1a4ae Mon Sep 17 00:00:00 2001 From: simon lehericey Date: Sat, 18 May 2024 10:02:29 +0200 Subject: [PATCH] perf(pj service): compute row_id without extraneous requests --- app/models/champ.rb | 6 ------ app/services/pieces_justificatives_service.rb | 12 ++++++++++-- spec/services/procedure_export_service_zip_spec.rb | 4 ++-- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/app/models/champ.rb b/app/models/champ.rb index a66b91e84..74b5fd1e9 100644 --- a/app/models/champ.rb +++ b/app/models/champ.rb @@ -95,12 +95,6 @@ class Champ < ApplicationRecord [row_id, stable_id].compact end - def row_index - return nil if parent_id.nil? - - Champ.where(parent_id:).pluck(:row_id).sort.index(row_id) - end - # used for the `required` html attribute # check visibility to avoid hidden required input # which prevent the form from being sent. diff --git a/app/services/pieces_justificatives_service.rb b/app/services/pieces_justificatives_service.rb index 4b83d3b28..612adba35 100644 --- a/app/services/pieces_justificatives_service.rb +++ b/app/services/pieces_justificatives_service.rb @@ -141,10 +141,18 @@ class PiecesJustificativesService champs = champs.reject(&:private?) end + champs_id_row_index = champs.filter { _1.row_id.present? }.group_by(&:dossier_id).values.each_with_object({}) do |champs_for_dossier, hash| + champs_for_dossier.group_by(&:stable_id).values.each do |champs_for_stable_id| + champs_for_stable_id.sort_by(&:row_id).each.with_index { |c, index| hash[c.id] = index } + end + end + champs.flat_map do |champ| - champ.piece_justificative_file_attachments.map.with_index do |attachment, index| + champ.piece_justificative_file_attachments.filter { |a| safe_attachment(a) }.map.with_index do |attachment, index| + row_index = champs_id_row_index[champ.id] + if @export_template - @export_template.attachment_and_path(champ.dossier, attachment, index:, row_index: champ.row_index, champ:) + @export_template.attachment_and_path(champ.dossier, attachment, index:, row_index:, champ:) else ActiveStorage::DownloadableFile.pj_and_path(champ.dossier_id, attachment) end diff --git a/spec/services/procedure_export_service_zip_spec.rb b/spec/services/procedure_export_service_zip_spec.rb index 1baace907..e50cce89f 100644 --- a/spec/services/procedure_export_service_zip_spec.rb +++ b/spec/services/procedure_export_service_zip_spec.rb @@ -40,7 +40,7 @@ describe ProcedureExportService do subject end - expect(sql_count).to eq(89) + expect(sql_count).to eq(58) dossier = dossiers.first @@ -58,7 +58,7 @@ describe ProcedureExportService do "export/dossier-#{dossier.id}/libelle-du-champ-2-#{dossier.id}-1-2.png" ] - expect(files.size).to eq(10 * 6 + 1) + expect(files.size).to eq(dossiers.count * 6 + 1) expect(structure - files.map(&:filename)).to be_empty end FileUtils.remove_entry_secure('tmp.zip')