The personal finance app for everyone (by everyone)
Ruby
QIF Import: Read the QIF date order from !Option:MDY and !Option:DMY (#5400)
Sailing74ad3da5f642aa
diff --git a/app/models/concerns/qif_parser.rb b/app/models/concerns/qif_parser.rbindex b962a59750..84873c4411 100644--- a/app/models/concerns/qif_parser.rb+++ b/app/models/concerns/qif_parser.rb@@ -12,6 +12,9 @@# !Type:CCard / !Type:Bank / !Type:Cash / !Type:Oth L – transactions# !Type:Invst – investment transactions#+# An optional "!Option:MDY" or "!Option:DMY" line declares whether numeric+# dates put the month or the day first.+## Transaction field codes:# D date M/ D'YY or MM/DD'YYYY# T amount may include commas, e.g. "-1,234.56"@@ -116,6 +119,17 @@ module QifParser.firstend+ # 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)+ return nil if content.blank?++ content = normalize_encoding(content)+ content = normalize_line_endings(content).delete_prefix("\uFEFF")++ content.match(/^!Option:(MDY|DMY)[ \t]*$/i)&.captures&.first&.upcase+ end+# Parses all transactions from the file, excluding the Opening Balance entry.# Returns an array of ParsedTransaction structs.def self.parse(content, date_format: "%m/%d/%Y")@@ -542,7 +556,7 @@ module QifParsertry_parse_date(date_str, date_format: date_format)end- # Extracts all raw date strings from D-fields in transaction sections only.+ # Extracts all raw date strings from D-fields in every transaction section.# Skips metadata sections (Cat, Tag, Security) where D means "description".# Used by Import.detect_date_format to sample dates before parsing.def self.extract_raw_dates(content)@@ -551,8 +565,7 @@ module QifParsercontent = normalize_encoding(content)content = normalize_line_endings(content)- transaction_sections = TRANSACTION_TYPES.filter_map { |type| extract_section(content, type) }- transaction_sections.flat_map { |section| section.scan(/^D(.+)$/i).flatten }+ transaction_sections(content).flat_map { |section| section[:content].scan(/^D(.+)$/i).flatten }.map { |d| normalize_qif_date(d) }.compactenddiff --git a/app/models/import.rb b/app/models/import.rbindex a4fcfbb168..284bc727e9 100644--- a/app/models/import.rb+++ b/app/models/import.rb@@ -572,7 +572,7 @@ class Import < ApplicationRecordfirst_sample = raw_date_samples.find(&:present?)return [] if first_sample.blank?- Family::DATE_FORMATS.filter_map do |label, fmt|+ date_format_options.filter_map do |label, fmt|parsed = try_parse_date_sample(first_sample, format: fmt)next unless parsednext unless self.class.reasonable_date_range.cover?(Date.parse(parsed))@@ -581,6 +581,12 @@ class Import < ApplicationRecordendend+ # [label, strptime format] pairs offered by #valid_date_formats_with_preview.+ # Subclasses can override to offer formats only their file type uses.+ def date_format_options+ Family::DATE_FORMATS+ end+# Returns raw date strings from the import file for format detection/preview.# Subclasses should override to extract dates from their specific format.def raw_date_samplesdiff --git a/app/models/qif_import.rb b/app/models/qif_import.rbindex 02375f08bc..6edb8357d4 100644--- a/app/models/qif_import.rb+++ b/app/models/qif_import.rb@@ -1,4 +1,10 @@class QifImport < Import+ # Month-first dates with dots (e.g. "7.10.13" for July 10) occur in QIF+ # exports that declare "!Option:MDY" but have no Family::DATE_FORMATS entry.+ QIF_ONLY_DATE_FORMATS = [+ [ "MM.DD.YYYY", "%m.%d.%Y" ]+ ].freeze+after_create :set_default_config# The date format used to parse the raw QIF file's D-fields (e.g. "%m/%d/%Y").@@ -155,6 +161,10 @@ class QifImport < ImportQifParser.try_parse_date(sample, date_format: format)end+ def date_format_options+ Family::DATE_FORMATS + QIF_ONLY_DATE_FORMATS+ end+privatedef parsed_transactions_with_splits@@ -537,14 +547,47 @@ class QifImport < Importend# Auto-detects the QIF file's date format from D-field samples and persists it.+ # A declared "!Option:MDY"/"!Option:DMY" limits detection to formats with that+ # day/month order (year-first formats are unambiguous and always kept), as+ # long as the chosen format reads every date. Otherwise all formats compete.# Falls back to "%m/%d/%Y" (US convention) if detection is inconclusive.def detect_and_set_qif_date_format!samples = QifParser.extract_raw_dates(raw_file_str)- detected = Import.detect_date_format(samples, fallback: "%m/%d/%Y")+ formats = date_format_options.map(&:last)+ declared_order = QifParser.date_order(raw_file_str)++ if declared_order+ ordered_formats = formats.select { |fmt| [ declared_order, nil ].include?(day_month_order(fmt)) }+ detected = Import.detect_date_format(samples, candidates: ordered_formats, fallback: nil)+ detected = nil unless detected && reads_all_dates?(samples, detected)+ end++ detected ||= Import.detect_date_format(samples, candidates: formats, fallback: "%m/%d/%Y")self.qif_date_format = detectedupdate_column(:column_mappings, column_mappings)end+ def reads_all_dates?(samples, fmt)+ samples.all? do |sample|+ Import.reasonable_date_range.cover?(Date.strptime(sample, fmt))+ rescue Date::Error, ArgumentError+ false+ end+ end++ # "MDY" or "DMY" for formats that start with the month or the day, nil for+ # formats that start with the year.+ def day_month_order(fmt)+ fields = fmt.scan(/%[a-zA-Z]/)+ return nil if fields.first.in?(%w[%Y %y])++ day_index = fields.index { |field| field.in?(%w[%d %e]) }+ month_index = fields.index { |field| field.in?(%w[%m %b]) }+ return nil unless day_index && month_index++ month_index < day_index ? "MDY" : "DMY"+ end+# Returns the signed qty for a trade row:# buy-like actions keep qty positive; sell-like negate it.def trade_qty_for(action, raw_qty)diff --git a/test/models/qif_import_test.rb b/test/models/qif_import_test.rbindex f21d0f7811..87552caf5c 100644--- a/test/models/qif_import_test.rb+++ b/test/models/qif_import_test.rb@@ -1494,4 +1494,188 @@ class QifImportTest < ActiveSupport::TestCaseassert_empty formatsend++ # ── Declared date order (!Option:MDY / !Option:DMY) ─────────────────────────++ MDY_DOT_QIF = <<~QIF+ !Option:MDY+ !Type:CCard+ D6.12.26+ U69.99+ T69.99+ PFirst Purchase+ ^+ D6.5.26+ U169.99+ T169.99+ PSecond Purchase+ ^+ QIF++ DOT_QIF_WITHOUT_OPTION = <<~QIF+ !Type:Bank+ D6.12.20+ T-10.00+ PFirst Store+ ^+ D6.5.20+ T-20.00+ PSecond Store+ ^+ QIF++ test "date_order reads the declared date order" do+ assert_equal "MDY", QifParser.date_order(MDY_DOT_QIF)+ assert_equal "DMY", QifParser.date_order("!option:dmy\r\n!Type:Bank\r\n")+ assert_nil QifParser.date_order(DOT_QIF_WITHOUT_OPTION)+ assert_nil QifParser.date_order(nil)+ end++ test "date_order reads the declared date order behind a UTF-8 byte order mark" do+ assert_equal "MDY", QifParser.date_order("\uFEFF" + MDY_DOT_QIF)+ assert_equal "MDY", QifParser.date_order(("\xEF\xBB\xBF" + MDY_DOT_QIF).b)+ end++ test "date_order reads the declared date order with CR-only line endings" do+ assert_equal "MDY", QifParser.date_order(MDY_DOT_QIF.gsub("\n", "\r"))+ end++ test "generate_rows_from_csv reads month-first dotted dates with CR-only line endings" do+ @import.update!(raw_file_str: MDY_DOT_QIF.gsub("\n", "\r"))+ @import.generate_rows_from_csv++ assert_equal "%m.%d.%Y", @import.reload.qif_date_format+ assert_equal "2026-06-12", @import.rows.find_by(name: "First Purchase").date+ end++ test "generate_rows_from_csv reads month-first dotted dates when the file declares MDY" do+ @import.update!(raw_file_str: MDY_DOT_QIF)+ @import.generate_rows_from_csv++ assert_equal "%m.%d.%Y", @import.reload.qif_date_format+ assert_equal "2026-06-12", @import.rows.find_by(name: "First Purchase").date+ assert_equal "2026-06-05", @import.rows.find_by(name: "Second Purchase").date+ end++ test "generate_rows_from_csv reads day-first dates when the file declares DMY" do+ @import.update!(raw_file_str: <<~QIF)+ !Option:DMY+ !Type:Bank+ D04-06-2020+ T-10.00+ PFirst Store+ ^+ D01-10-2020+ T-20.00+ PSecond Store+ ^+ QIF+ @import.generate_rows_from_csv++ assert_equal "%d-%m-%Y", @import.reload.qif_date_format+ assert_equal "2020-06-04", @import.rows.find_by(name: "First Store").date+ end++ test "generate_rows_from_csv keeps day-first dotted dates when no order is declared" do+ @import.update!(raw_file_str: DOT_QIF_WITHOUT_OPTION)+ @import.generate_rows_from_csv++ assert_equal "%d.%m.%Y", @import.reload.qif_date_format+ assert_equal "2020-12-06", @import.rows.find_by(name: "First Store").date+ end++ test "generate_rows_from_csv detects month-first dotted dates without a declared order" do+ @import.update!(raw_file_str: <<~QIF)+ !Type:Bank+ D7.10.20+ T-10.00+ PFirst Store+ ^+ D7.25.20+ T-20.00+ PSecond Store+ ^+ QIF+ @import.generate_rows_from_csv++ assert_equal "%m.%d.%Y", @import.reload.qif_date_format+ assert_equal 2, @import.rows.count+ end++ test "generate_rows_from_csv keeps year-first dates when the file declares an order" do+ @import.update!(raw_file_str: <<~QIF)+ !Option:MDY+ !Type:Bank+ D2020-06-04+ T-10.00+ PFirst Store+ ^+ QIF+ @import.generate_rows_from_csv++ assert_equal "%Y-%m-%d", @import.reload.qif_date_format+ end++ test "generate_rows_from_csv falls back to all formats when the declared order does not fit the dates" do+ @import.update!(raw_file_str: <<~QIF)+ !Option:MDY+ !Type:Bank+ D29.03.2021+ T-10.00+ PFirst Store+ ^+ QIF+ @import.generate_rows_from_csv++ assert_equal "%d.%m.%Y", @import.reload.qif_date_format+ assert_equal "2021-03-29", @import.rows.find_by(name: "First Store").date+ end++ test "generate_rows_from_csv checks dates in every section against the declared order" do+ @import.update!(raw_file_str: <<~QIF)+ !Option:MDY+ !Type:Bank+ D04.06.2020+ T-10.00+ PFirst Store+ ^+ !Type:Bank+ D29.03.2021+ T-20.00+ PSecond Store+ ^+ QIF+ @import.generate_rows_from_csv++ assert_equal "%d.%m.%Y", @import.reload.qif_date_format+ assert_equal "2020-06-04", @import.rows.find_by(name: "First Store").date+ assert_equal "2021-03-29", @import.rows.find_by(name: "Second Store").date+ end++ test "extract_raw_dates reads every transaction section" do+ content = <<~QIF+ !Type:Bank+ D04.06.2020+ ^+ !Type:Cat+ NFood+ DFood expenses+ ^+ !Type:Bank+ D29.03.2021+ ^+ QIF++ assert_equal %w[04.06.2020 29.03.2021], QifParser.extract_raw_dates(content)+ end++ test "valid_date_formats_with_preview offers month-first dotted dates" do+ @import.update!(raw_file_str: MDY_DOT_QIF)+ formats = @import.valid_date_formats_with_preview++ mdy = formats.find { |f| f[:format] == "%m.%d.%Y" }+ assert_equal "MM.DD.YYYY", mdy[:label]+ assert_equal "2026-06-12", mdy[:preview]+ assert_includes formats.map { |f| f[:format] }, "%d.%m.%Y"+ endend