The personal finance app for everyone (by everyone)
Ruby
Preset the sign convention when importing a Sure CSV export (#4754)
GFRcd5ad7e037dc
diff --git a/app/controllers/import/uploads_controller.rb b/app/controllers/import/uploads_controller.rbindex d3cad01b32..f290bf1a9a 100644--- a/app/controllers/import/uploads_controller.rb+++ b/app/controllers/import/uploads_controller.rb@@ -24,6 +24,7 @@ class Import::UploadsController < ApplicationControllerelsif csv_valid?(csv_str)@import.account = import_account_id.present? ? accessible_accounts.find(import_account_id) : nil@import.assign_attributes(raw_file_str: csv_str, col_sep: upload_params[:col_sep])+ @import.preset_for_uploaded_csv@import.save!(validate: false)redirect_to import_configuration_path(@import, template_hint: true), notice: t("imports.create.csv_uploaded")diff --git a/app/controllers/imports_controller.rb b/app/controllers/imports_controller.rbindex 0baa11f14f..eff2849d7a 100644--- a/app/controllers/imports_controller.rb+++ b/app/controllers/imports_controller.rb@@ -130,7 +130,9 @@ class ImportsController < ApplicationController# Stream reading is not fully applicable here as we store the raw string in the DB,# but we have validated size beforehand to prevent memory exhaustion from massive files.- import.update!(raw_file_str: file.read)+ import.raw_file_str = file.read+ import.preset_for_uploaded_csv+ import.save!redirect_to import_configuration_path(import), notice: t("imports.create.csv_uploaded")elsediff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rbindex 888c395bae..aec967c0e9 100644--- a/app/models/family/data_exporter.rb+++ b/app/models/family/data_exporter.rb@@ -3,6 +3,7 @@ require "csv"class Family::DataExporterEXPORT_VERSION = 2+ TRANSACTIONS_CSV_HEADERS = [ "date", "account_name", "amount", "name", "category", "tags", "notes", "currency" ].freezedef initialize(family)@family = family@@ -81,7 +82,7 @@ class Family::DataExporterdef generate_transactions_csvCSV.generate do |csv|- csv << [ "date", "account_name", "amount", "name", "category", "tags", "notes", "currency" ]+ csv << TRANSACTIONS_CSV_HEADERS# Only export transactions from accounts belonging to this family# Exclude split parents (export children instead)diff --git a/app/models/import.rb b/app/models/import.rbindex 0f05a6fcd3..e0a38a7833 100644--- a/app/models/import.rb+++ b/app/models/import.rb@@ -522,6 +522,10 @@ class Import < ApplicationRecordfamily.accounts.empty? && has_unassigned_account?end+ # Hook for subclasses that recognise a known file format on upload+ def preset_for_uploaded_csv+ end+# Used to optionally pre-fill the configuration for the current importdef suggested_templatefamily.imports@@ -532,16 +536,18 @@ class Import < ApplicationRecordenddef apply_template!(import_template)- update!(- import_template.attributes.slice(- "date_col_label", "amount_col_label", "name_col_label",- "category_col_label", "tags_col_label", "account_col_label",- "qty_col_label", "ticker_col_label", "price_col_label",- "entity_type_col_label", "notes_col_label", "currency_col_label",- "date_format", "signage_convention", "number_format",- "exchange_operating_mic_col_label",- "rows_to_skip"- )+ update!(template_attributes(import_template))+ end++ def template_attributes(import_template)+ import_template.attributes.slice(+ "date_col_label", "amount_col_label", "name_col_label",+ "category_col_label", "tags_col_label", "account_col_label",+ "qty_col_label", "ticker_col_label", "price_col_label",+ "entity_type_col_label", "notes_col_label", "currency_col_label",+ "date_format", "signage_convention", "number_format",+ "exchange_operating_mic_col_label",+ "rows_to_skip")enddiff --git a/app/models/transaction_import.rb b/app/models/transaction_import.rbindex 8b93431e68..8679996584 100644--- a/app/models/transaction_import.rb+++ b/app/models/transaction_import.rb@@ -1,4 +1,18 @@class TransactionImport < Import+ SURE_EXPORT_SETTINGS = {+ amount_type_strategy: "signed_amount",+ signage_convention: "inflows_negative",+ date_format: "%Y-%m-%d",+ number_format: "1,234.56",+ rows_to_skip: 0+ }.freeze++ # The column label for each column of Family::DataExporter::TRANSACTIONS_CSV_HEADERS, in its order.+ SURE_EXPORT_LABELS = %i[+ date_col_label account_col_label amount_col_label name_col_label+ category_col_label tags_col_label notes_col_label currency_col_label+ ].zip(Family::DataExporter::TRANSACTIONS_CSV_HEADERS).to_h.freeze+def import!transaction domappings.each(&:create_mappable!)@@ -116,4 +130,58 @@ class TransactionImport < Importcsv.delete("account") if account.present?csvend++ # Sure's own transactions.csv export keeps the stored sign (outflows positive),+ # ISO dates and plain decimals, so a re-import of it needs matching settings.+ # Call after assigning a new raw_file_str and before saving it.+ def preset_for_uploaded_csv+ if sure_export_csv?(raw_file_str, col_sep)+ assign_attributes(SURE_EXPORT_SETTINGS)+ elsif sure_export_csv?(raw_file_str_was, col_sep_was)+ assign_attributes(amount_type_strategy: "signed_amount", signage_convention: "inflows_positive", date_format: family.date_format)+ end+ end++ # A template from another bank's file would bring its own sign, formats,+ # column names and skipped rows, none of which fit a Sure export.+ def apply_template!(import_template)+ return super unless sure_export_csv?(raw_file_str, col_sep)++ update!(template_attributes(import_template).merge(SURE_EXPORT_SETTINGS.stringify_keys, sure_export_labels.stringify_keys))+ end++ private+ def sure_export_csv?(csv_str, separator)+ # A dropped file is read as binary bytes; read it as UTF-8 so a BOM or+ # non-ASCII characters elsewhere in the file cannot raise.+ headers = header_record(utf8_without_bom(csv_str), separator).map { |header| export_header_key(header) }+ headers.any? && (Family::DataExporter::TRANSACTIONS_CSV_HEADERS - headers).empty?+ end++ # Column labels must match the parsed headers exactly, which keep a BOM and+ # the file's own spelling (e.g. "Date"), so map each export column to it.+ # Read from the file itself: a Sure export skips no rows, whatever+ # rows_to_skip the import had before the template reset it.+ def sure_export_labels+ headers = header_record(raw_file_str, col_sep)+ SURE_EXPORT_LABELS.transform_values do |label|+ headers.find { |header| export_header_key(header) == label } || label+ end+ end++ # The first CSV record, read like Import.parse_csv_str reads headers:+ # leading blank lines are skipped and a quoted field may span lines.+ def header_record(csv_str, separator)+ CSV.new(csv_str.to_s.strip, col_sep: separator.presence || ",", liberal_parsing: true).shift.to_a+ rescue CSV::MalformedCSVError+ []+ end++ def export_header_key(header)+ utf8_without_bom(header).strip.downcase+ end++ def utf8_without_bom(str)+ str.to_s.dup.force_encoding(Encoding::UTF_8).scrub.delete_prefix("\uFEFF")+ endenddiff --git a/test/controllers/import/uploads_controller_test.rb b/test/controllers/import/uploads_controller_test.rbindex fd203a23e0..cc3e65a4bf 100644--- a/test/controllers/import/uploads_controller_test.rb+++ b/test/controllers/import/uploads_controller_test.rb@@ -35,6 +35,46 @@ class Import::UploadsControllerTest < ActionDispatch::IntegrationTestassert_equal "CSV uploaded successfully.", flash[:notice]end+ test "re-importing a Sure transactions.csv export keeps transfer directions" do+ family = @user.family+ source = family.accounts.create!(name: "Export Source", accountable: Depository.new, balance: 1000, currency: "USD")+ destination = family.accounts.create!(name: "Export Destination", accountable: Depository.new, balance: 0, currency: "USD")+ outflow = source.entries.create!(name: "Transfer to savings", date: Date.parse("2024-05-17"), amount: 100, currency: "USD", entryable: Transaction.new(kind: "funds_movement"))+ inflow = destination.entries.create!(name: "Transfer from checking", date: Date.parse("2024-05-17"), amount: -100, currency: "USD", entryable: Transaction.new(kind: "funds_movement"))+ Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable, status: "confirmed")++ exported_csv = nil+ Zip::File.open_buffer(Family::DataExporter.new(family).generate_export) do |zip|+ exported_csv = zip.read("transactions.csv")+ end++ patch import_upload_url(@import), params: { import: { raw_file_str: exported_csv, col_sep: "," } }++ get import_configuration_url(@import)+ assert_select 'select[name="import[signage_convention]"] option[selected][value="inflows_negative"]'+ assert_select 'select[name="import[date_format]"] option[selected][value="%Y-%m-%d"]'++ # Submit the column mapping and keep every preselected setting, as the form does+ @import.reload+ patch import_configuration_url(@import), params: {+ import: {+ date_col_label: "date",+ date_format: @import.date_format,+ amount_col_label: "amount",+ number_format: @import.number_format,+ amount_type_strategy: @import.amount_type_strategy,+ signage_convention: @import.signage_convention,+ account_col_label: "account_name",+ name_col_label: "name",+ currency_col_label: "currency"+ }+ }++ rows = @import.reload.rows+ assert_equal outflow.amount, rows.find_by!(name: outflow.name, account: source.name).signed_amount+ assert_equal inflow.amount, rows.find_by!(name: inflow.name, account: destination.name).signed_amount+ end+test "account select does not leak unshared family accounts (#1803)" dosign_in users(:family_member)diff --git a/test/controllers/imports_controller_test.rb b/test/controllers/imports_controller_test.rbindex 422fbfedb0..a5b3dec8fc 100644--- a/test/controllers/imports_controller_test.rb+++ b/test/controllers/imports_controller_test.rb@@ -120,6 +120,43 @@ class ImportsControllerTest < ActionDispatch::IntegrationTestassert_redirected_to import_upload_url(Import.all.ordered.first)end+ test "dropping a Sure transactions.csv export presets the export sign convention" do+ exported_csv = "#{Family::DataExporter::TRANSACTIONS_CSV_HEADERS.join(",")}\n2024-05-15,Checking Account,42.5,Grocery,,,,USD\n"++ post imports_url, params: {+ import: {+ type: "TransactionImport",+ import_file: Rack::Test::UploadedFile.new(StringIO.new(exported_csv), "text/csv", original_filename: "transactions.csv")+ }+ }++ import = Import.all.ordered.first+ assert_redirected_to import_configuration_url(import)+ assert_equal "inflows_negative", import.signage_convention+ assert_equal "%Y-%m-%d", import.date_format+ end++ test "dropping a CSV with non-ASCII characters presets by header and does not fail" do+ header = Family::DataExporter::TRANSACTIONS_CSV_HEADERS.join(",")+ [ "#{header}\n2024-05-15,Checking Account,42.5,Café,,,,USD\n", "\uFEFFdate,amount,name\n2024-05-15,5,Café\n" ].each do |csv|+ file = Tempfile.new([ "upload", ".csv" ], binmode: true)+ file.write(csv)+ file.rewind++ assert_difference "Import.count", 1 do+ post imports_url, params: {+ import: { type: "TransactionImport", import_file: Rack::Test::UploadedFile.new(file.path, "text/csv") }+ }+ end++ import = Import.all.ordered.first+ assert_redirected_to import_configuration_url(import)+ assert_equal csv.start_with?(header) ? "inflows_negative" : "inflows_positive", import.signage_convention+ ensure+ file&.close!+ end+ end+test "create with an empty request body redirects back with an alert" doassert_no_difference "Import.count" dopost imports_urldiff --git a/test/models/transaction_import_test.rb b/test/models/transaction_import_test.rbindex 13d638dbdb..b715b3d497 100644--- a/test/models/transaction_import_test.rb+++ b/test/models/transaction_import_test.rb@@ -7,6 +7,111 @@ class TransactionImportTest < ActiveSupport::TestCase@subject = @import = imports(:transaction)end+ test "presets the export settings for a Sure transactions.csv export" do+ @import.amount_type_strategy = "custom_column"+ @import.raw_file_str = "\uFEFF#{Family::DataExporter::TRANSACTIONS_CSV_HEADERS.join(",").upcase},counterparty_iban\n2024-05-15,Checking,42.5,Grocery,,,,USD,\n"++ @import.preset_for_uploaded_csv++ assert_equal "signed_amount", @import.amount_type_strategy+ assert_equal "inflows_negative", @import.signage_convention+ assert_equal "%Y-%m-%d", @import.date_format+ assert_equal "1,234.56", @import.number_format+ end++ test "does not treat the transaction import template as a Sure export" do+ @import.raw_file_str = @import.csv_template.to_csv++ @import.preset_for_uploaded_csv++ assert_equal "inflows_positive", @import.signage_convention+ end++ test "keeps a chosen sign convention when one non-Sure CSV replaces another" do+ @import.update!(raw_file_str: "date,amount,payee\n2024-05-14,-10,Coffee\n", signage_convention: "inflows_negative")+ @import.raw_file_str = "date,amount,name\n2024-05-15,-42.5,Grocery\n"++ @import.preset_for_uploaded_csv++ assert_equal "inflows_negative", @import.signage_convention+ end++ test "restores the default sign convention when a Sure export is replaced by another CSV" do+ @import.update!(raw_file_str: "#{Family::DataExporter::TRANSACTIONS_CSV_HEADERS.join(",")}\n2024-05-15,Checking,42.5,Grocery,,,,USD\n")+ @import.update!(TransactionImport::SURE_EXPORT_SETTINGS)+ @import.family.update!(date_format: "%d.%m.%Y")+ @import.assign_attributes(raw_file_str: "date;amount;name\n2024-05-15;-42,5;Grocery\n", col_sep: ";")++ @import.preset_for_uploaded_csv++ assert_equal "signed_amount", @import.amount_type_strategy+ assert_equal "inflows_positive", @import.signage_convention+ assert_equal "%d.%m.%Y", @import.date_format+ end++ test "keeps the Sure export sign convention when a template from another import is applied" do+ template = imports(:transaction).dup+ template.update!(status: "complete", signage_convention: "inflows_positive", date_format: "%m/%d/%Y", rows_to_skip: 2, date_col_label: "Buchungstag", amount_col_label: "Betrag")+ @import = families(:dylan_family).imports.create!(type: "TransactionImport", raw_file_str: "#{Family::DataExporter::TRANSACTIONS_CSV_HEADERS.join(",")}\n2024-05-15,Checking,42.5,Grocery,,,,USD\n")++ @import.apply_template!(template)++ assert_equal "inflows_negative", @import.reload.signage_convention+ assert_equal "%Y-%m-%d", @import.date_format+ assert_equal 0, @import.rows_to_skip+ assert_equal "date", @import.date_col_label+ assert_equal "amount", @import.amount_col_label+ end++ test "recognises a Sure export after leading blank lines" do+ @import.raw_file_str = "\n\n#{Family::DataExporter::TRANSACTIONS_CSV_HEADERS.join(",")}\n2024-05-15,Checking,42.5,Grocery,,,,USD\n"++ @import.preset_for_uploaded_csv++ assert_equal "inflows_negative", @import.signage_convention+ end++ test "maps template labels to the export's own header spelling" do+ template = imports(:transaction).dup+ template.update!(status: "complete", date_col_label: "Buchungstag")+ headers = Family::DataExporter::TRANSACTIONS_CSV_HEADERS.map(&:capitalize)+ @import = families(:dylan_family).imports.create!(type: "TransactionImport", raw_file_str: "\uFEFF#{headers.join(",")}\n2024-05-15,Checking,42.5,Grocery,,,,USD\n")++ @import.apply_template!(template)++ assert_equal "\uFEFFDate", @import.reload.date_col_label+ assert_equal "Amount", @import.amount_col_label+ assert_equal "2024-05-15", @import.csv_rows.first[@import.date_col_label]+ end++ test "recognises a Sure export whose extra header holds a quoted line break" do+ @import.raw_file_str = "#{Family::DataExporter::TRANSACTIONS_CSV_HEADERS.join(",")},\"counterparty\nIBAN\"\n2024-05-15,Checking,42.5,Grocery,,,,USD,\n"++ @import.preset_for_uploaded_csv++ assert_equal "inflows_negative", @import.signage_convention+ end++ test "maps template labels from the export's header even when rows were skipped before" do+ template = imports(:transaction).dup+ template.update!(status: "complete")+ @import = families(:dylan_family).imports.create!(type: "TransactionImport", rows_to_skip: 1,+ raw_file_str: "#{Family::DataExporter::TRANSACTIONS_CSV_HEADERS.map(&:capitalize).join(",")}\n2024-05-15,Checking,42.5,Grocery,,,,USD\n")++ @import.apply_template!(template)++ assert_equal 0, @import.reload.rows_to_skip+ assert_equal "Date", @import.date_col_label+ assert_equal "Account_name", @import.account_col_label+ end++ test "ignores blank and unparseable CSV headers when presetting the sign convention" do+ @import.raw_file_str = "\"date,\"amount\n"++ assert_nothing_raised { @import.preset_for_uploaded_csv }+ assert_equal "inflows_positive", @import.signage_convention+ end+test "uploaded? if raw_file_str is present" do@import.expects(:raw_file_str).returns("test").onceassert @import.uploaded?