The personal finance app for everyone (by everyone)
Ruby
fix(import): tolerate null Rule names and orphaned rejected transfers (#2775)
pro3958d57c4301f24a
diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rbindex 7a68419c55..c65dbf7d29 100644--- a/app/models/family/data_importer.rb+++ b/app/models/family/data_importer.rb@@ -735,9 +735,15 @@ class Family::DataImporterdef import_rejected_transfers(records)records.each do |record|data = record["data"]- inflow_transaction_id = mapped_id(:transactions, data["inflow_transaction_id"], record_type: "RejectedTransfer")- outflow_transaction_id = mapped_id(:transactions, data["outflow_transaction_id"], record_type: "RejectedTransfer")- next unless inflow_transaction_id && outflow_transaction_id+ # A rejected transfer is an advisory hint that stops two transactions from+ # being re-matched. When either side is missing (e.g. the transaction was+ # deleted after the rejection), skip the row instead of failing the import.+ inflow_transaction_id = mapped_id(:transactions, data["inflow_transaction_id"], record_type: "RejectedTransfer", required: false)+ outflow_transaction_id = mapped_id(:transactions, data["outflow_transaction_id"], record_type: "RejectedTransfer", required: false)+ unless inflow_transaction_id && outflow_transaction_id+ increment_summary("RejectedTransfer", :skipped)+ next+ endrejected_transfer = RejectedTransfer.find_or_create_by!(inflow_transaction_id: inflow_transaction_id,diff --git a/app/models/import/preflight.rb b/app/models/import/preflight.rbindex 20199f80b3..44be89ac77 100644--- a/app/models/import/preflight.rb+++ b/app/models/import/preflight.rb@@ -237,7 +237,11 @@ class Import::Preflightcontent: content).callstats = result.stats- warnings = result.warnings.dup+ # result.warnings are {code, message} hashes internally, but the published+ # OpenAPI contract documents preflight warnings as strings. Surface the+ # human-readable message at the API boundary so the array stays homogeneous and+ # contract-generated clients can still deserialize it.+ warnings = result.warnings.map { |warning| warning.is_a?(Hash) ? warning[:message] : warning }warnings << "No importable records were found." if stats[:rows_count].positive? && (stats[:entity_counts] || {}).values.sum.zero?warnings << "Row count exceeds this import type's publish limit." if stats[:rows_count] > SureImport.max_row_countdiff --git a/app/models/sure_import/preflight.rb b/app/models/sure_import/preflight.rbindex d12eac05cd..68c7335b1d 100644--- a/app/models/sure_import/preflight.rb+++ b/app/models/sure_import/preflight.rb@@ -25,9 +25,14 @@ class SureImport::Preflight"Valuation" => %w[account_id date amount],"Budget" => %w[id start_date end_date],"BudgetCategory" => %w[budget_id category_id],- "Rule" => %w[name]+ "Rule" => %w[id]}.freeze+ # Record types whose references are advisory: the importer skips rows whose+ # referenced records are absent instead of failing, so a dangling reference is+ # a warning rather than a blocking error.+ SOFT_REFERENCE_TYPES = %w[RejectedTransfer].freeze+TAXONOMY_TYPES = { "Category" => :categories, "Tag" => :tags, "Merchant" => :merchants }.freezeSOURCE_ID_TYPES = TAXONOMY_TYPES.merge(@@ -265,7 +270,17 @@ class SureImport::Preflightdef validate_reference(record, type, mapping_key, field, value)return if value.blank?return if @source_ids[mapping_key].include?(value.to_s)- add_error(:missing_reference, "Line #{record[:line_number]} #{type} references missing #{field} #{value.inspect}.")+ interpolations = {+ line: record[:line_number],+ type: type,+ field: field,+ value: value.inspect+ }+ if SOFT_REFERENCE_TYPES.include?(type)+ add_warning(:skipped_missing_reference, I18n.t("sure_import.preflight.skipped_missing_reference", **interpolations))+ else+ add_error(:missing_reference, I18n.t("sure_import.preflight.missing_reference", **interpolations))+ endenddef validate_tag_references(record, type)@@ -309,4 +324,6 @@ class SureImport::Preflightdef blank_required_value?(value) = value.blank?def add_error(code, message) = @errors << { code: code.to_s, message: message }++ def add_warning(code, message) = @warnings << { code: code.to_s, message: message }enddiff --git a/config/locales/models/sure_import/preflight/en.yml b/config/locales/models/sure_import/preflight/en.ymlnew file mode 100644index 0000000000..f446b14f86--- /dev/null+++ b/config/locales/models/sure_import/preflight/en.yml@@ -0,0 +1,6 @@+---+en:+ sure_import:+ preflight:+ missing_reference: "Line %{line} %{type} references missing %{field} %{value}."+ skipped_missing_reference: "Line %{line} %{type} references missing %{field} %{value}. It will be skipped during import."diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rbindex 21ea0d4b7f..552268ee38 100644--- a/test/models/family/data_importer_test.rb+++ b/test/models/family/data_importer_test.rb@@ -1636,6 +1636,45 @@ class Family::DataImporterTest < ActiveSupport::TestCaseassert_equal "Candidate outflow", rejected_transfer.outflow_transaction.entry.nameend+ test "skips rejected transfers with missing transactions under strict import" do+ session = @family.import_sessions.create!(expected_chunks: 1)++ ndjson = build_ndjson([+ {+ type: "Account",+ data: { id: "checking", name: "Checking", balance: "1000", currency: "USD", accountable_type: "Depository" }+ },+ {+ type: "Account",+ data: { id: "savings", name: "Savings", balance: "2500", currency: "USD", accountable_type: "Depository" }+ },+ {+ type: "Transaction",+ data: { id: "rejected-outflow", account_id: "checking", date: "2024-01-20", amount: "25.00", name: "Candidate outflow", currency: "USD", kind: "standard" }+ },+ {+ type: "Transaction",+ data: { id: "rejected-inflow", account_id: "savings", date: "2024-01-20", amount: "-25.00", name: "Candidate inflow", currency: "USD", kind: "standard" }+ },+ {+ type: "RejectedTransfer",+ data: { id: "rejected-valid", inflow_transaction_id: "rejected-inflow", outflow_transaction_id: "rejected-outflow" }+ },+ {+ type: "RejectedTransfer",+ data: { id: "rejected-orphan", inflow_transaction_id: "rejected-inflow", outflow_transaction_id: "missing-outflow" }+ }+ ])++ result = nil+ assert_difference -> { RejectedTransfer.count }, 1 do+ result = Family::DataImporter.new(@family, ndjson, import_session: session).import!+ end++ assert_equal 1, result[:summary].dig("rejected_transfers", "created")+ assert_equal 1, result[:summary].dig("rejected_transfers", "skipped")+ end+test "imports duplicate transfer decisions idempotently with unknown status fallback" dondjson = build_ndjson([{diff --git a/test/models/sure_import_test.rb b/test/models/sure_import_test.rbindex d0a076bf87..2f54486405 100644--- a/test/models/sure_import_test.rb+++ b/test/models/sure_import_test.rb@@ -611,6 +611,23 @@ class SureImportTest < ActiveSupport::TestCaseassert_includes codes, "missing_reference"end+ test "preflight allows null rule names and treats orphaned rejected transfers as warnings" do+ attach_ndjson(build_ndjson([+ { type: "Rule", data: { id: "rule-1", name: nil, resource_type: "transaction" } },+ { type: "RejectedTransfer", data: {+ id: "rejected-1",+ inflow_transaction_id: "missing-inflow",+ outflow_transaction_id: "missing-outflow"+ } }+ ]))++ result = @import.sure_preflight++ assert result.valid?, result.error_message+ assert_empty result.errors+ assert_includes result.warnings.map { |warning| warning[:code] }, "skipped_missing_reference"+ end+test "preflight rejects invalid accountable types through explicit allowlist" doattach_ndjson(build_ndjson([{ type: "Account", data: {@@ -848,6 +865,30 @@ class Import::PreflightTest < ActiveSupport::TestCaseassert_includes payload[:warnings], "No importable records were found."end+ test "SureImport preflight serializes hash warnings as strings at the API boundary" do+ result = Struct.new(:stats, :errors, :warnings, keyword_init: true) do+ def valid?+ true+ end+ end.new(+ stats: { rows_count: 2, valid_rows_count: 2, invalid_rows_count: 0, entity_counts: { accounts: 2 } },+ errors: [],+ warnings: [ { code: "skipped_missing_reference", message: "Skipped an orphaned rejected transfer." } ]+ )+ SureImport::Preflight.stubs(:new).returns(stub(call: result))++ response = Import::Preflight.new(+ family: @family,+ params: { type: "SureImport", raw_file_content: "{}" }+ ).call+ payload = response.payload[:data]++ # The contract documents warnings as strings, so the {code, message} hash must+ # surface as its message -- never leak the hash into the response.+ assert payload[:warnings].all? { |warning| warning.is_a?(String) }, "preflight warnings must be strings"+ assert_includes payload[:warnings], "Skipped an orphaned rejected transfer."+ end+privatedef build_ndjson(records)