The personal finance app for everyone (by everyone)
Ruby
Support QIF split transactions and account metadata (#3348)
Sure Admin (bot)b26b1f099f1b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a2afdb85d4..4eb595c2b3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -38,7 +38,17 @@ jobs:bundler-cache: true- name: Scan for security vulnerabilities in JavaScript dependencies- run: bin/importmap audit+ run: |+ for attempt in 1 2 3; do+ echo "Running importmap audit, attempt ${attempt}/3"+ bin/importmap audit && exit 0++ if [ "$attempt" = 3 ]; then+ exit 1+ fi++ sleep $((attempt * 10))+ donelint:runs-on: ubuntu-latestdiff --git a/app/controllers/import/qif_category_selections_controller.rb b/app/controllers/import/qif_category_selections_controller.rbindex cf7538b9b3..b626aac3e0 100644--- a/app/controllers/import/qif_category_selections_controller.rb+++ b/app/controllers/import/qif_category_selections_controller.rb@@ -17,13 +17,10 @@ class Import::QifCategorySelectionsController < ApplicationControllerdef update# If the user changed the date format, re-generate rows with the new format.- format_changed = falseif selection_params[:date_format].present? && selection_params[:date_format] != @import.qif_date_format- format_changed = true@import.qif_date_format = selection_params[:date_format]@import.update_column(:column_mappings, @import.column_mappings)@import.generate_rows_from_csv- @import.sync_mappingsendall_categories = @import.row_categories@@ -36,6 +33,12 @@ class Import::QifCategorySelectionsController < ApplicationControllerdeselected_tags = all_tags - selected_tagsActiveRecord::Base.transaction do+ @import.column_mappings = (@import.column_mappings || {}).merge(+ "qif_selected_categories" => selected_categories,+ "qif_selected_tags" => selected_tags+ )+ @import.save!(validate: false)+# Clear category on rows whose category was deselectedif deselected_categories.any?@import.rows.where(category: deselected_categories).update_all(category: "")@@ -51,7 +54,7 @@ class Import::QifCategorySelectionsController < ApplicationControllerendend- @import.sync_mappings unless format_changed+ @import.sync_mappingsendredirect_to import_clean_path(@import), notice: t(".success")diff --git a/app/controllers/import/uploads_controller.rb b/app/controllers/import/uploads_controller.rbindex 076452a88a..d777718179 100644--- a/app/controllers/import/uploads_controller.rb+++ b/app/controllers/import/uploads_controller.rb@@ -72,14 +72,16 @@ class Import::UploadsController < ApplicationControllerrender :show, status: :unprocessable_entity and returnend- unless import_account_id.present?- flash.now[:alert] = "Please select an account for the QIF import"+ normalized_qif = QifParser.normalize_encoding(csv_str)++ unless import_account_id.present? || QifParser.parse_accounts(normalized_qif).any?+ flash.now[:alert] = t(".qif_account_required")render :show, status: :unprocessable_entity and returnendActiveRecord::Base.transaction do- @import.account = accessible_accounts.find(import_account_id)- @import.raw_file_str = QifParser.normalize_encoding(csv_str)+ @import.account = accessible_accounts.find(import_account_id) if import_account_id.present?+ @import.raw_file_str = normalized_qif@import.save!(validate: false)@import.generate_rows_from_csv@import.sync_mappingsdiff --git a/app/models/concerns/qif_parser.rb b/app/models/concerns/qif_parser.rbindex 654cae5d48..b962a59750 100644--- a/app/models/concerns/qif_parser.rb+++ b/app/models/concerns/qif_parser.rb@@ -31,6 +31,7 @@# T total total cash amount of transactionmodule QifParserTRANSACTION_TYPES = %w[CCard Bank Cash Invst Oth\ L Oth\ A].freeze+ GENERIC_TRANSACTION_TYPES = TRANSACTION_TYPES - [ "Invst" ]# Investment action types that create Trade records (buy or sell shares).BUY_LIKE_ACTIONS = %w[Buy ReinvDiv Cover].freeze@@ -42,10 +43,14 @@ module QifParserOUTFLOW_TRANSACTION_ACTIONS = %w[XOut MiscExp].freezeParsedTransaction = Struct.new(- :date, :amount, :payee, :memo, :category, :tags, :check_num, :cleared, :split,+ :date, :amount, :payee, :memo, :category, :tags, :check_num, :cleared,+ :split, :split_lines, :account_name, :account_type,keyword_init: true)+ ParsedSplitLine = Struct.new(:category, :tags, :amount, :memo, keyword_init: true)+ ParsedAccount = Struct.new(:name, :account_type, :description, keyword_init: true)+ParsedCategory = Struct.new(:name, :description, :income, keyword_init: true)ParsedTag = Struct.new(:name, :description, keyword_init: true)@@ -53,7 +58,7 @@ module QifParserParsedInvestmentTransaction = Struct.new(:date, :action, :security_name, :security_ticker,- :price, :qty, :amount, :memo, :payee, :category, :tags,+ :price, :qty, :amount, :memo, :payee, :category, :tags, :account_name, :account_type,keyword_init: true)@@ -119,13 +124,16 @@ module QifParsercontent = normalize_encoding(content)content = normalize_line_endings(content)- type = account_type(content)- return [] unless type-- section = extract_section(content, type)- return [] unless section-- parse_records(section).filter_map { |record| build_transaction(record, date_format: date_format) }+ transaction_sections(content).select { |section| GENERIC_TRANSACTION_TYPES.include?(section[:type]) }.flat_map do |section|+ parse_records(section[:content]).filter_map do |record|+ build_transaction(+ record,+ date_format: date_format,+ account: section[:account],+ account_type: section[:type]+ )+ end+ endend# Returns the opening balance entry from the QIF file, if present.@@ -135,25 +143,32 @@ module QifParser## Returns a hash { date: Date, amount: BigDecimal } or nil.def self.parse_opening_balance(content, date_format: "%m/%d/%Y")- return nil unless valid?(content)+ parse_opening_balances(content, date_format: date_format).first&.slice(:date, :amount)+ end++ # Returns opening balance entries keyed by the QIF account metadata for+ # multi-account QIF exports, or a single metadata-less result for legacy files.+ def self.parse_opening_balances(content, date_format: "%m/%d/%Y")+ return [] unless valid?(content)content = normalize_encoding(content)content = normalize_line_endings(content)- type = account_type(content)- return nil unless type+ transaction_sections(content).filter_map do |section|+ record = parse_records(section[:content]).find { |r| r["P"]&.strip == "Opening Balance" }+ next unless record- section = extract_section(content, type)- return nil unless section+ date = parse_qif_date(record["D"], date_format: date_format)+ amount = parse_qif_amount(record["T"] || record["U"])+ next unless date && amount- record = parse_records(section).find { |r| r["P"]&.strip == "Opening Balance" }- return nil unless record-- date = parse_qif_date(record["D"], date_format: date_format)- amount = parse_qif_amount(record["T"] || record["U"])- return nil unless date && amount-- { date: Date.parse(date), amount: amount.to_d }+ {+ account_name: section[:account]&.name,+ account_type: section[:type],+ date: Date.parse(date),+ amount: amount.to_d+ }+ endend# Parses categories from the !Type:Cat section.@@ -199,6 +214,17 @@ module QifParserendend+ def self.parse_accounts(content)+ return [] if content.blank?++ content = normalize_encoding(content)+ content = normalize_line_endings(content)++ content.scan(/^!Account[^\n]*\n(.*?)(?=^!Account|^!Type:|\z)/mi).flat_map do |captures|+ parse_records(captures[0]).filter_map { |record| build_account(record) }+ end+ end+# Parses all !Type:Security sections and returns an array of ParsedSecurity structs.# Each security in a QIF file gets its own !Type:Security header, so we scan# for all occurrences rather than just the first.@@ -236,10 +262,17 @@ module QifParserticker_by_name = parse_securities(content).each_with_object({}) { |s, h| h[s.name] = s.ticker }- section = extract_section(content, "Invst")- return [] unless section-- parse_records(section).filter_map { |record| build_investment_transaction(record, ticker_by_name, date_format: date_format) }+ transaction_sections(content).select { |section| section[:type] == "Invst" }.flat_map do |section|+ parse_records(section[:content]).filter_map do |record|+ build_investment_transaction(+ record,+ ticker_by_name,+ date_format: date_format,+ account: section[:account],+ account_type: section[:type]+ )+ end+ endend# ------------------------------------------------------------------@@ -260,9 +293,70 @@ module QifParserendprivate_class_method :extract_section+ def self.transaction_sections(content)+ sections = []+ current_account = nil+ lines = content.lines+ index = 0++ while index < lines.length+ line = lines[index]++ if line.match?(/^!Account/i)+ section_content, index = collect_section_lines(lines, index + 1)+ current_account = parse_records(section_content).filter_map { |record| build_account(record) }.first+ next+ end++ if (match = line.match(/^!Type:(.+)/i))+ type = match[1].strip+ section_content, index = collect_section_lines(lines, index + 1)++ if TRANSACTION_TYPES.include?(type)+ sections << {+ type: type,+ account: current_account,+ content: section_content+ }+ end++ next+ end++ index += 1+ end++ sections+ end+ private_class_method :transaction_sections++ def self.collect_section_lines(lines, index)+ section_lines = []++ while index < lines.length && !lines[index].match?(/^!(?:Account|Type:)/i)+ section_lines << lines[index]+ index += 1+ end++ [ section_lines.join, index ]+ end+ private_class_method :collect_section_lines++ def self.build_account(record)+ return nil if record["N"].blank?++ ParsedAccount.new(+ name: record["N"].strip,+ account_type: record["T"]&.strip,+ description: record["D"]&.strip+ )+ end+ private_class_method :build_account+# Splits a section into an array of field-code => value hashes.# Single-letter codes with no value (e.g. "I", "E", "T") are stored with nil.- # Split transactions (multiple S/$/E lines) are flagged with "_split" => true.+ # Split transactions (multiple S/$/E lines) are flagged and retain ordered+ # split line data so Quicken splits can be imported as Sure splits.def self.parse_records(section_content)records = []current = {}@@ -279,8 +373,15 @@ module QifParservalue = line[1..]&.stripnext unless code- # Mark records that contain split fields (S = split category, $ = split amount)- current["_split"] = true if code == "S"+ case code+ when "S"+ current["_split"] = true+ (current["_split_lines"] ||= []) << { "category" => value.presence }+ when "$"+ current["_split_lines"]&.last&.[]=("amount", value.presence)+ when "E"+ current["_split_lines"]&.last&.[]=("memo", value.presence)+ end# Flag fields like "I" (income) and "E" (expense) have no meaningful valuecurrent[code] = value.presence@@ -292,7 +393,7 @@ module QifParserendprivate_class_method :parse_records- def self.build_transaction(record, date_format: "%m/%d/%Y")+ def self.build_transaction(record, date_format: "%m/%d/%Y", account: nil, account_type: nil)# "Opening Balance" is a Quicken convention for the account's starting balance –# it is not a real transaction and must not be imported as one.return nil if record["P"]&.strip == "Opening Balance"@@ -308,6 +409,7 @@ module QifParserreturn nil unless date && amountcategory, tags = parse_category_and_tags(record["L"])+ split_lines = build_split_lines(record["_split_lines"])ParsedTransaction.new(date: date,@@ -318,11 +420,31 @@ module QifParsertags: tags,check_num: record["N"],cleared: record["C"],- split: record["_split"] == true+ split: record["_split"] == true,+ split_lines: split_lines,+ account_name: account&.name,+ account_type: account&.account_type.presence || account_type)endprivate_class_method :build_transaction+ def self.build_split_lines(lines)+ Array(lines).filter_map do |line|+ amount = parse_qif_amount(line["amount"])+ next unless amount++ category, tags = parse_category_and_tags(line["category"])++ ParsedSplitLine.new(+ category: category,+ tags: tags,+ amount: amount,+ memo: line["memo"]+ )+ end+ end+ private_class_method :build_split_lines+# Separates the category name from any tag(s) appended with a "/" delimiter.# Transfer accounts are wrapped in brackets – treated as no category.#@@ -446,7 +568,7 @@ module QifParser# Builds a ParsedInvestmentTransaction from a raw record hash.# ticker_by_name maps security names (N field in !Type:Security) to tickers (S field).- def self.build_investment_transaction(record, ticker_by_name, date_format: "%m/%d/%Y")+ def self.build_investment_transaction(record, ticker_by_name, date_format: "%m/%d/%Y", account: nil, account_type: nil)action = record["N"]&.stripreturn nil unless action.present?@@ -476,7 +598,9 @@ module QifParsermemo: record["M"]&.strip,payee: record["P"]&.strip,category: category,- tags: tags+ tags: tags,+ account_name: account&.name,+ account_type: account&.account_type.presence || account_type)endprivate_class_method :build_investment_transactiondiff --git a/app/models/entry.rb b/app/models/entry.rbindex 3d1fee3902..14ff608518 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -461,6 +461,9 @@ class Entry < ApplicationRecordname: split_attrs[:name],amount: split_attrs[:amount],currency: currency,+ notes: split_attrs[:notes],+ import: import,+ import_locked: import_locked,excluded: TRUTHY_VALUES.include?(split_attrs[:excluded]),entryable: child_transaction)diff --git a/app/models/import/category_mapping.rb b/app/models/import/category_mapping.rbindex a625aa1d47..777b68d78a 100644--- a/app/models/import/category_mapping.rb+++ b/app/models/import/category_mapping.rb@@ -1,7 +1,11 @@class Import::CategoryMapping < Import::Mappingclass << selfdef mappables_by_key(import)- unique_values = import.rows.map(&:category).uniq+ unique_values = if import.is_a?(QifImport)+ import.row_categories+ else+ import.rows.map(&:category).uniq+ end# For hierarchical QIF keys like "Home:Home Improvement", look up the child# name ("Home Improvement") since category names are unique per family.@@ -55,10 +59,16 @@ class Import::CategoryMapping < Import::Mappingparent_name = parts[0].stripchild_name = parts[1].strip- # Ensure the parent category exists before creating the child.- parent = import.family.categories.find_or_create_by!(name: parent_name) do |cat|- cat.color = Category::COLORS.sample- cat.lucide_icon = Category.suggested_icon(parent_name)+ # Ensure parent is a top-level category (subcategories cannot have children in Sure).+ parent = import.family.categories.roots.find_by(name: parent_name)++ if parent.nil?+ existing = import.family.categories.find_by(name: parent_name)+ if existing&.subcategory?+ parent = existing.parent+ else+ parent = create_root_category!(parent_name)+ endendself.mappable = import.family.categories.find_or_create_by!(name: child_name) do |cat|@@ -75,4 +85,18 @@ class Import::CategoryMapping < Import::Mappingsave!end++ private+ def create_root_category!(name)+ import.family.categories.roots.create!(name: name) do |cat|+ cat.color = Category::COLORS.sample+ cat.lucide_icon = Category.suggested_icon(name)+ end+ rescue ActiveRecord::RecordNotUnique+ import.family.categories.roots.find_by!(name: name)+ rescue ActiveRecord::RecordInvalid => error+ raise unless error.record.is_a?(Category) && error.record.errors.of_kind?(:name, :taken)++ import.family.categories.roots.find_by!(name: name)+ endenddiff --git a/app/models/import/tag_mapping.rb b/app/models/import/tag_mapping.rbindex 4b9a1be08c..36daa3075c 100644--- a/app/models/import/tag_mapping.rb+++ b/app/models/import/tag_mapping.rb@@ -1,7 +1,11 @@class Import::TagMapping < Import::Mappingclass << selfdef mappables_by_key(import)- unique_values = import.rows.map(&:tags_list).flatten.uniq+ unique_values = if import.is_a?(QifImport)+ import.row_tags+ else+ import.rows.map(&:tags_list).flatten.uniq+ endtags = import.family.tags.where(name: unique_values).index_by(&:name)diff --git a/app/models/qif_import.rb b/app/models/qif_import.rbindex a0590cb213..fd52edcc1c 100644--- a/app/models/qif_import.rb+++ b/app/models/qif_import.rb@@ -22,11 +22,8 @@ class QifImport < Importrows.destroy_all- if investment_account?- generate_investment_rows- else- generate_transaction_rows- end+ generate_transaction_rows+ generate_investment_rowsupdate_column(:rows_count, rows.count)end@@ -35,20 +32,10 @@ class QifImport < Importtransaction domappings.each(&:create_mappable!)- if investment_account?- import_investment_rows!- else- import_transaction_rows!+ import_transaction_rows!+ import_investment_rows!- if (ob = QifParser.parse_opening_balance(raw_file_str, date_format: qif_date_format))- Account::OpeningBalanceManager.new(account).set_opening_balance(- balance: ob[:amount],- date: ob[:date]- )- else- adjust_opening_anchor_if_needed!- end- end+ apply_opening_balances_or_adjust_anchors!endend@@ -62,19 +49,23 @@ class QifImport < Importenddef column_keys- if qif_account_type == "Invst"+ if qif_account_type == "Invst" && has_qif_accounts?+ %i[date account ticker qty price amount currency name]+ elsif qif_account_type == "Invst"%i[date ticker qty price amount currency name]+ elsif has_qif_accounts?+ %i[date account amount name currency category tags notes]else%i[date amount name currency category tags notes]endenddef publishable?- account.present? && super+ (account.present? || has_qif_accounts?) && superenddef publishable_from_validation_stats?(invalid_rows_count:)- account.present? && super+ (account.present? || has_qif_accounts?) && superend# Returns true if import! will move the opening anchor back to cover transactions@@ -103,9 +94,17 @@ class QifImport < Import@qif_account_type = raw_file_str.present? ? QifParser.account_type(raw_file_str) : nilend+ def qif_accounts+ @qif_accounts ||= raw_file_str.present? ? QifParser.parse_accounts(raw_file_str) : []+ end++ def has_qif_accounts?+ qif_accounts.any?+ end+# Unique categories used across all rows (blank entries excluded).def row_categories- rows.distinct.pluck(:category).reject(&:blank?).sort+ (rows.distinct.pluck(:category) + selected_split_categories).reject(&:blank?).uniq.sortend# Returns true if the QIF file contains any split transactions.@@ -115,18 +114,15 @@ class QifImport < Importend# Categories that appear on split transactions in the QIF file.- # Split transactions use S/$ fields to break a total into sub-amounts;- # the app does not yet support splits, so these categories are flagged.def split_categoriesreturn @split_categories if defined?(@split_categories)- split_cats = parsed_transactions_with_splits.select(&:split).map(&:category).reject(&:blank?).uniq.sort- @split_categories = split_cats & row_categories+ @split_categories = parsed_split_categoriesend# Unique tags used across all rows (blank entries excluded).def row_tags- rows.flat_map(&:tags_list).uniq.reject(&:blank?).sort+ (rows.flat_map(&:tags_list) + selected_split_tags).uniq.reject(&:blank?).sortend# True once the category/tag selection step has been completed@@ -152,7 +148,33 @@ class QifImport < Importprivatedef parsed_transactions_with_splits- @parsed_transactions_with_splits ||= QifParser.parse(raw_file_str)+ @parsed_transactions_with_splits ||= QifParser.parse(raw_file_str, date_format: qif_date_format)+ end++ def parsed_transaction_by_source_row_number+ @parsed_transaction_by_source_row_number ||= parsed_transactions_with_splits.each.with_index(1).to_h { |trn, index| [ index, trn ] }+ end++ def parsed_split_categories+ parsed_transactions_with_splits.flat_map { |trn| trn.split_lines.to_a.map(&:category) }.reject(&:blank?).uniq.sort+ end++ def parsed_split_tags+ parsed_transactions_with_splits.flat_map { |trn| trn.split_lines.to_a.flat_map(&:tags) }+ end++ def selected_split_categories+ selected = column_mappings&.dig("qif_selected_categories")+ return parsed_split_categories unless selected++ parsed_split_categories & selected+ end++ def selected_split_tags+ selected = column_mappings&.dig("qif_selected_tags")+ return parsed_split_tags unless selected++ parsed_split_tags & selectedenddef investment_account?@@ -176,12 +198,13 @@ class QifImport < Importnotes: trn.memo.to_s,category: trn.category.to_s,tags: trn.tags.join("|"),- account: "",+ account: trn.account_name.to_s,qty: "",ticker: "",price: "",exchange_operating_mic: "",- entity_type: ""+ entity_type: "",+ resource_type: trn.account_type.to_s}end@@ -193,13 +216,16 @@ class QifImport < Importdef generate_investment_rowsinv_transactions = QifParser.parse_investment_transactions(raw_file_str, date_format: qif_date_format)+ source_row_offset = rows.maximum(:source_row_number).to_imapped_rows = inv_transactions.map.with_index(1) do |trn, index|+ source_row_number = source_row_offset + index+if QifParser::TRADE_ACTIONS.include?(trn.action)qty = trade_qty_for(trn.action, trn.qty){- source_row_number: index,+ source_row_number: source_row_number,date: trn.date.to_s,ticker: trn.security_ticker.to_s,qty: qty.to_s,@@ -210,13 +236,14 @@ class QifImport < Importnotes: trn.memo.to_s,category: "",tags: "",- account: "",+ account: trn.account_name.to_s,exchange_operating_mic: "",- entity_type: trn.action+ entity_type: trn.action,+ resource_type: trn.account_type.to_s}else{- source_row_number: index,+ source_row_number: source_row_number,date: trn.date.to_s,amount: trn.amount.to_s,currency: default_currency.to_s,@@ -224,12 +251,13 @@ class QifImport < Importnotes: trn.memo.to_s,category: trn.category.to_s,tags: trn.tags.join("|"),- account: "",+ account: trn.account_name.to_s,qty: "",ticker: "",price: "",exchange_operating_mic: "",- entity_type: trn.action+ entity_type: trn.action,+ resource_type: trn.account_type.to_s}endend@@ -245,7 +273,21 @@ class QifImport < Import# ------------------------------------------------------------------def import_transaction_rows!- transactions = rows.map do |row|+ split_rows, regular_rows = rows.ordered+ .reject { |row| row.resource_type == "Invst" }+ .partition do |row|+ parsed_transaction_by_source_row_number[row.source_row_number]&.split_lines.present?+ end++ import_regular_transaction_rows!(regular_rows)+ import_split_transaction_rows!(split_rows)+ end++ def import_regular_transaction_rows!(regular_rows)+ return if regular_rows.empty?++ transactions = regular_rows.map do |row|+ row_account = account_for_row(row)category = mappings.categories.mappable_for(row.category)tags = row.tags_list.map { |tag| mappings.tags.mappable_for(tag) }.compact@@ -253,13 +295,13 @@ class QifImport < Importcategory: category,tags: tags,entry: Entry.new(- account: account,- date: row.date_iso,- amount: row.signed_amount,- name: row.name,- currency: row.currency,- notes: row.notes,- import: self,+ account: row_account,+ date: row.date_iso,+ amount: row.signed_amount,+ name: row.name,+ currency: row.currency,+ notes: row.notes,+ import: self,import_locked: true))@@ -268,12 +310,66 @@ class QifImport < ImportTransaction.import!(transactions, recursive: true)end+ def import_split_transaction_rows!(split_rows)+ split_rows.each do |row|+ row_account = account_for_row(row)+ parsed_transaction = parsed_transaction_by_source_row_number[row.source_row_number]+ category = mappings.categories.mappable_for(row.category)+ tags = row.tags_list.map { |tag| mappings.tags.mappable_for(tag) }.compact++ transaction = Transaction.create!(+ category: category,+ tags: tags+ )++ entry = Entry.create!(+ account: row_account,+ date: row.date_iso,+ amount: row.signed_amount,+ name: row.name,+ currency: row.currency,+ notes: row.notes,+ import: self,+ import_locked: true,+ entryable: transaction+ )++ import_split_lines!(entry, parsed_transaction, fallback_tags: tags) if parsed_transaction&.split_lines.present?+ end+ end++ def import_split_lines!(entry, parsed_transaction, fallback_tags:)+ split_rows = parsed_transaction.split_lines.map do |line|+ {+ name: line.memo.presence || line.category.presence || entry.name,+ amount: signed_transaction_amount(line.amount),+ category_id: mappings.categories.mappable_for(line.category)&.id,+ notes: line.memo,+ tags: line.tags.present? ? line.tags.map { |tag| mappings.tags.mappable_for(tag) }.compact : fallback_tags+ }+ end++ return unless split_rows.sum { |row| row[:amount].to_d } == entry.amount++ children = entry.split!(split_rows)+ children.zip(split_rows).each do |child, row|+ child.update!(notes: row[:notes]) if row[:notes].present?+ row[:tags].each { |tag| child.entryable.taggings.create!(tag: tag) }+ end+ end++ def signed_transaction_amount(amount)+ amount.to_d * (signage_convention == "inflows_positive" ? -1 : 1)+ end+def import_investment_rows!- trade_rows = rows.select { |r| QifParser::TRADE_ACTIONS.include?(r.entity_type) }- transaction_rows = rows.reject { |r| QifParser::TRADE_ACTIONS.include?(r.entity_type) }+ investment_rows = rows.select { |r| r.resource_type == "Invst" }+ trade_rows = investment_rows.select { |r| QifParser::TRADE_ACTIONS.include?(r.entity_type) }+ transaction_rows = investment_rows.reject { |r| QifParser::TRADE_ACTIONS.include?(r.entity_type) }if trade_rows.any?trades = trade_rows.map do |row|+ row_account = account_for_row(row)security = find_or_create_security(ticker: row.ticker)# Use the stored T-field amount for accuracy (includes any fees/commissions).@@ -287,7 +383,7 @@ class QifImport < Importcurrency: row.currency,investment_activity_label: investment_activity_label_for(row.entity_type),entry: Entry.new(- account: account,+ account: row_account,date: row.date_iso,amount: entry_amount,name: row.name,@@ -303,6 +399,7 @@ class QifImport < Importif transaction_rows.any?transactions = transaction_rows.map do |row|+ row_account = account_for_row(row)# Inflow actions: money entering account → negative Entry.amount# Outflow actions: money leaving account → positive Entry.amountentry_amount = QifParser::INFLOW_TRANSACTION_ACTIONS.include?(row.entity_type) ? -row.amount.to_d : row.amount.to_d@@ -314,7 +411,7 @@ class QifImport < Importcategory: category,tags: tags,entry: Entry.new(- account: account,+ account: row_account,date: row.date_iso,amount: entry_amount,name: row.name,@@ -334,24 +431,93 @@ class QifImport < Import# Helpers# ------------------------------------------------------------------- def adjust_opening_anchor_if_needed!- manager = Account::OpeningBalanceManager.new(account)+ def apply_opening_balances_or_adjust_anchors!+ opening_balances = QifParser.parse_opening_balances(raw_file_str, date_format: qif_date_format)++ if has_qif_accounts?+ accounts_by_name = qif_accounts.to_h { |qif_account| [ qif_account.name, find_or_create_qif_account(qif_account.name, qif_account.account_type) ] }+ opening_balances.each do |opening_balance|+ target_account = accounts_by_name[opening_balance[:account_name]]+ next unless target_account++ Account::OpeningBalanceManager.new(target_account).set_opening_balance(+ balance: opening_balance[:amount],+ date: opening_balance[:date]+ )+ end++ accounts_by_name.each_value do |target_account|+ next if opening_balances.any? { |opening_balance| opening_balance[:account_name] == target_account.name }++ adjust_opening_anchor_if_needed!(target_account, earliest_row_date(target_account.name))+ end+ elsif (opening_balance = opening_balances.first)+ Account::OpeningBalanceManager.new(account).set_opening_balance(+ balance: opening_balance[:amount],+ date: opening_balance[:date]+ )+ else+ adjust_opening_anchor_if_needed!(account, earliest_row_date)+ end+ end++ def adjust_opening_anchor_if_needed!(target_account, earliest)+ manager = Account::OpeningBalanceManager.new(target_account)return unless manager.has_opening_anchor?- earliest = earliest_row_datereturn unless earliest.present? && earliest < manager.opening_date- Account::OpeningBalanceManager.new(account).set_opening_balance(+ Account::OpeningBalanceManager.new(target_account).set_opening_balance(balance: manager.opening_balance,date: earliest - 1.day)end- def earliest_row_date- str = rows.minimum(:date)+ def earliest_row_date(account_name = nil)+ scope = account_name.present? ? rows.where(account: account_name) : rows+ str = scope.minimum(:date)Date.parse(str) if str.present?end+ def account_for_row(row)+ return account if row.account.blank?++ qif_account_cache[row.account] ||= find_or_create_qif_account(row.account, row.resource_type)+ end++ def qif_account_cache+ @qif_account_cache ||= {}+ end++ def find_or_create_qif_account(name, qif_type)+ family.accounts.find_by(name: name) || Account.create_and_sync(+ {+ family: family,+ name: name,+ balance: 0,+ currency: default_currency,+ accountable_type: accountable_type_for_qif_type(qif_type),+ import: self+ },+ skip_initial_sync: true+ )+ end++ def accountable_type_for_qif_type(qif_type)+ case qif_type+ when "CCard"+ "CreditCard"+ when "Invst"+ "Investment"+ when "Oth A"+ "OtherAsset"+ when "Oth L"+ "OtherLiability"+ else+ "Depository"+ end+ end+def set_default_configupdate!(signage_convention: "inflows_positive",diff --git a/app/views/import/qif_category_selections/show.html.erb b/app/views/import/qif_category_selections/show.html.erbindex f2b4430045..b1a1c36212 100644--- a/app/views/import/qif_category_selections/show.html.erb+++ b/app/views/import/qif_category_selections/show.html.erb@@ -77,7 +77,7 @@name="categories[]"value="<%= category %>"id="cat_<%= index %>_<%= category.parameterize(separator: "_") %>"- <%= "checked" unless is_split %>+ checkedclass="rounded border-primary"></div><div class="col-span-8 flex items-center gap-2">diff --git a/app/views/import/uploads/show.html.erb b/app/views/import/uploads/show.html.erbindex 7d19818c68..7bac7f02ca 100644--- a/app/views/import/uploads/show.html.erb+++ b/app/views/import/uploads/show.html.erb@@ -58,7 +58,7 @@<%= form.select :account_id,Current.user.accessible_accounts.visible.alphabetically.pluck(:name, :id),{ label: t(".qif_account_label"), include_blank: t(".qif_account_placeholder"), selected: @import.account_id },- required: true %>+ required: false %><label for="import_import_file" class="flex flex-col items-center justify-center w-full h-64 border border-secondary border-dashed rounded-xl cursor-pointer" data-controller="file-upload" data-file-upload-target="uploadArea"><div class="flex flex-col items-center justify-center pt-5 pb-6">diff --git a/config/locales/views/imports/en.yml b/config/locales/views/imports/en.ymlindex 697a2e6cf8..083835f30e 100644--- a/config/locales/views/imports/en.yml+++ b/config/locales/views/imports/en.yml@@ -22,7 +22,7 @@ en:one: "1 txn"other: "%{count} txns"split_warning_title: Split transactions detected- split_warning_description: "This QIF file contains split transactions. Splits are not yet supported, so each split transaction will be imported as a single transaction with its full amount and no category. The individual split breakdowns will not be preserved."+ split_warning_description: "This QIF file contains split transactions. Review the detected split categories and tags below before importing."split_badge: splitempty_state_primary: No categories or tags were found in this QIF file.empty_state_secondary: All transactions will be imported without categories or tags.@@ -200,6 +200,7 @@ en:uploads:handle_qif_upload:qif_uploaded: "QIF file uploaded successfully."+ qif_account_required: Please select an account for the QIF importupdate:qif_uploaded: "QIF file uploaded successfully."show:@@ -215,7 +216,7 @@ en:download_sample_csv: Download a sample CSVto_see_format: to see the required CSV formatqif_title: Upload QIF file- qif_description: Select the account this QIF file belongs to, then upload your .qif export from Quicken.+ qif_description: Select an account for single-account files, or leave blank when your QIF export includes account names.qif_account_label: Accountqif_account_placeholder: Select an account…qif_file_prompt: to add your QIF file herediff --git a/test/models/import/category_mapping_test.rb b/test/models/import/category_mapping_test.rbindex 4d20966b1d..11ee50be26 100644--- a/test/models/import/category_mapping_test.rb+++ b/test/models/import/category_mapping_test.rb@@ -22,4 +22,84 @@ class Import::CategoryMappingTest < ActiveSupport::TestCaseassert_equal "Add as new category", options.first.firstassert_equal Import::Mapping::CREATE_NEW_KEY, options.first.lastend++ test "create_mappable! uses root parent when parent_name matches an existing subcategory" do+ import = @mapping.import++ # First, create a mapping where "Insurance" becomes a subcategory under "Auto"+ m1 = import.mappings.create!(key: "Auto:Insurance", create_when_empty: true, type: "Import::CategoryMapping")+ m1.create_mappable!++ insurance_sub = import.family.categories.find_by!(name: "Insurance")+ assert insurance_sub.subcategory?+ assert_equal "Auto", insurance_sub.parent.name++ # Now create a mapping where "Insurance" is the parent_name in "Insurance:ADD"+ m2 = import.mappings.create!(key: "Insurance:ADD", create_when_empty: true, type: "Import::CategoryMapping")+ assert_nothing_raised do+ m2.create_mappable!+ end++ add_sub = import.family.categories.find_by!(name: "ADD")+ assert add_sub.subcategory?+ assert_equal "Auto", add_sub.parent.name+ end++ test "create_mappable! atomically creates shared root parent during concurrent imports" do+ family = families(:empty)+ parent_name = "Concurrent Parent #{SecureRandom.hex(4)}"+ child_names = 8.times.map { |index| "Concurrent Child #{index} #{SecureRandom.hex(4)}" }+ ready = Queue.new+ start = Queue.new+ errors = Queue.new+ import_ids = Queue.new++ threads = child_names.map do |child_name|+ Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do+ import = TransactionImport.create!(family: Family.find(family.id), status: :pending)+ import_ids << import.id++ mapping = import.mappings.create!(+ key: "#{parent_name}:#{child_name}",+ create_when_empty: true,+ type: "Import::CategoryMapping"+ )++ ready << true+ start.pop+ mapping.create_mappable!+ rescue => error+ errors << error+ end+ end+ end++ child_names.size.times { ready.pop }+ child_names.size.times { start << true }+ threads.each(&:join)++ thread_errors = []+ thread_errors << errors.pop until errors.empty?++ assert_empty thread_errors, -> { thread_errors.map { |error| "#{error.class}: #{error.message}" }.join("\n") }+ assert_equal 1, family.categories.roots.where(name: parent_name).count++ parent = family.categories.roots.find_by!(name: parent_name)+ assert_equal child_names.sort, parent.subcategories.where(name: child_names).pluck(:name).sort+ ensure+ if defined?(child_names)+ Category.where(family: family, name: child_names).destroy_all+ end++ if defined?(parent_name)+ Category.where(family: family, name: parent_name).destroy_all+ end++ if defined?(import_ids)+ ids = []+ ids << import_ids.pop until import_ids.empty?+ Import.where(id: ids).destroy_all+ end+ endenddiff --git a/test/models/qif_import_test.rb b/test/models/qif_import_test.rbindex d48007a7e7..b6d2f829dc 100644--- a/test/models/qif_import_test.rb+++ b/test/models/qif_import_test.rb@@ -183,6 +183,118 @@ class QifImportTest < ActiveSupport::TestCase^QIF+ QIF_WITH_ACCOUNTS = <<~QIF+ !Account+ NQIF Checking+ TBank+ ^+ !Type:Bank+ D1/ 1'24+ U-25.00+ T-25.00+ PCoffee Shop+ ^+ !Account+ NQIF Visa+ TCCard+ ^+ !Type:CCard+ D1/ 2'24+ U-50.00+ T-50.00+ PGrocery Store+ ^+ QIF++ QIF_WITH_MIXED_ACCOUNT_TYPES = <<~QIF+ !Account+ NQIF Checking+ TBank+ ^+ !Type:Bank+ D1/ 1'24+ U-25.00+ T-25.00+ PCoffee Shop+ ^+ !Type:Security+ NACME+ SACME+ TStock+ ^+ !Account+ NQIF Brokerage+ TInvst+ ^+ !Type:Invst+ D1/ 2'24+ NBuy+ YACME+ I66.10+ Q2+ U132.20+ T132.20+ ^+ QIF++ QIF_WITH_BALANCE_ONLY_ACCOUNT = <<~QIF+ !Account+ NBalance Only+ TBank+ ^+ !Type:Bank+ D1/ 1'24+ U500.00+ T500.00+ POpening Balance+ ^+ !Account+ NQIF Checking+ TBank+ ^+ !Type:Bank+ D1/ 2'24+ U-25.00+ T-25.00+ PCoffee Shop+ ^+ QIF++ QIF_WITH_SPLIT_TAGS = <<~QIF+ !Type:Bank+ D1/ 1'24+ U-100.00+ T-100.00+ PTagged Split Store+ L--Split--+ SFood/TRIP2025+ $-60.00+ EGroceries+ STravel/KEEP+ $-40.00+ ETrain+ ^+ QIF++ QIF_WITH_ROUNDING_SPLIT_MISMATCH = <<~QIF+ !Type:Bank+ D1/ 1'24+ U-100.00+ T-100.00+ PRounded Split Store+ L--Split--+ SFood+ $-60.00+ SHousehold+ $-39.99+ ^+ D1/ 2'24+ U-20.00+ T-20.00+ PCoffee Shop+ ^+ QIF+# ── QifParser: valid? ───────────────────────────────────────────────────────test "valid? returns true for QIF content" do@@ -207,6 +319,13 @@ class QifImportTest < ActiveSupport::TestCaseassert_equal "Bank", QifParser.account_type(qif)end+ test "parse_accounts extracts QIF account metadata" do+ accounts = QifParser.parse_accounts(QIF_WITH_ACCOUNTS)++ assert_equal [ "QIF Checking", "QIF Visa" ], accounts.map(&:name)+ assert_equal [ "Bank", "CCard" ], accounts.map(&:account_type)+ end+# ── QifParser: parse (transactions) ─────────────────────────────────────────test "parse returns correct number of transactions" do@@ -248,6 +367,13 @@ class QifImportTest < ActiveSupport::TestCaseassert_equal [ "TRIP2025" ], transactions[2].tagsend+ test "parse associates transactions with QIF account metadata" do+ transactions = QifParser.parse(QIF_WITH_ACCOUNTS)++ assert_equal [ "QIF Checking", "QIF Visa" ], transactions.map(&:account_name)+ assert_equal [ "Bank", "CCard" ], transactions.map(&:account_type)+ end+# ── QifParser: parse_categories ─────────────────────────────────────────────test "parse_categories returns all categories" do@@ -320,6 +446,19 @@ class QifImportTest < ActiveSupport::TestCaserefute normal_txn.split, "Expected normal transaction not to be flagged"end+ test "parse preserves ordered split line details" do+ transactions = QifParser.parse(QIF_WITH_SPLITS)+ split_txn = transactions.find { |t| t.payee == "Grocery & Hardware Store" }++ assert_equal 2, split_txn.split_lines.length+ assert_equal "Food & Dining", split_txn.split_lines.first.category+ assert_equal "-100.00", split_txn.split_lines.first.amount+ assert_equal "Groceries", split_txn.split_lines.first.memo+ assert_equal "Household", split_txn.split_lines.second.category+ assert_equal "-50.00", split_txn.split_lines.second.amount+ assert_equal "Supplies", split_txn.split_lines.second.memo+ end+test "parse returns correct count including split transactions" dotransactions = QifParser.parse(QIF_WITH_SPLITS)assert_equal 2, transactions.length@@ -396,6 +535,35 @@ class QifImportTest < ActiveSupport::TestCaseassert row.category.blank?end+ test "generates rows with QIF account metadata" do+ @import.update!(account: nil, raw_file_str: QIF_WITH_ACCOUNTS)+ @import.generate_rows_from_csv++ coffee = @import.rows.find_by!(name: "Coffee Shop")+ grocery = @import.rows.find_by!(name: "Grocery Store")++ assert_equal "QIF Checking", coffee.account+ assert_equal "Bank", coffee.resource_type+ assert_equal "QIF Visa", grocery.account+ assert_equal "CCard", grocery.resource_type+ end++ test "generates rows for mixed transaction and investment QIF sections" do+ @import.update!(account: nil, raw_file_str: QIF_WITH_MIXED_ACCOUNT_TYPES)+ @import.generate_rows_from_csv++ assert_equal 2, @import.rows.count++ coffee = @import.rows.find_by!(name: "Coffee Shop")+ buy = @import.rows.find_by!(entity_type: "Buy")++ assert_equal "QIF Checking", coffee.account+ assert_equal "Bank", coffee.resource_type+ assert_equal "QIF Brokerage", buy.account+ assert_equal "Invst", buy.resource_type+ assert_equal "ACME", buy.ticker+ end+test "requires_csv_workflow? is false" dorefute @import.requires_csv_workflow?end@@ -455,14 +623,122 @@ class QifImportTest < ActiveSupport::TestCaserefute @import.has_split_transactions?end- test "split_categories is empty when splits use --Split-- placeholder" do+ test "split_categories uses split line categories when splits use --Split-- placeholder" do@import.update!(raw_file_str: QIF_WITH_SPLIT_PLACEHOLDER)@import.generate_rows_from_csv- assert_empty @import.split_categories+ assert_equal [ "Clothing", "Food", "Home Improvement" ], @import.split_categories+ assert_includes @import.row_categories, "Clothing"+ assert_includes @import.row_categories, "Food"+ assert_includes @import.row_categories, "Home Improvement"refute_includes @import.row_categories, "--Split--"end+ test "import! creates split children from QIF split lines" do+ @import.update!(raw_file_str: QIF_WITH_SPLITS)+ @import.generate_rows_from_csv+ @import.sync_mappings++ assert_difference "Entry.count", 4 do+ @import.import!+ end++ parent = @account.entries.find_by!(name: "Grocery & Hardware Store")+ assert parent.excluded?+ assert parent.split_parent?+ assert_equal @import, parent.import++ children = parent.child_entries.includes(:entryable).order(:amount)+ assert_equal 2, children.count++ supplies = children.find { |entry| entry.name == "Supplies" }+ groceries = children.find { |entry| entry.name == "Groceries" }++ assert_not_nil groceries+ assert_not_nil supplies+ assert_in_delta 100, groceries.amount, 0.01+ assert_equal "Food & Dining", groceries.entryable.category.name+ assert_equal "Groceries", groceries.notes+ assert_equal @import, groceries.import+ assert groceries.import_locked?++ assert_in_delta 50, supplies.amount, 0.01+ assert_equal "Household", supplies.entryable.category.name+ assert_equal "Supplies", supplies.notes+ assert_equal @import, supplies.import+ assert supplies.import_locked?+ end++ test "import! creates split children from QIF split lines with detected non-default date format" do+ qif = <<~QIF+ !Type:Bank+ D31/ 1'24+ U-30.00+ T-30.00+ PMarket and tram+ L--Split--+ SFood+ $-10.00+ STransport+ $-20.00+ ^+ QIF++ @import.update!(raw_file_str: qif)+ @import.generate_rows_from_csv+ @import.sync_mappings++ assert_equal "%d/%m/%Y", @import.reload.qif_date_format++ @import.import!++ parent = @account.entries.find_by!(name: "Market and tram")+ assert_equal Date.new(2024, 1, 31), parent.date+ assert parent.split_parent?+ assert_equal [ 10, 20 ], parent.child_entries.order(:amount).pluck(:amount).map(&:to_i)+ assert_equal [ "Food", "Transport" ], parent.child_entries.includes(entryable: :category).map { |entry| entry.entryable.category.name }.sort+ end++ test "import! preserves deselected split categories and tags" do+ @import.update!(+ raw_file_str: QIF_WITH_SPLIT_TAGS,+ column_mappings: (@import.column_mappings || {}).merge(+ "qif_selected_categories" => [ "Travel" ],+ "qif_selected_tags" => [ "KEEP" ]+ )+ )+ @import.generate_rows_from_csv+ @import.sync_mappings++ @import.import!++ parent = @account.entries.find_by!(name: "Tagged Split Store")+ groceries = parent.child_entries.includes(entryable: :tags).find_by!(name: "Groceries")+ train = parent.child_entries.includes(entryable: :tags).find_by!(name: "Train")++ assert_nil groceries.entryable.category+ assert_empty groceries.entryable.tags+ assert_equal "Travel", train.entryable.category.name+ assert_equal [ "KEEP" ], train.entryable.tags.map(&:name)+ end++ test "import! skips split creation when split line totals do not match parent" do+ @import.update!(raw_file_str: QIF_WITH_ROUNDING_SPLIT_MISMATCH)+ @import.generate_rows_from_csv+ @import.sync_mappings++ assert_difference "Transaction.count", 2 do+ @import.import!+ end++ rounded_parent = @account.entries.find_by!(name: "Rounded Split Store")+ coffee = @account.entries.find_by!(name: "Coffee Shop")++ refute rounded_parent.split_parent?+ refute rounded_parent.excluded?+ assert_not_nil coffee+ end+test "categories_selected? is false before sync_mappings" do@import.update!(raw_file_str: SAMPLE_QIF)@import.generate_rows_from_csv@@ -485,6 +761,56 @@ class QifImportTest < ActiveSupport::TestCaserefute import_without_account.publishable?end+ test "publishable? allows QIF account metadata without selected account" do+ import_without_account = QifImport.create!(family: @family)+ import_without_account.update!(raw_file_str: QIF_WITH_ACCOUNTS)+ import_without_account.generate_rows_from_csv++ assert import_without_account.publishable?+ end++ test "import! creates accounts from QIF metadata and routes transactions" do+ @import.update!(account: nil, raw_file_str: QIF_WITH_ACCOUNTS)+ @import.generate_rows_from_csv+ @import.sync_mappings++ assert_difference "Account.count", 2 do+ @import.import!+ end++ checking = @family.accounts.find_by!(name: "QIF Checking")+ visa = @family.accounts.find_by!(name: "QIF Visa")++ assert_equal @import, checking.import+ assert_equal "Depository", checking.accountable_type+ assert_equal @import, visa.import+ assert_equal "CreditCard", visa.accountable_type++ coffee = checking.entries.find_by!(name: "Coffee Shop", entryable_type: "Transaction")+ grocery = visa.entries.find_by!(name: "Grocery Store", entryable_type: "Transaction")++ assert_in_delta 25, coffee.amount, 0.01+ assert_in_delta 50, grocery.amount, 0.01+ end++ test "import! routes mixed transaction and investment sections independently" do+ @import.update!(account: nil, raw_file_str: QIF_WITH_MIXED_ACCOUNT_TYPES)+ @import.generate_rows_from_csv+ @import.sync_mappings++ assert_difference "Transaction.count", 1 do+ assert_difference "Trade.count", 1 do+ @import.import!+ end+ end++ checking = @family.accounts.find_by!(name: "QIF Checking")+ brokerage = @family.accounts.find_by!(name: "QIF Brokerage")++ assert checking.entries.exists?(name: "Coffee Shop", entryable_type: "Transaction")+ assert brokerage.entries.exists?(entryable_type: "Trade")+ end+# ── Opening balance handling ─────────────────────────────────────────────────test "Opening Balance row is not generated as a transaction row" do@@ -507,6 +833,23 @@ class QifImportTest < ActiveSupport::TestCaseassert_equal BigDecimal("500"), manager.opening_balanceend+ test "import! creates declared account that only has an opening balance" do+ @import.update!(account: nil, raw_file_str: QIF_WITH_BALANCE_ONLY_ACCOUNT)+ @import.generate_rows_from_csv+ @import.sync_mappings++ assert_difference "Account.count", 2 do+ @import.import!+ end++ balance_only = @family.accounts.find_by!(name: "Balance Only")+ manager = Account::OpeningBalanceManager.new(balance_only)++ assert manager.has_opening_anchor?+ assert_equal Date.new(2024, 1, 1), manager.opening_date+ assert_equal BigDecimal("500"), manager.opening_balance+ end+test "import! moves opening anchor back when transactions predate it" do# Anchor set 2 years ago; SAMPLE_QIF has transactions from 2020 which predate it@account.entries.create!(