The personal finance app for everyone (by everyone)
Ruby
Reconcile PDF statement imports against transactions that already exist (#3105)
Juan José Mata8ca65ffd2749
diff --git a/app/controllers/imports_controller.rb b/app/controllers/imports_controller.rbindex 7d36a783ea..cc1b0f2866 100644--- a/app/controllers/imports_controller.rb+++ b/app/controllers/imports_controller.rb@@ -1,7 +1,7 @@class ImportsController < ApplicationControllerinclude SettingsHelper- before_action :set_import, only: %i[show update publish destroy revert apply_template cancel]+ before_action :set_import, only: %i[show update publish destroy revert apply_template cancel summary]before_action :require_statement_import_permission!, only: %i[update publish destroy revert apply_template cancel]def update@@ -16,7 +16,17 @@ class ImportsController < ApplicationControllerendreturn if @import.account_statement.present? && !require_account_permission!(account)- @import.is_a?(PdfImport) ? @import.assign_account!(account) : @import.update!(account: account)+ if @import.is_a?(PdfImport)+ # Refused for an import whose data already landed -- see+ # PdfImport#reassignable?. A replayed or back-button PATCH gets the+ # explanation rather than a silent unwind.+ unless @import.assign_account!(account)+ redirect_back_or_to import_path(@import), alert: t("imports.update.account_locked")+ return+ end+ else+ @import.update!(account: account)+ endendredirect_to import_path(@import), notice: t("imports.update.account_saved", default: "Account saved.")@@ -30,6 +40,14 @@ class ImportsController < ApplicationControllerredirect_back_or_to import_path(@import), alert: t(".max_rows_exceeded", max: @import.max_row_count)end+ # Statement imports only: what became of each extracted transaction. Without it+ # a statement whose lines all matched finishes on the generic complete screen,+ # which cannot distinguish "everything was already recorded" from "nothing was+ # found".+ def summary+ raise ActiveRecord::RecordNotFound unless @import.is_a?(PdfImport)+ end+def cancelif @import.force_fail!redirect_to imports_path, notice: t(".cancelled")diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rbindex 0e3a479ea0..89c4194094 100644--- a/app/models/account/provider_import_adapter.rb+++ b/app/models/account/provider_import_adapter.rb@@ -717,24 +717,40 @@ class Account::ProviderImportAdapter# @param name [String, nil] Optional transaction name for more accurate matching# @param exclude_entry_ids [Set, Array, nil] Entry IDs to exclude from the search (e.g., already claimed entries)# @return [Entry, nil] The duplicate entry or nil if not found- def find_duplicate_transaction(date:, amount:, currency:, name: nil, exclude_entry_ids: nil)+ # @param date_window [Integer] days either side of `date` to consider. Defaults+ # to 0 (exact date), which is what provider sync wants. Statement imports+ # pass a small window, because a statement's posting date routinely differs+ # from the date a provider recorded for the same transaction.+ # @param include_provider_entries [Boolean] when false (the default) only+ # manual and CSV-imported entries are considered, which is correct for+ # provider sync: a provider must not claim another provider's entry. A+ # statement import passes true, because the whole question it is asking is+ # whether this transaction already arrived via sync.+ def find_duplicate_transaction(date:, amount:, currency:, name: nil, exclude_entry_ids: nil, date_window: 0, include_provider_entries: false)# Convert date to Date object if it's a stringdate = Date.parse(date.to_s) unless date.is_a?(Date)# Look for entries on the same account with:- # 1. Same date+ # 1. Same date (or within date_window of it)# 2. Same amount (exact match)# 3. Same currency- # 4. No external_id (manual/CSV imported transactions)+ # 4. No external_id (manual/CSV imported transactions), unless the caller+ # opted into provider-sourced entries too# 5. Entry type is Transaction (not Trade or Valuation)# 6. Optionally same name (if name parameter is provided)# 7. Not in the excluded IDs list (if provided)query = account.entries.where(entryable_type: "Transaction")- .where(date: date).where(amount: amount).where(currency: currency)- .where(external_id: nil)++ query = if date_window.to_i.zero?+ query.where(date: date)+ else+ query.where(date: (date - date_window.days)..(date + date_window.days))+ end++ query = query.where(external_id: nil) unless include_provider_entries# Add name filter if providedquery = query.where(name: name) if name.present?@@ -742,7 +758,15 @@ class Account::ProviderImportAdapter# Exclude already claimed entries if providedquery = query.where.not(id: exclude_entry_ids) if exclude_entry_ids.present?- query.order(created_at: :asc).first+ candidates = query.order(created_at: :asc)++ # Exact-date search keeps the original oldest-first behaviour.+ return candidates.first if date_window.to_i.zero?++ # A windowed search prefers the closest date, falling back to oldest-created+ # on a tie. Done in Ruby because the candidate set is already narrowed to one+ # account, one amount and one currency within a few days -- a handful of rows.+ candidates.to_a.min_by { |entry| [ (entry.date - date).abs, entry.created_at ] }end# Finds a pending transaction that likely matches a newly posted transactiondiff --git a/app/models/account_statement/account_matcher.rb b/app/models/account_statement/account_matcher.rbindex 6e8c5c1c2d..c657584ecd 100644--- a/app/models/account_statement/account_matcher.rb+++ b/app/models/account_statement/account_matcher.rb@@ -3,6 +3,8 @@class AccountStatement::AccountMatcherMatch = Struct.new(:account, :confidence, keyword_init: true)+ MINIMUM_CONFIDENCE = "0.35".to_d+attr_reader :statementdef initialize(statement)@@ -10,64 +12,104 @@ class AccountStatement::AccountMatcherenddef best_match- candidates = statement.family.accounts.visible.to_a.filter_map do |account|- confidence = confidence_for(account)- next if confidence < 0.35-- Match.new(account: account, confidence: confidence.round(4))- end-- candidates.max_by(&:confidence)+ self.class.best_match(+ family: statement.family,+ institution_hint: statement.institution_name_hint,+ account_name_hint: statement.account_name_hint,+ account_last4_hint: statement.account_last4_hint,+ currency: statement.statement_currency+ )end- private-- def confidence_for(account)- score = 0.to_d-- if institution_hint.present?- score += 0.45.to_d if account_text(account).include?(institution_hint)+ class << self+ # Hint-based entry point so callers that hold statement metadata without an+ # AccountStatement row (e.g. per-account reconciliation entries extracted+ # from a multi-account PDF) score against the same rules.+ #+ # `exclude_account_ids` lets a caller resolving several accounts out of one+ # document avoid handing the same account to two different entries.+ def best_match(family:, institution_hint: nil, account_name_hint: nil, account_last4_hint: nil, currency: nil, exclude_account_ids: [])+ return nil if family.blank?++ institution_hint = normalize_hint(institution_hint)+ account_name_hint = normalize_hint(account_name_hint)+ account_last4_hint = normalize_hint(account_last4_hint)++ return nil if institution_hint.blank? && account_name_hint.blank? && account_last4_hint.blank?++ excluded = Array.wrap(exclude_account_ids).compact++ candidates = family.accounts.visible.to_a.filter_map do |account|+ next if excluded.include?(account.id)++ confidence = confidence_for(+ account,+ institution_hint: institution_hint,+ account_name_hint: account_name_hint,+ account_last4_hint: account_last4_hint,+ currency: currency+ )+ next if confidence < MINIMUM_CONFIDENCE++ Match.new(account: account, confidence: confidence.round(4))end- if account_name_hint.present?- score += 0.25.to_d if account.name.to_s.downcase.include?(account_name_hint)- end+ ranked = candidates.sort_by { |match| -match.confidence }+ best = ranked.first+ return nil if best.nil?- if account_last4_hint.present?- score += 0.25.to_d if account_sensitive_match_text(account).include?(account_last4_hint)+ # Two accounts the hints cannot tell apart (identical names at the same+ # institution) would otherwise resolve to whichever the scan reached+ # first. Refuse to guess instead.+ if ranked.length > 1 && ranked[1].confidence == best.confidence+ Rails.logger.warn("AccountStatement::AccountMatcher found equally confident candidates; refusing to guess")+ return nilend- score += 0.05.to_d if statement.statement_currency == account.currency- [ score, 1.to_d ].min+ bestend- def institution_hint- @institution_hint ||= statement.institution_name_hint.to_s.downcase.squish.presence- end+ private- def account_name_hint- @account_name_hint ||= statement.account_name_hint.to_s.downcase.squish.presence- end+ def confidence_for(account, institution_hint:, account_name_hint:, account_last4_hint:, currency:)+ score = 0.to_d- def account_last4_hint- @account_last4_hint ||= statement.account_last4_hint.to_s.downcase.squish.presence- end+ if institution_hint.present?+ score += 0.45.to_d if account_text(account).include?(institution_hint)+ end- def account_text(account)- [- account.name,- account.institution_name,- account.institution_domain- ].compact.join(" ").downcase- end+ if account_name_hint.present?+ score += 0.25.to_d if account.name.to_s.downcase.include?(account_name_hint)+ end- def account_sensitive_match_text(account)- # Exclude user-controlled account notes from matching hints. Statement- # matching should use conservative account metadata, not free-form prose- # that can accidentally manufacture a last-four match.- [- account.name,- account.institution_name- ].compact.join(" ").downcase- end+ if account_last4_hint.present?+ score += 0.25.to_d if account_sensitive_match_text(account).include?(account_last4_hint)+ end++ score += 0.05.to_d if currency.present? && currency == account.currency+ [ score, 1.to_d ].min+ end++ def normalize_hint(value)+ value.to_s.downcase.squish.presence+ end++ def account_text(account)+ [+ account.name,+ account.institution_name,+ account.institution_domain+ ].compact.join(" ").downcase+ end++ def account_sensitive_match_text(account)+ # Exclude user-controlled account notes from matching hints. Statement+ # matching should use conservative account metadata, not free-form prose+ # that can accidentally manufacture a last-four match.+ [+ account.name,+ account.institution_name+ ].compact.join(" ").downcase+ end+ endenddiff --git a/app/models/entry.rb b/app/models/entry.rbindex 44ffa15f49..3285b8d516 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -12,6 +12,11 @@ class Entry < ApplicationRecordbelongs_to :transfer, optional: truebelongs_to :import, optional: truebelongs_to :parent_entry, class_name: "Entry", optional: true+ belongs_to :reconciled_by_statement, class_name: "AccountStatement", optional: true++ # Mirrors chk_entries_reconciled_at_present_when_statement_set so a direct+ # assignment surfaces a validation error rather than a StatementInvalid.+ validates :reconciled_at, presence: true, if: -> { reconciled_by_statement_id.present? }has_many :child_entries, class_name: "Entry", foreign_key: :parent_entry_id, dependent: :destroy@@ -50,6 +55,11 @@ class Entry < ApplicationRecord)}+ # Reconciliation scopes - see AddReconciliationToEntries+ scope :reconciled, -> { where.not(reconciled_at: nil) }+ scope :unreconciled, -> { where(reconciled_at: nil) }+ scope :reconciled_by, ->(statement) { where(reconciled_by_statement_id: statement) }+# Pending transaction scopes - check Transaction.extra for provider pending flags# Works with any provider that stores pending status in extra["provider_name"]["pending"]scope :pending, -> {@@ -295,6 +305,42 @@ class Entry < ApplicationRecordexternal_id.present?end+ # Reconciliation state, following the Quicken uncleared / cleared / reconciled+ # model. Only the last state is stored -- see AddReconciliationToEntries.+ #+ # @return [Symbol] :uncleared, :cleared or :reconciled+ def reconciliation_state+ return :reconciled if reconciled?+ return :cleared if cleared?++ :uncleared+ end++ # The institution has acknowledged this transaction: it either arrived from a+ # provider, or was entered by hand and later claimed by one (which stamps+ # external_id and source -- see Account::ProviderImportAdapter). Derived rather+ # than stored so it cannot drift, and deliberately not user-settable: this is a+ # fact about where the entry came from, not an opinion about it.+ def cleared?+ external_id.present? || source.present?+ end++ # A statement has been matched against this transaction. Unlike cleared?, this+ # is a judgement -- made by a statement import, or by the user directly -- so+ # it is stored and can be undone.+ def reconciled?+ reconciled_at.present?+ end++ # @param statement [AccountStatement, nil] the statement providing the evidence+ def mark_reconciled!(statement: nil, at: Time.current)+ update!(reconciled_at: at, reconciled_by_statement: statement)+ end++ def unmark_reconciled!+ update!(reconciled_at: nil, reconciled_by_statement: nil)+ end+# Checks if entry should be protected from provider sync overwrites.# This does NOT prevent user from editing - only protects from automated sync.#diff --git a/app/models/import.rb b/app/models/import.rbindex 6d92a01e8b..eb10615cc5 100644--- a/app/models/import.rb+++ b/app/models/import.rb@@ -319,11 +319,12 @@ class Import < ApplicationRecordImport.transaction doaccounts.destroy_allentries.destroy_all+ revert_derived_state!endfamily.sync_later- update! status: :pending+ update! status: status_after_revertrescue => errorupdate! status: :revert_failed, error: error.messageend@@ -531,6 +532,19 @@ class Import < ApplicationRecordendprivate+ # Hook for import types that also maintain state outside their own rows and+ # entries -- PdfImport records statement reconciliation on entries it did+ # not create, and destroying its own entries does not unwind that. Runs+ # inside revert's transaction, so a failure here rolls the whole revert back.+ def revert_derived_state!+ end++ # Where the record lands once its data is gone. Most imports return to+ # pending with their rows intact, ready to be published again.+ def status_after_revert+ :pending+ end+# Commit signal for import types whose records hang off the family rather# than the import itself (Category/Merchant/Rule imports create no entries# or accounts, so the base data_committed? can't see them). import! runs asdiff --git a/app/models/pdf_import.rb b/app/models/pdf_import.rbindex 120c74c8e2..147cbc141b 100644--- a/app/models/pdf_import.rb+++ b/app/models/pdf_import.rb@@ -106,11 +106,29 @@ class PdfImport < Importtransaction domappings.each(&:create_mappable!)- new_transactions = rows.map do |row|- category = mappings.categories.mappable_for(row.category)+ # Rows were already filtered against existing records when they were+ # generated, but a provider sync can land in between, so check again here+ # the way TransactionImport#import! does.+ adapter = Account::ProviderImportAdapter.new(account)+ # Entries this statement already consumed during row generation are spoken+ # for. Without excluding them, a statement carrying two same-amount+ # transactions where the account held only one would re-match the surviving+ # row against that same entry and silently drop a genuinely new+ # transaction. Newly synced entries are still caught, because only the+ # already-reconciled ones are excluded.+ claimed = reconciled_entries.pluck(:id)+ reconciled_now = []+ reconciled_at = Time.current++ new_transactions = rows.filter_map do |row|+ if (existing = already_recorded_entry(adapter, row, claimed))+ claimed << existing.id+ reconciled_now << existing+ next+ endTransaction.new(- category: category,+ category: mappings.categories.mappable_for(row.category),entry: Entry.new(account: account,date: row.date_iso,@@ -119,25 +137,61 @@ class PdfImport < Importcurrency: row.currency,notes: row.notes,import: self,- import_locked: true+ import_locked: true,+ # Born reconciled: the statement being imported is the evidence.+ # Set by id rather than association so activerecord-import writes the+ # column directly on the recursive insert.+ reconciled_at: reconciled_at,+ reconciled_by_statement_id: account_statement&.id))endTransaction.import!(new_transactions, recursive: true) if new_transactions.any?+ reconcile_entries!(reconciled_now, at: reconciled_at)endend+ # Re-targeting is destructive: it releases the statement's evidence on the+ # account being left and rebuilds the rows from scratch. Returns false rather+ # than doing any of that when the import is no longer re-targetable, so a+ # back-button or replayed PATCH cannot unwind a published import.def assign_account!(account)- transaction do+ with_lock do+ return false unless reassignable?++ previous_account_id = account_idupdate!(account: account)+if (statement = account_statement)statement.lock!statement.link_to_account!(account) if statement.account_id != account.idend++ next true if previous_account_id == account.id++ # Matching is per-account, so anything reconciled against the old account+ # is no longer evidence-backed, and the rows have to be judged again.+ release_reconciliations!(previous_account_id)+ if has_extracted_transactions?+ generate_rows_from_extracted_data+ sync_mappings+ refresh_status_after_regeneration!+ end++ trueendend+ # A published import's entries already live in the account it was published+ # to, and a running job owns the record while it is importing or reverting.+ # An import that reconciled every line is still re-targetable: it is complete+ # but committed nothing of its own, and the user may well have picked the+ # wrong account.+ def reassignable?+ !data_committed? && !importing? && !reverting?+ end+def pdf_uploaded?statement_backed? || pdf_file.attached?end@@ -203,8 +257,13 @@ class PdfImport < Importraise error_messageend- update!(extracted_data: response.data)- response.data+ # BankStatementExtractor returns symbol keys, but every reader here (and in+ # generate_rows_from_extracted_data) digs with strings. jsonb keeps the hash+ # exactly as assigned until the record is reloaded, so without this the+ # in-memory read comes back empty and the import produces no rows at all.+ data = response.data.deep_stringify_keys+ update!(extracted_data: data)+ dataenddef bank_statement?@@ -225,7 +284,12 @@ class PdfImport < Importdef generate_rows_from_extracted_datatransaction do- rows.destroy_all+ # insert_all! below bypasses ActiveRecord, so the `rows` association is+ # never populated with what it wrote. Reload before destroying, or a second+ # call on the same in-memory record (assign_account! regenerating after+ # ProcessPdfJob already generated) clears a stale empty collection, deletes+ # nothing, and collides on (import_id, source_row_number).+ rows.reload.destroy_allunless has_extracted_transactions?update_column(:rows_count, 0)@@ -233,10 +297,9 @@ class PdfImport < Importendcurrency = account&.currency || family.currency-- mapped_rows = extracted_transactions.map.with_index(1) do |txn, index|- {- import_id: id,+ candidates = extracted_transactions.map.with_index(1) do |txn, index|+ Import::Row.new(+ import: self,source_row_number: index,date: format_date_for_import(txn["date"]),amount: txn["amount"].to_s,@@ -244,14 +307,83 @@ class PdfImport < Importcategory: txn["category"].to_s,notes: txn["notes"].to_s,currency: currency+ )+ end++ unmatched, matched_entries = partition_already_recorded(candidates)++ reconcile_entries!(matched_entries)++ mapped_rows = unmatched.map.with_index(1) do |row, index|+ {+ import_id: id,+ source_row_number: index,+ date: row.date,+ amount: row.amount,+ name: row.name,+ category: row.category,+ notes: row.notes,+ currency: row.currency}endImport::Row.insert_all!(mapped_rows) if mapped_rows.any?+ # Drop the now-stale association cache so later reads (sync_mappings, the+ # view) see what was actually written.+ rows.resetupdate_column(:rows_count, mapped_rows.size)endend+ # Transactions this statement reconciled against records that already existed.+ # Derived from the statement link rather than stored, so it cannot go stale.+ def reconciled_entries+ return Entry.none if account_statement.blank?++ Entry.reconciled_by(account_statement)+ end++ # The half of reconciled_entries this import did not create -- transactions the+ # account already held when the statement arrived. Everything this import+ # creates is born reconciled too, so the two have to be told apart before+ # either count means anything.+ def already_recorded_entries+ reconciled_entries.where.not(id: entries.select(:id))+ end++ # The next three are memoized because the summary dialog and the review screen+ # each read them more than once, and every read is its own COUNT -- rendering+ # the dialog issued roughly fifteen queries for a static summary. They report+ # a finished outcome for display, so a value cached for the life of the+ # request is what callers want; anything re-judging the import recomputes from+ # the entries directly. (`||=` is safe here: 0 is truthy in Ruby.)+ def already_recorded_count+ @already_recorded_count ||= already_recorded_entries.count+ end++ def imported_count+ @imported_count ||= entries.count+ end++ # Rows still on offer. import! creates an entry per row and leaves the rows in+ # place as the record of what was published, so past that point rows_count is+ # a history, not a queue. Memoized mostly for data_committed?, which is two+ # more EXISTS queries every time it is asked.+ def awaiting_review_count+ @awaiting_review_count ||= data_committed? ? 0 : rows_count+ end++ # No query: extracted_data is already in memory.+ def extracted_count+ extracted_transactions.size+ end++ # Whether the statement described transactions the account already had. The+ # difference between "nothing to import" and "nothing was found".+ def reconciled_anything?+ already_recorded_count.positive?+ end+def send_next_steps_email(user)PdfImportMailer.with(user: user,@@ -323,6 +455,131 @@ class PdfImport < Importprivate+ # A statement's posting date routinely differs by a day or two from the date+ # a provider recorded for the same transaction, so matching allows a small+ # window rather than demanding an exact date.+ RECONCILIATION_DATE_WINDOW = 3++ # Splits candidate rows into those that are genuinely new and the existing+ # entries the rest already correspond to. Matching is per-account, so with no+ # account assigned yet every row is treated as new and judged again once the+ # user picks one (see assign_account!).+ def partition_already_recorded(candidates)+ return [ candidates, [] ] if account.blank?++ adapter = Account::ProviderImportAdapter.new(account)+ claimed = []+ unmatched = []+ matched = []++ candidates.each do |row|+ if (existing = already_recorded_entry(adapter, row, claimed))+ claimed << existing.id+ matched << existing+ else+ unmatched << row+ end+ end++ [ unmatched, matched ]+ end++ # Name is deliberately not part of the match: statement descriptions and+ # provider names for the same transaction rarely agree, and the adapter makes+ # the same choice for provider sync.+ def already_recorded_entry(adapter, row, claimed)+ adapter.find_duplicate_transaction(+ date: row.date_iso,+ amount: row.signed_amount,+ currency: row.currency,+ exclude_entry_ids: claimed,+ date_window: RECONCILIATION_DATE_WINDOW,+ include_provider_entries: true+ )+ rescue ArgumentError, TypeError => e # Date::Error subclasses ArgumentError+ # A row whose date or amount will not parse cannot be judged. Offer it for+ # import rather than dropping it silently -- the review step surfaces it.+ DebugLogEntry.capture(+ category: "import",+ level: "warn",+ message: "PdfImport: could not evaluate statement row for reconciliation (#{e.class})",+ source: "pdf_import",+ family: family,+ account: account,+ metadata: {+ import_id: id,+ account_statement_id: account_statement_id,+ source_row_number: row.source_row_number,+ raw_date: row.date,+ raw_amount: row.amount,+ error_class: e.class.name+ }+ )+ nil+ end++ def reconcile_entries!(entries, at: Time.current)+ return if entries.blank?++ Entry.where(id: entries.map(&:id)).update_all(+ reconciled_at: at,+ reconciled_by_statement_id: account_statement&.id,+ updated_at: at+ )+ end++ # Regeneration can empty the row set (everything now matches) or refill it+ # (the new account matches nothing). Status has to follow, using the same+ # rule ProcessPdfJob applies after initial processing -- otherwise a+ # fully-matched import sits at pending with no rows, which renders as the+ # processing screen forever and cannot be restarted.+ def refresh_status_after_regeneration!+ return if data_committed?+ return unless pending? || complete?++ target = statement_with_transactions? && rows_count > 0 ? "pending" : "complete"+ update!(status: target) unless status.to_s == target+ end++ # Scoped to the account being moved away from. A statement is evidence for+ # exactly one account at a time, but it can back more than one import, so an+ # unscoped release would clear reconciliations another account still relies+ # on. Nothing is reconciled while no account is assigned, so a blank scope+ # has nothing to release.+ def release_reconciliations!(account_scope_id)+ return if account_statement.blank? || account_scope_id.blank?++ Entry.reconciled_by(account_statement).where(account_id: account_scope_id).update_all(+ reconciled_at: nil,+ reconciled_by_statement_id: nil,+ updated_at: Time.current+ )+ end++ # Reverting a statement import unwinds its evidence as well as its rows. The+ # entries it created are already destroyed by the time this runs; the ones it+ # only matched keep marks this statement no longer backs. Releasing and then+ # regenerating re-judges every statement line against what the account+ # actually holds now, so the review screen offers exactly what is missing.+ def revert_derived_state!+ release_reconciliations!(account_id)+ return unless has_extracted_transactions?++ generate_rows_from_extracted_data+ # A line that matched at publish time carried no row and so no mapping.+ # If it no longer matches it is a row again, and needs one.+ sync_mappings+ end++ # A statement whose every line still matches something -- a provider-synced+ # account, say -- reverts to zero rows. Returning that to pending renders the+ # processing screen with no way out, so an import with nothing left to offer+ # finishes as complete, the same way refresh_status_after_regeneration! ends+ # a fully reconciled import.+ def status_after_revert+ statement_with_transactions? && rows_count > 0 ? :pending : :complete+ end+def format_date_for_import(date_str)return "" if date_str.blank?diff --git a/app/views/imports/_pdf_import.html.erb b/app/views/imports/_pdf_import.html.erbindex f9e23e10b3..75d424704e 100644--- a/app/views/imports/_pdf_import.html.erb+++ b/app/views/imports/_pdf_import.html.erb@@ -36,14 +36,26 @@<div class="space-y-2"><h2 class="font-medium text-primary"><%= t("imports.pdf_import.transactions_extracted") %></h2><p class="text-sm text-secondary px-3 py-2 bg-container-inset rounded-lg">- <%= t("imports.pdf_import.transactions_extracted_count", count: import.rows_count) %>+ <%# rows_count is what is left to import, not what the statement held:+ anything the account already had was matched and withheld. Calling+ that number "extracted" under-reports the statement. %>+ <%= t("imports.pdf_import.transactions_extracted_count", count: import.extracted_count) %>+ <% if import.reconciled_anything? %>+ <span class="block mt-1 text-xs text-subdued">+ <%= t("imports.pdf_import.already_recorded_note", count: import.already_recorded_count) %>+ </span>+ <% end %></p></div><div class="space-y-2"><h2 id="pdf-import-select-account" class="font-medium text-primary"><%= t("imports.pdf_import.select_account") %></h2><%= styled_form_with model: import, scope: :import, url: import_path(import), method: :patch, class: "space-y-2" do |f| %>- <% accounts = Current.user.accessible_accounts.manual.alphabetically.pluck(:name, :id) %>+ <%# Provider-backed accounts are offered too: rows are matched against+ existing transactions before they are ever shown, so importing a+ statement for a synced account can no longer duplicate what sync+ already brought in. %>+ <% accounts = Current.user.accessible_accounts.alphabetically.pluck(:name, :id) %><% if accounts.any? %><%= f.select :account_id, accounts,{ include_blank: t("imports.pdf_import.select_account_placeholder"), selected: import.account_id, label: false },@@ -79,6 +91,7 @@<% else %><p class="text-center text-sm text-secondary"><%= t("imports.pdf_import.select_account_to_continue") %></p><% end %>+ <%= render DS::Link.new(text: t("imports.pdf_import.view_summary"), href: summary_import_path(import), variant: "secondary", full_width: true, frame: :modal) %><%= render DS::Link.new(text: t("imports.pdf_import.back_to_imports"), href: imports_path, variant: "secondary", full_width: true) %></div>@@ -128,7 +141,13 @@<div class="text-center space-y-2"><h1 class="font-medium text-primary text-center text-3xl"><%= t("imports.pdf_import.complete_title") %></h1>- <p class="text-sm text-secondary"><%= t("imports.pdf_import.complete_description") %></p>+ <%# A statement whose every line was already on file creates nothing, and+ the generic description reads as though the import did nothing at all. %>+ <% if import.imported_count.zero? && import.reconciled_anything? %>+ <p class="text-sm text-secondary"><%= t("imports.pdf_import.complete_fully_reconciled", count: import.already_recorded_count) %></p>+ <% else %>+ <p class="text-sm text-secondary"><%= t("imports.pdf_import.complete_description") %></p>+ <% end %></div><div class="bg-container border border-primary rounded-xl p-4 space-y-4">@@ -161,7 +180,8 @@</div><div class="space-y-2 flex flex-col">- <%= render DS::Link.new(text: t("imports.pdf_import.back_to_imports"), href: imports_path, variant: "primary", full_width: true) %>+ <%= render DS::Link.new(text: t("imports.pdf_import.view_summary"), href: summary_import_path(import), variant: "primary", full_width: true, frame: :modal) %>+ <%= render DS::Link.new(text: t("imports.pdf_import.back_to_imports"), href: imports_path, variant: "secondary", full_width: true) %><%= render DS::Button.new(text: t("imports.pdf_import.delete_import"),href: import_path(import),diff --git a/app/views/imports/summary.html.erb b/app/views/imports/summary.html.erbnew file mode 100644index 0000000000..336a83300e--- /dev/null+++ b/app/views/imports/summary.html.erb@@ -0,0 +1,61 @@+<%# Where every transaction the statement listed ended up. Counts are derived+ from the entries themselves rather than stored on the import, so they stay+ true if a later sync or edit changes the picture. %>+<%= render DS::Dialog.new(width: "md") do |dialog| %>+ <% dialog.with_header(+ title: t(".title"),+ subtitle: @import.account.present? ? t(".subtitle", account: @import.account.name) : t(".subtitle_no_account")+ ) %>++ <% dialog.with_body do %>+ <div class="space-y-4">+ <dl class="divide-y divide-alpha-black-200 theme-dark:divide-alpha-white-200 border border-primary rounded-xl overflow-hidden">+ <div class="flex items-center justify-between gap-4 px-4 py-3">+ <dt class="text-sm text-secondary"><%= t(".extracted") %></dt>+ <dd class="text-sm font-medium text-primary tabular-nums"><%= @import.extracted_count %></dd>+ </div>++ <div class="flex items-center justify-between gap-4 px-4 py-3">+ <dt class="text-sm text-secondary">+ <%= t(".already_recorded") %>+ <span class="block text-xs text-subdued"><%= t(".already_recorded_hint") %></span>+ </dt>+ <dd class="text-sm font-medium text-primary tabular-nums"><%= @import.already_recorded_count %></dd>+ </div>++ <% if @import.imported_count.positive? %>+ <div class="flex items-center justify-between gap-4 px-4 py-3">+ <dt class="text-sm text-secondary"><%= t(".imported") %></dt>+ <dd class="text-sm font-medium text-primary tabular-nums"><%= @import.imported_count %></dd>+ </div>+ <% end %>++ <% if @import.awaiting_review_count.positive? %>+ <div class="flex items-center justify-between gap-4 px-4 py-3">+ <dt class="text-sm text-secondary"><%= t(".awaiting_review") %></dt>+ <dd class="text-sm font-medium text-primary tabular-nums"><%= @import.awaiting_review_count %></dd>+ </div>+ <% end %>+ </dl>++ <%# The case this dialog exists for: an import that finished having created+ nothing looks identical to one that found nothing. %>+ <% if @import.reconciled_anything? && @import.awaiting_review_count.zero? && @import.imported_count.zero? %>+ <p class="text-sm text-secondary px-3 py-2 bg-container-inset rounded-lg">+ <%= t(".fully_reconciled", count: @import.already_recorded_count) %>+ </p>+ <% end %>++ <% if @import.account_statement.present? %>+ <p class="text-xs text-subdued">+ <%= t(".statement_evidence_html",+ statement: link_to(@import.account_statement.filename,+ account_statement_path(@import.account_statement),+ class: "text-primary hover:text-primary-hover underline")) %>+ </p>+ <% end %>+ </div>+ <% end %>++ <% dialog.with_action(cancel_action: true, text: t(".close"), variant: "secondary", full_width: true) %>+<% end %>diff --git a/config/locales/views/imports/en.yml b/config/locales/views/imports/en.ymlindex 1a93dfbe12..6e4f9ff54a 100644--- a/config/locales/views/imports/en.yml+++ b/config/locales/views/imports/en.yml@@ -283,8 +283,23 @@ en:category_icon: "Lucide icon"merchant_color: "Color"merchant_website: "Website URL"+ summary:+ title: "Import summary"+ subtitle: "What became of each transaction on this statement in %{account}."+ subtitle_no_account: "What became of each transaction on this statement."+ extracted: "Found on the statement"+ already_recorded: "Already recorded"+ already_recorded_hint: "Matched to a transaction this account already had, and marked reconciled."+ imported: "Imported as new"+ awaiting_review: "Waiting to be imported"+ fully_reconciled:+ one: "Nothing needed importing — the statement's only transaction was already on file."+ other: "Nothing needed importing — all %{count} transactions were already on file."+ statement_evidence_html: "Reconciled against %{statement}."+ close: "Close"update:account_saved: "Account saved."+ account_locked: "This import has already been published, so its account can't be changed. Revert it first if you need to import it somewhere else."invalid_account: "Account not found."publish:started: "Your import has started in the background."@@ -479,7 +494,9 @@ en:processing_failed_with_message: "%{message}"processing_failed_generic: "Processing failed: %{error}"ready_for_review_title: Ready for Review- ready_for_review_description: "We extracted %{count} transactions from your statement. Review and publish them to add to your account."+ ready_for_review_description:+ one: "%{count} transaction from your statement isn't in this account yet. Review and publish it to add it."+ other: "%{count} transactions from your statement aren't in this account yet. Review and publish them to add them."transactions_extracted: Transactions Extractedtransactions_extracted_count:one: "%{count} transaction"@@ -494,5 +511,12 @@ en:one: "Publish %{count} Transaction"other: "Publish %{count} Transactions"review_transactions: Review Transactions+ view_summary: View import summary+ already_recorded_note:+ one: "%{count} was already in this account and was matched to the statement."+ other: "%{count} were already in this account and were matched to the statement."+ complete_fully_reconciled:+ one: "Every transaction on this statement was already in your account. %{count} was matched and marked reconciled — nothing needed importing."+ other: "Every transaction on this statement was already in your account. All %{count} were matched and marked reconciled — nothing needed importing."select_account_to_continue: Please select an account above to continue.unknown_document_type: Unknowndiff --git a/config/routes.rb b/config/routes.rbindex 628351161a..b104fc3652 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -434,6 +434,7 @@ Rails.application.routes.draw doput :revertput :apply_templatepost :cancel+ get :summaryendresource :upload, only: %i[show update], module: :importdiff --git a/db/migrate/20260820120000_add_reconciliation_to_entries.rb b/db/migrate/20260820120000_add_reconciliation_to_entries.rbnew file mode 100644index 0000000000..273074893b--- /dev/null+++ b/db/migrate/20260820120000_add_reconciliation_to_entries.rb@@ -0,0 +1,62 @@+class AddReconciliationToEntries < ActiveRecord::Migration[7.2]+ # entries is the largest table in the app, so the indexes are built+ # concurrently and the check constraint is added unvalidated then validated+ # separately -- VALIDATE takes only SHARE UPDATE EXCLUSIVE, so neither step+ # blocks writes for the length of a full scan.+ disable_ddl_transaction!++ # Reconciliation follows the Quicken model of uncleared / cleared / reconciled,+ # but only the last state is stored.+ #+ # "Cleared" means the institution acknowledged the transaction, which is+ # exactly what entries.source and entries.external_id already record — and it+ # stays accurate on its own, because Account::ProviderImportAdapter stamps both+ # onto a manually-entered entry when a provider transaction claims it. Storing+ # a separate flag would duplicate that truth and let it drift.+ #+ # "Reconciled" means a specific statement was matched against the transaction.+ # Nothing in the schema can derive that, so it is recorded here.+ def up+ add_column :entries, :reconciled_at, :datetime, null: true++ add_reference :entries,+ :reconciled_by_statement,+ type: :uuid,+ null: true,+ index: false,+ foreign_key: { to_table: :account_statements, on_delete: :nullify }++ # Supports "what has this statement reconciled?" when unwinding a statement,+ # and is narrow because the reconciled rows are a small slice of entries.+ add_index :entries,+ :reconciled_by_statement_id,+ where: "reconciled_by_statement_id IS NOT NULL",+ name: "index_entries_on_reconciled_by_statement",+ algorithm: :concurrently++ # Supports the per-account reconciled/unreconciled split the import review+ # screen and the account ledger both need.+ add_index :entries,+ [ :account_id, :reconciled_at ],+ where: "reconciled_at IS NOT NULL",+ name: "index_entries_on_account_and_reconciled_at",+ algorithm: :concurrently++ # An entry can be reconciled without a statement on file (marked by hand, or+ # the statement was later deleted and the FK nulled), but it can never point+ # at a statement without being reconciled.+ add_check_constraint :entries,+ "reconciled_by_statement_id IS NULL OR reconciled_at IS NOT NULL",+ name: "chk_entries_reconciled_at_present_when_statement_set",+ validate: false+ validate_check_constraint :entries, name: "chk_entries_reconciled_at_present_when_statement_set"+ end++ def down+ remove_check_constraint :entries, name: "chk_entries_reconciled_at_present_when_statement_set"+ remove_index :entries, name: "index_entries_on_account_and_reconciled_at", algorithm: :concurrently+ remove_index :entries, name: "index_entries_on_reconciled_by_statement", algorithm: :concurrently+ remove_reference :entries, :reconciled_by_statement, type: :uuid, foreign_key: { to_table: :account_statements }+ remove_column :entries, :reconciled_at+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 59960979e5..c28397175d 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[7.2].define(version: 2026_08_18_060353) do+ActiveRecord::Schema[7.2].define(version: 2026_08_20_120000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pgcrypto"enable_extension "plpgsql"@@ -656,6 +656,8 @@ ActiveRecord::Schema[7.2].define(version: 2026_08_18_060353) dot.boolean "user_modified", default: false, null: falset.boolean "import_locked", default: false, null: falset.uuid "parent_entry_id"+ t.datetime "reconciled_at"+ t.uuid "reconciled_by_statement_id"t.index "lower((name)::text)", name: "index_entries_on_lower_name"t.index ["account_id", "date", "entryable_id"], name: "index_entries_on_investment_totals_lookup", where: "(((entryable_type)::text = 'Trade'::text) AND (excluded = false))"t.index ["account_id", "date"], name: "index_entries_on_account_id_and_date"@@ -668,6 +670,9 @@ ActiveRecord::Schema[7.2].define(version: 2026_08_18_060353) dot.index ["import_locked"], name: "index_entries_on_import_locked_true", where: "(import_locked = true)"t.index ["parent_entry_id"], name: "index_entries_on_parent_entry_id"t.index ["user_modified"], name: "index_entries_on_user_modified_true", where: "(user_modified = true)"+ t.index ["account_id", "reconciled_at"], name: "index_entries_on_account_and_reconciled_at", where: "(reconciled_at IS NOT NULL)"+ t.index ["reconciled_by_statement_id"], name: "index_entries_on_reconciled_by_statement", where: "(reconciled_by_statement_id IS NOT NULL)"+ t.check_constraint "reconciled_by_statement_id IS NULL OR reconciled_at IS NOT NULL", name: "chk_entries_reconciled_at_present_when_statement_set"endcreate_table "eval_datasets", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|@@ -2376,6 +2381,7 @@ ActiveRecord::Schema[7.2].define(version: 2026_08_18_060353) doadd_foreign_key "debug_log_entries", "users", on_delete: :nullifyadd_foreign_key "enable_banking_accounts", "enable_banking_items"add_foreign_key "enable_banking_items", "families"+ add_foreign_key "entries", "account_statements", column: "reconciled_by_statement_id", on_delete: :nullifyadd_foreign_key "entries", "accounts", on_delete: :cascadeadd_foreign_key "entries", "entries", column: "parent_entry_id", on_delete: :cascadeadd_foreign_key "entries", "imports"diff --git a/test/controllers/imports_controller_test.rb b/test/controllers/imports_controller_test.rbindex 42ca620a8b..eb6ad3cd41 100644--- a/test/controllers/imports_controller_test.rb+++ b/test/controllers/imports_controller_test.rb@@ -113,6 +113,19 @@ class ImportsControllerTest < ActionDispatch::IntegrationTestassert_equal I18n.t("imports.create.document_uploaded"), flash[:notice]end+ test "summary renders the import outcome for a pdf import" do+ get summary_import_url(imports(:pdf_with_rows))++ assert_response :success+ assert_select "dialog"+ end++ test "summary is not available for non-pdf imports" do+ get summary_import_url(imports(:transaction))++ assert_response :not_found+ end+test "uploads pdf document as PdfImport when using DocumentImport option" doadapter = mock("vector_store_adapter")adapter.stubs(:supported_extensions).returns(%w[.pdf .txt])diff --git a/test/models/account/provider_import_adapter_statement_test.rb b/test/models/account/provider_import_adapter_statement_test.rbnew file mode 100644index 0000000000..d708f72e66--- /dev/null+++ b/test/models/account/provider_import_adapter_statement_test.rb@@ -0,0 +1,86 @@+require "test_helper"++# Covers the two options find_duplicate_transaction grew for statement imports:+# seeing provider-sourced entries, and tolerating a small date difference.+class Account::ProviderImportAdapterStatementTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @account = accounts(:depository)+ @adapter = Account::ProviderImportAdapter.new(@account)+ @date = Date.current+ end++ test "provider-synced entries stay invisible by default" do+ create_transaction(account: @account, date: @date, amount: 50, external_id: "plaid-1", source: "plaid")++ assert_nil @adapter.find_duplicate_transaction(date: @date, amount: 50, currency: "USD")+ end++ test "provider-synced entries are found when the caller opts in" do+ synced = create_transaction(account: @account, date: @date, amount: 50, external_id: "plaid-1", source: "plaid")++ found = @adapter.find_duplicate_transaction(+ date: @date, amount: 50, currency: "USD", include_provider_entries: true+ )++ assert_equal synced, found+ end++ test "manual entries are still found when opting in" do+ manual = create_transaction(account: @account, date: @date, amount: 50)++ found = @adapter.find_duplicate_transaction(+ date: @date, amount: 50, currency: "USD", include_provider_entries: true+ )++ assert_equal manual, found+ end++ test "an exact-date search ignores neighbouring dates" do+ create_transaction(account: @account, date: @date - 2, amount: 50)++ assert_nil @adapter.find_duplicate_transaction(date: @date, amount: 50, currency: "USD")+ end++ test "a windowed search finds a nearby date" do+ nearby = create_transaction(account: @account, date: @date - 2, amount: 50)++ found = @adapter.find_duplicate_transaction(date: @date, amount: 50, currency: "USD", date_window: 3)++ assert_equal nearby, found+ end++ test "a windowed search prefers the closest date" do+ create_transaction(account: @account, date: @date - 3, amount: 50, name: "Far")+ closest = create_transaction(account: @account, date: @date + 1, amount: 50, name: "Near")++ found = @adapter.find_duplicate_transaction(date: @date, amount: 50, currency: "USD", date_window: 3)++ assert_equal closest, found+ end++ test "a windowed search still respects the window edge" do+ create_transaction(account: @account, date: @date - 5, amount: 50)++ assert_nil @adapter.find_duplicate_transaction(date: @date, amount: 50, currency: "USD", date_window: 3)+ end++ test "amount and currency still have to match exactly" do+ create_transaction(account: @account, date: @date, amount: 50)++ assert_nil @adapter.find_duplicate_transaction(date: @date, amount: 51, currency: "USD", date_window: 3)+ assert_nil @adapter.find_duplicate_transaction(date: @date, amount: 50, currency: "EUR", date_window: 3)+ end++ test "already-claimed entries are excluded" do+ first = create_transaction(account: @account, date: @date, amount: 50)+ second = create_transaction(account: @account, date: @date, amount: 50)++ found = @adapter.find_duplicate_transaction(+ date: @date, amount: 50, currency: "USD", date_window: 3, exclude_entry_ids: [ first.id ]+ )++ assert_equal second, found+ end+enddiff --git a/test/models/entry_reconciliation_test.rb b/test/models/entry_reconciliation_test.rbnew file mode 100644index 0000000000..083d72f2ea--- /dev/null+++ b/test/models/entry_reconciliation_test.rb@@ -0,0 +1,98 @@+require "test_helper"++class EntryReconciliationTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @account = accounts(:depository)+ @statement = create_statement+ end++ test "an entry with no provenance is uncleared" do+ entry = create_transaction(account: @account)++ assert_equal :uncleared, entry.reconciliation_state+ assert_not entry.cleared?+ assert_not entry.reconciled?+ end++ test "an entry carrying provider provenance is cleared without storing a flag" do+ from_external_id = create_transaction(account: @account, external_id: "plaid-1")+ from_source = create_transaction(account: @account, source: "simplefin")++ assert_equal :cleared, from_external_id.reconciliation_state+ assert_equal :cleared, from_source.reconciliation_state+ end++ test "reconciled outranks cleared" do+ entry = create_transaction(account: @account, source: "plaid")+ entry.mark_reconciled!(statement: @statement)++ assert_equal :reconciled, entry.reload.reconciliation_state+ assert_equal @statement, entry.reconciled_by_statement+ end++ test "reconciling is reversible but clearing is not affected by it" do+ entry = create_transaction(account: @account, source: "plaid")+ entry.mark_reconciled!(statement: @statement)+ entry.unmark_reconciled!++ assert_equal :cleared, entry.reload.reconciliation_state+ assert_nil entry.reconciled_at+ assert_nil entry.reconciled_by_statement_id+ end++ test "an entry can be reconciled by hand with no statement on file" do+ entry = create_transaction(account: @account)+ entry.mark_reconciled!++ assert entry.reload.reconciled?+ assert_nil entry.reconciled_by_statement_id+ end++ test "an entry cannot cite a statement without being reconciled" do+ entry = create_transaction(account: @account)+ entry.reconciled_by_statement = @statement++ # Mirrors chk_entries_reconciled_at_present_when_statement_set: the model+ # rejects it before the database constraint is reached.+ assert_not entry.valid?+ assert_predicate entry.errors[:reconciled_at], :any?+ end++ test "scopes partition reconciled from unreconciled" do+ reconciled = create_transaction(account: @account)+ unreconciled = create_transaction(account: @account)+ reconciled.mark_reconciled!(statement: @statement)++ assert_includes Entry.reconciled, reconciled+ assert_not_includes Entry.reconciled, unreconciled+ assert_includes Entry.unreconciled, unreconciled+ assert_includes Entry.reconciled_by(@statement), reconciled+ end++ test "deleting the statement leaves the entry reconciled but unevidenced" do+ entry = create_transaction(account: @account)+ entry.mark_reconciled!(statement: @statement)++ @statement.destroy!++ entry.reload+ assert entry.reconciled?, "reconciliation should survive losing the evidence"+ assert_nil entry.reconciled_by_statement_id+ end++ private++ def create_statement(account: @account, filename: "statement.pdf")+ AccountStatement.create_from_upload!(+ family: account.family,+ account: account,+ file: uploaded_file(+ filename: filename,+ content_type: "application/pdf",+ content: file_fixture("imports/sample_bank_statement.pdf").binread+ )+ )+ end+enddiff --git a/test/models/pdf_import_reconciliation_test.rb b/test/models/pdf_import_reconciliation_test.rbnew file mode 100644index 0000000000..58783a6b47--- /dev/null+++ b/test/models/pdf_import_reconciliation_test.rb@@ -0,0 +1,403 @@+require "test_helper"++# The behaviour issue #1379 actually asked for: a statement should only offer+# transactions that are not already recorded, and should mark the rest reconciled.+class PdfImportReconciliationTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @account = accounts(:depository)+ @family = @account.family+ @statement = create_statement+ @import = PdfImport.create_from_statement!(statement: @statement)+ @import.update!(document_type: "bank_statement")+ @date = Date.current+ end++ # Extractor convention: negative for debits, positive for credits. Import+ # signage ("inflows_positive") flips that into Entry convention, where an+ # expense is positive.+ def extracted(date:, amount:, name:)+ { "date" => date.to_s, "amount" => amount.to_s, "name" => name }+ end++ test "rows are only generated for transactions that are not already recorded" do+ create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")++ @import.update!(extracted_data: { "transactions" => [+ extracted(date: @date, amount: -50, name: "COFFEE SHOP"),+ extracted(date: @date, amount: -12, name: "BOOKSTORE")+ ] })++ @import.generate_rows_from_extracted_data++ assert_equal 1, @import.reload.rows_count+ assert_equal "BOOKSTORE", @import.rows.sole.name+ end++ test "the already-recorded transaction is marked reconciled against the statement" do+ existing = create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")++ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "COFFEE SHOP") ] })+ @import.generate_rows_from_extracted_data++ existing.reload+ assert_equal :reconciled, existing.reconciliation_state+ assert_equal @statement, existing.reconciled_by_statement+ assert_equal [ existing ], @import.reconciled_entries.to_a+ end++ test "a provider-synced transaction counts as already recorded" do+ synced = create_transaction(+ account: @account, date: @date, amount: 50, name: "COFFEE", external_id: "plaid-1", source: "plaid"+ )++ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee Shop") ] })+ @import.generate_rows_from_extracted_data++ assert_equal 0, @import.reload.rows_count+ assert_equal :reconciled, synced.reload.reconciliation_state+ end++ test "a statement date a day or two off the recorded date still matches" do+ create_transaction(account: @account, date: @date - 2, amount: 50, name: "Coffee")++ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data++ assert_equal 0, @import.reload.rows_count+ end++ test "two identical statement lines do not both match one recorded transaction" do+ create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")++ @import.update!(extracted_data: { "transactions" => [+ extracted(date: @date, amount: -50, name: "Coffee"),+ extracted(date: @date, amount: -50, name: "Coffee")+ ] })+ @import.generate_rows_from_extracted_data++ assert_equal 1, @import.reload.rows_count, "the second identical line is genuinely new"+ end++ test "with no account assigned every transaction is offered" do+ @import.update!(account: nil)+ create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")++ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data++ assert_equal 1, @import.reload.rows_count+ end++ test "a row whose date cannot be parsed is offered rather than dropped" do+ @import.update!(extracted_data: { "transactions" => [+ { "date" => "not-a-date", "amount" => "-50", "name" => "Mystery" }+ ] })++ @import.generate_rows_from_extracted_data++ assert_equal 1, @import.reload.rows_count+ end++ test "a row whose amount cannot be parsed is offered with its raw value intact" do+ @import.update!(extracted_data: { "transactions" => [+ { "date" => @date.to_s, "amount" => "not-a-number", "name" => "Mystery" }+ ] })++ @import.generate_rows_from_extracted_data++ row = @import.reload.rows.sole+ assert_equal 1, @import.rows_count+ # Stored verbatim rather than coerced to 0, so the review step shows the user+ # what the statement actually said.+ assert_equal "not-a-number", row.amount+ end++ test "reassigning the account re-judges the rows and releases the old reconciliation" do+ other = @family.accounts.create!(+ name: "Second Checking", balance: 0, currency: "USD", accountable: Depository.new+ )+ on_first = create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")++ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data+ assert_equal 0, @import.reload.rows_count++ @import.assign_account!(other)++ assert_not on_first.reload.reconciled?, "the old account's entry is no longer evidence-backed"+ assert_equal 1, @import.reload.rows_count, "nothing on the new account matches, so it is offered"+ end++ test "extract_transactions stores string keys so rows can actually be generated" do+ provider = mock("llm_provider")+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)+ provider.stubs(:extract_bank_statement).returns(+ OpenStruct.new(success?: true, data: { transactions: [ { date: @date.to_s, amount: "-5.0", name: "Coffee" } ] })+ )+ @import.stubs(:pdf_file_content).returns("fake-pdf")++ @import.extract_transactions++ # Without deep_stringify_keys this reads back empty and no rows are built.+ assert_equal 1, @import.extracted_transactions.size+ assert_equal "Coffee", @import.extracted_transactions.first["name"]+ end++ test "publishing does not re-match a row against an entry row generation already consumed" do+ create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")++ # Two identical statement lines, one existing transaction: the first line+ # reconciles against it, the second is genuinely new and must be created.+ @import.update!(extracted_data: { "transactions" => [+ extracted(date: @date, amount: -50, name: "Coffee"),+ extracted(date: @date, amount: -50, name: "Coffee")+ ] })+ @import.generate_rows_from_extracted_data+ assert_equal 1, @import.reload.rows_count++ assert_difference -> { @account.entries.count }, 1 do+ @import.import!+ end+ end++ test "assigning an account that reconciles every row completes the import" do+ @import.update!(account: nil, status: :pending)+ create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")++ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data+ assert_equal 1, @import.reload.rows_count, "nothing matches while no account is assigned"++ @import.assign_account!(@account)++ @import.reload+ assert_equal 0, @import.rows_count+ assert @import.complete?, "a fully reconciled import must finish rather than sit at pending with no rows"+ end++ test "assigning an account that matches nothing returns the import to pending" do+ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data+ @import.update!(status: :complete)++ other = @family.accounts.create!(+ name: "Untouched Checking", balance: 0, currency: "USD", accountable: Depository.new+ )+ # complete but nothing of its own committed: still the user's to re-target.+ assert @import.assign_account!(other)++ @import.reload+ assert_equal 1, @import.rows_count+ assert @import.pending?+ end++ test "a row that cannot be evaluated is recorded in the debug log" do+ @import.update!(extracted_data: { "transactions" => [+ { "date" => "not-a-date", "amount" => "-50", "name" => "Mystery" }+ ] })++ assert_difference "DebugLogEntry.count", 1 do+ @import.generate_rows_from_extracted_data+ end++ logged = DebugLogEntry.last+ assert_equal "import", logged.category+ assert_equal @family, logged.family+ assert_equal @import.id, logged.metadata["import_id"]+ end++ test "regenerating rows twice does not collide on source row numbers" do+ # insert_all! leaves the rows association stale, so a second generation on+ # the same in-memory record used to re-insert source_row_number 1.+ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -12, name: "Bookstore") ] })++ @import.generate_rows_from_extracted_data+ @import.generate_rows_from_extracted_data++ assert_equal 1, @import.reload.rows_count+ assert_equal 1, @import.rows.count+ end++ test "releasing reconciliations leaves another account's evidence intact" do+ other = @family.accounts.create!(+ name: "Sibling Checking", balance: 0, currency: "USD", accountable: Depository.new+ )+ # Same statement, evidence recorded against a second account by another import.+ on_other = create_transaction(account: other, date: @date, amount: 99, name: "Elsewhere")+ on_other.mark_reconciled!(statement: @statement)++ on_first = create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")+ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data+ assert on_first.reload.reconciled?++ @import.assign_account!(other)++ # Both fields matter: reconciled_at is the state, reconciled_by_statement_id+ # is the evidence, and Entry#unmark_reconciled! clears the pair.+ on_first.reload+ assert_not on_first.reconciled?, "the account being left is released"+ assert_nil on_first.reconciled_by_statement_id, "its statement evidence is cleared too"++ on_other.reload+ assert on_other.reconciled?, "another account's evidence must survive"+ assert_equal @statement.id, on_other.reconciled_by_statement_id+ end++ test "reverting a fully reconciled import completes it rather than stranding it at pending" do+ create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")+ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data+ @import.update!(status: :complete)+ assert_equal 0, @import.reload.rows_count++ @import.revert++ @import.reload+ assert_nil @import.error+ # pending with no rows renders the processing screen with no way back out.+ assert @import.complete?, "expected complete, got #{@import.status}"+ assert_equal 0, @import.rows_count+ end++ test "reverting an import puts the transactions it created back on offer" do+ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data+ assert_equal 1, @import.reload.rows_count++ assert_difference -> { @account.entries.count }, 1 do+ @import.import!+ end+ @import.update!(status: :complete)++ assert_difference -> { @account.entries.count }, -1 do+ @import.revert+ end++ @import.reload+ assert @import.pending?, "expected pending, got #{@import.status}"+ assert_equal 1, @import.rows_count, "the created entry is gone, so its statement line is new again"+ end++ test "reverting releases evidence from an entry the statement no longer matches" do+ drifted = create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")+ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data+ assert drifted.reload.reconciled?+ @import.update!(status: :complete)++ # Corrected after the fact, so the statement line no longer describes it.+ drifted.update!(amount: 75)++ @import.revert++ drifted.reload+ assert_not drifted.reconciled?, "a statement that no longer matches must stop claiming the entry"+ assert_nil drifted.reconciled_by_statement_id+ assert_equal 1, @import.reload.rows_count+ assert @import.pending?, "expected pending, got #{@import.status}"+ end++ test "reassigning a published import is refused rather than half-unwinding it" do+ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data+ @import.import!+ @import.update!(status: :complete)++ other = @family.accounts.create!(+ name: "Wrong Turn Checking", balance: 0, currency: "USD", accountable: Depository.new+ )++ assert_not @import.assign_account!(other), "a replayed PATCH must not unwind a published import"++ @import.reload+ assert_equal @account, @import.account+ assert_equal 1, @import.rows_count, "the rows recording what was published survive"+ assert_equal 1, @import.entries.count+ end++ test "reassigning is refused while a job still owns the record" do+ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data+ @import.update!(status: :importing)++ other = @family.accounts.create!(+ name: "Mid Flight Checking", balance: 0, currency: "USD", accountable: Depository.new+ )++ assert_not @import.assign_account!(other)+ assert_equal @account, @import.reload.account+ end++ test "the outcome counts separate what was already recorded from what is new" do+ create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")+ @import.update!(extracted_data: { "transactions" => [+ extracted(date: @date, amount: -50, name: "Coffee"),+ extracted(date: @date, amount: -12, name: "Bookstore")+ ] })+ @import.generate_rows_from_extracted_data+ @import.reload++ assert_equal 2, @import.extracted_count+ assert_equal 1, @import.already_recorded_count+ assert_equal 0, @import.imported_count+ assert_equal 1, @import.awaiting_review_count+ assert @import.reconciled_anything?+ end++ test "publishing moves the offered rows into the imported count" do+ create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")+ @import.update!(extracted_data: { "transactions" => [+ extracted(date: @date, amount: -50, name: "Coffee"),+ extracted(date: @date, amount: -12, name: "Bookstore")+ ] })+ @import.generate_rows_from_extracted_data+ @import.import!+ @import.reload++ # Entries this import created are born reconciled too, so they must not be+ # counted as transactions the account already had.+ assert_equal 1, @import.already_recorded_count+ assert_equal 1, @import.imported_count+ # Rows survive publishing as the record of what was written, so the count+ # has to stop describing them as a queue.+ assert_equal 0, @import.awaiting_review_count+ end++ test "a fully reconciled statement reports everything as already recorded" do+ create_transaction(account: @account, date: @date, amount: 50, name: "Coffee")+ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -50, name: "Coffee") ] })+ @import.generate_rows_from_extracted_data+ @import.reload++ assert_equal 1, @import.extracted_count+ assert_equal 1, @import.already_recorded_count+ assert_equal 0, @import.imported_count+ assert_equal 0, @import.awaiting_review_count+ end++ test "an import that matched nothing reports nothing as already recorded" do+ @import.update!(extracted_data: { "transactions" => [ extracted(date: @date, amount: -12, name: "Bookstore") ] })+ @import.generate_rows_from_extracted_data+ @import.reload++ assert_equal 0, @import.already_recorded_count+ assert_not @import.reconciled_anything?+ end++ private++ def create_statement+ AccountStatement.create_from_upload!(+ family: @family,+ account: @account,+ file: uploaded_file(+ filename: "statement.pdf",+ content_type: "application/pdf",+ content: file_fixture("imports/sample_bank_statement.pdf").binread+ )+ )+ end+end