The personal finance app for everyone (by everyone)
Ruby
QIF Import: Improve reading of account types (#5491)
Sailing749004895d509c
diff --git a/app/controllers/import/qif_category_selections_controller.rb b/app/controllers/import/qif_category_selections_controller.rbindex 19493dd6fa..11910d3bc9 100644--- a/app/controllers/import/qif_category_selections_controller.rb+++ b/app/controllers/import/qif_category_selections_controller.rb@@ -16,6 +16,7 @@ class Import::QifCategorySelectionsController < ApplicationController@tag_counts = compute_tag_counts@split_categories = @import.split_categories@has_split_transactions = @import.has_split_transactions?+ @unknown_account_types = @import.unknown_qif_account_typesenddef updatediff --git a/app/models/concerns/qif_parser.rb b/app/models/concerns/qif_parser.rbindex 84873c4411..24c7b07ab2 100644--- a/app/models/concerns/qif_parser.rb+++ b/app/models/concerns/qif_parser.rb@@ -12,6 +12,10 @@# !Type:CCard / !Type:Bank / !Type:Cash / !Type:Oth L – transactions# !Type:Invst – investment transactions#+# Account sections with a type outside TRANSACTION_TYPES (e.g. "Oth T" from+# Lexware FinanzManager) are read like "Bank" sections; see+# unknown_account_types.+## An optional "!Option:MDY" or "!Option:DMY" line declares whether numeric# dates put the month or the day first.#@@ -45,6 +49,12 @@ module QifParserINFLOW_TRANSACTION_ACTIONS = %w[Div IntInc XIn CGLong CGShort MiscInc].freezeOUTFLOW_TRANSACTION_ACTIONS = %w[XOut MiscExp].freeze+ # Sections that hold lists rather than an account's transactions.+ NON_ACCOUNT_TYPES = %w[Tag Cat Class Security Prices Memorized].freeze++ # Account sections of a type outside TRANSACTION_TYPES are read as this type.+ FALLBACK_ACCOUNT_TYPE = "Bank"+ParsedTransaction = Struct.new(:date, :amount, :payee, :memo, :category, :tags, :check_num, :cleared,:split, :split_lines, :account_name, :account_type,@@ -109,16 +119,28 @@ module QifParserend# Returns the transaction account type string (e.g. "CCard", "Bank", "Invst").- # Skips metadata sections (Tag, Cat, Security, Prices) which are not account data.+ # Skips sections that are not account data (NON_ACCOUNT_TYPES); unknown+ # account types are returned as FALLBACK_ACCOUNT_TYPE.def self.account_type(content)return nil if content.blank?content.scan(/^!Type:(.+)/i).flatten- .map(&:strip)- .reject { |t| %w[Tag Cat Security Prices].include?(t) }+ .filter_map { |type| section_account_type(type) }.firstend+ # Returns the distinct account section types (as written in the file) that+ # are not in TRANSACTION_TYPES and are read as FALLBACK_ACCOUNT_TYPE.+ def self.unknown_account_types(content)+ return [] unless valid?(content)++ content = normalize_encoding(content)++ content.scan(/^!Type:(.+)/i).flatten.map(&:strip).uniq.select do |type|+ known_type(type, NON_ACCOUNT_TYPES).nil? && known_type(type, TRANSACTION_TYPES).nil?+ end+ end+# Returns "MDY" or "DMY" when the file declares its date order with an# "!Option:MDY" or "!Option:DMY" line, otherwise nil.def self.date_order(content)@@ -323,10 +345,10 @@ module QifParserendif (match = line.match(/^!Type:(.+)/i))- type = match[1].strip+ type = section_account_type(match[1])section_content, index = collect_section_lines(lines, index + 1)- if TRANSACTION_TYPES.include?(type)+ if typesections << {type: type,account: current_account,@@ -344,6 +366,31 @@ module QifParserendprivate_class_method :transaction_sections+ # Maps a "!Type:" value to its TRANSACTION_TYPES entry, ignoring case and+ # surrounding spaces. Returns nil for blank values and NON_ACCOUNT_TYPES and+ # FALLBACK_ACCOUNT_TYPE for any other type.+ def self.section_account_type(raw_type)+ type = raw_type.to_s.strip+ return nil if type.empty? || known_type(type, NON_ACCOUNT_TYPES)++ known_type(type, TRANSACTION_TYPES) || FALLBACK_ACCOUNT_TYPE+ end+ private_class_method :section_account_type++ # The "T" type of an "!Account" record overrides the type of the sections+ # that follow it, so only a standard type (matched regardless of case) is+ # kept. Any other value is dropped and the section type applies.+ def self.standard_account_type(raw_type)+ type = raw_type.to_s.strip+ known_type(type, TRANSACTION_TYPES) unless type.empty?+ end+ private_class_method :standard_account_type++ def self.known_type(type, types)+ types.find { |known| known.casecmp?(type.strip) }+ end+ private_class_method :known_type+def self.collect_section_lines(lines, index)section_lines = []@@ -361,7 +408,7 @@ module QifParserParsedAccount.new(name: record["N"].strip,- account_type: record["T"]&.strip,+ account_type: standard_account_type(record["T"]),description: record["D"]&.strip)enddiff --git a/app/models/qif_import.rb b/app/models/qif_import.rbindex 6edb8357d4..3bd93bfee4 100644--- a/app/models/qif_import.rb+++ b/app/models/qif_import.rb@@ -100,6 +100,12 @@ class QifImport < Import@qif_account_type = raw_file_str.present? ? QifParser.account_type(raw_file_str) : nilend+ # Account types in the file that are not standard QIF account types and are+ # imported like a bank account (e.g. "Oth T").+ def unknown_qif_account_types+ raw_file_str.present? ? QifParser.unknown_account_types(raw_file_str) : []+ end+def qif_accounts@qif_accounts ||= raw_file_str.present? ? QifParser.parse_accounts(raw_file_str) : []enddiff --git a/app/views/import/qif_category_selections/show.html.erb b/app/views/import/qif_category_selections/show.html.erbindex b1a1c36212..94f38adfb2 100644--- a/app/views/import/qif_category_selections/show.html.erb+++ b/app/views/import/qif_category_selections/show.html.erb@@ -40,6 +40,18 @@<% end %><% end %>+ <%# ── Unknown account types ───────────────────────────────── %>+ <% if @unknown_account_types.any? %>+ <%= render DS::Alert.new(+ variant: :warning,+ title: t(".unknown_account_type_title", count: @unknown_account_types.size),+ message: t(".unknown_account_type_description",+ count: @unknown_account_types.size,+ types: @unknown_account_types.map { |type| t(".unknown_account_type_name", type: type) }.to_sentence,+ product_name: product_name)+ ) %>+ <% end %>+<%# ── Split transaction warning ────────────────────────────── %><% if @has_split_transactions %><div class="flex gap-3 items-start rounded-xl border border-warning bg-warning/5 px-4 py-3">diff --git a/config/locales/views/imports/de.yml b/config/locales/views/imports/de.ymlindex 1e4cd25eb8..fd24de4206 100644--- a/config/locales/views/imports/de.yml+++ b/config/locales/views/imports/de.yml@@ -25,6 +25,13 @@ de:split_warning_title: Aufgeteilte Buchungen erkanntsplit_warning_description: "Diese QIF-Datei enthält aufgeteilte Buchungen. Aufgeteilte Buchungen werden noch nicht unterstützt – jede aufgeteilte Buchung wird als einzelne Buchung mit ihrem Gesamtbetrag und ohne Kategorie importiert. Die einzelnen Aufteilungsdetails werden nicht übernommen."split_badge: aufgeteilt+ unknown_account_type_name: "„%{type}“"+ unknown_account_type_title:+ one: Unbekannter Kontotyp+ other: Unbekannte Kontotypen+ unknown_account_type_description:+ one: "Diese QIF-Datei enthält den Kontotyp %{types}, den %{product_name} nicht kennt. Die Buchungen werden wie bei einem Bankkonto importiert."+ other: "Diese QIF-Datei enthält die Kontotypen %{types}, die %{product_name} nicht kennt. Die Buchungen werden wie bei einem Bankkonto importiert."update:success: Kategorien und Tags gespeichert.cleans:diff --git a/config/locales/views/imports/en.yml b/config/locales/views/imports/en.ymlindex 8e34c2903b..937844cbd0 100644--- a/config/locales/views/imports/en.yml+++ b/config/locales/views/imports/en.yml@@ -24,6 +24,13 @@ en:split_warning_title: Split transactions detectedsplit_warning_description: "This QIF file contains split transactions. Review the detected split categories and tags below before importing."split_badge: split+ unknown_account_type_name: "“%{type}”"+ unknown_account_type_title:+ one: Unknown account type+ other: Unknown account types+ unknown_account_type_description:+ one: "This QIF file contains the account type %{types}, which %{product_name} doesn't recognize. Its transactions will be imported like a bank account."+ other: "This QIF file contains the account types %{types}, which %{product_name} doesn't recognize. Their transactions will be imported like a bank account."empty_state_primary: No categories or tags were found in this QIF file.empty_state_secondary: All transactions will be imported without categories or tags.submit: Continue to reviewdiff --git a/test/controllers/import/qif_category_selections_controller_test.rb b/test/controllers/import/qif_category_selections_controller_test.rbnew file mode 100644index 0000000000..37f147000d--- /dev/null+++ b/test/controllers/import/qif_category_selections_controller_test.rb@@ -0,0 +1,46 @@+require "test_helper"++class Import::QifCategorySelectionsControllerTest < ActionDispatch::IntegrationTest+ setup do+ sign_in @user = users(:family_admin)+ @account = accounts(:depository)+ end++ test "show warns about account types that are imported like a bank account" do+ import = qif_import_with(<<~QIF)+ !Type:Oth T+ D1/ 1'20+ T-25.00+ PGrocery Store+ ^+ QIF++ get import_qif_category_selection_url(import)++ assert_response :success+ assert_select "p", text: /Unknown account type/+ assert_select "div", text: /This QIF file contains the account type “Oth T”/+ end++ test "show does not warn about standard account types" do+ import = qif_import_with(<<~QIF)+ !Type:Bank+ D1/ 1'20+ T-25.00+ PGrocery Store+ ^+ QIF++ get import_qif_category_selection_url(import)++ assert_response :success+ assert_select "p", text: /Unknown account type/, count: 0+ end++ private+ def qif_import_with(content)+ import = QifImport.create!(family: @user.family, account: @account, raw_file_str: content)+ import.generate_rows_from_csv+ import+ end+enddiff --git a/test/models/qif_import_test.rb b/test/models/qif_import_test.rbindex 87552caf5c..f67e8a9b60 100644--- a/test/models/qif_import_test.rb+++ b/test/models/qif_import_test.rb@@ -319,6 +319,108 @@ class QifImportTest < ActiveSupport::TestCaseassert_equal "Bank", QifParser.account_type(qif)end+ # Lexware FinanzManager exports some accounts with the non-standard type "Oth T".+ QIF_WITH_UNKNOWN_ACCOUNT_TYPE = <<~QIF+ !Type:Cat+ NFood+ DFood expenses+ ^+ !Type:Oth T+ D1/ 1'20+ T500.00+ POpening Balance+ L[Tagesgeld]+ ^+ D3/ 1'20+ T-25.00+ PGrocery Store+ LFood+ ^+ QIF++ test "account_type reads an unknown account type as Bank" do+ assert_equal "Bank", QifParser.account_type(QIF_WITH_UNKNOWN_ACCOUNT_TYPE)+ end++ test "account_type ignores Class and Memorized sections" do+ qif = "!Type:Class\nNBusiness\n^\n!Type:Memorized\nKC\nPRent\n^\n!Type:CCard\nD1/1'24\nT-10.00\nPTest\n^\n"+ assert_equal "CCard", QifParser.account_type(qif)+ assert_empty QifParser.unknown_account_types(qif)+ end++ test "account_type matches standard account types regardless of case" do+ qif = "!Type:ccard\nD1/1'24\nT-10.00\nPTest\n^\n"++ assert_equal "CCard", QifParser.account_type(qif)+ assert_empty QifParser.unknown_account_types(qif)+ assert_equal [ "CCard" ], QifParser.parse(qif).map(&:account_type)+ end++ test "account metadata types are matched like section types" do+ qif = <<~QIF+ !Account+ NBrokerage+ Tinvst+ ^+ !Type:invst+ D1/2'24+ NBuy+ YACME+ I10.00+ Q2+ T20.00+ ^+ !Account+ NTagesgeld+ TOth T+ ^+ !Type:Oth T+ D1/3'24+ T-5.00+ PKiosk+ ^+ QIF++ assert_equal [ "Invst", nil ], QifParser.parse_accounts(qif).map(&:account_type)+ assert_equal [ "Invst" ], QifParser.parse_investment_transactions(qif).map(&:account_type)+ assert_equal [ [ "Kiosk", "Bank" ] ], QifParser.parse(qif).map { |t| [ t.payee, t.account_type ] }+ assert_equal [ "Oth T" ], QifParser.unknown_account_types(qif)+ end++ test "an unknown account metadata type leaves the section type in place" do+ qif = <<~QIF+ !Account+ NVisa+ TOth T+ ^+ !Type:CCard+ D1/3'24+ T-5.00+ PKiosk+ ^+ QIF++ assert_equal [ "CCard" ], QifParser.parse(qif).map(&:account_type)+ assert_empty QifParser.unknown_account_types(qif)+ end++ test "unknown_account_types lists each non-standard account type once" do+ qif = QIF_WITH_UNKNOWN_ACCOUNT_TYPE + "!Type:Oth T\nD4/1'20\nT-5.00\nPKiosk\n^\n!Type:Bank\nD5/1'20\nT-1.00\nPBakery\n^\n"++ assert_equal [ "Oth T" ], QifParser.unknown_account_types(qif)+ assert_empty QifParser.unknown_account_types(SAMPLE_QIF)+ assert_empty QifParser.unknown_account_types(nil)+ end++ test "parse reads the transactions of an unknown account type like a bank account" do+ transactions = QifParser.parse(QIF_WITH_UNKNOWN_ACCOUNT_TYPE)++ assert_equal [ "Grocery Store" ], transactions.map(&:payee)+ assert_equal [ "Bank" ], transactions.map(&:account_type)+ assert_equal BigDecimal("500"), QifParser.parse_opening_balance(QIF_WITH_UNKNOWN_ACCOUNT_TYPE)[:amount]+ assert_equal [ "1/1/2020", "3/1/2020" ], QifParser.extract_raw_dates(QIF_WITH_UNKNOWN_ACCOUNT_TYPE)+ end+test "parse_accounts extracts QIF account metadata" doaccounts = QifParser.parse_accounts(QIF_WITH_ACCOUNTS)@@ -573,6 +675,29 @@ class QifImportTest < ActiveSupport::TestCaseassert_equal "CCard", @import.qif_account_typeend+ test "an unknown account type is imported like a bank account" do+ @import.update!(raw_file_str: QIF_WITH_UNKNOWN_ACCOUNT_TYPE)+ @import.generate_rows_from_csv+ @import.sync_mappings++ assert_equal "Bank", @import.qif_account_type+ assert_equal [ "Oth T" ], @import.unknown_qif_account_types+ assert_not_empty @import.valid_date_formats_with_preview+ assert_equal [ "Grocery Store" ], @import.rows.map(&:name)+ assert_equal [ "Food" ], @import.row_categories++ @import.import!++ manager = Account::OpeningBalanceManager.new(@account)+ assert_equal Date.new(2020, 1, 1), manager.opening_date+ assert_equal BigDecimal("500"), manager.opening_balance+ end++ test "unknown_qif_account_types is empty for standard QIF files" do+ @import.update!(raw_file_str: SAMPLE_QIF)+ assert_empty @import.unknown_qif_account_types+ end+test "row_categories excludes blank categories" do@import.update!(raw_file_str: SAMPLE_QIF)@import.generate_rows_from_csv