The personal finance app for everyone (by everyone)
Ruby
Share one pending predicate, and classify investment cash movements in one place (#3557)
jaysbeekay33bc802958ee
diff --git a/app/controllers/pending_duplicate_merges_controller.rb b/app/controllers/pending_duplicate_merges_controller.rbindex ec2914097e..67a909980a 100644--- a/app/controllers/pending_duplicate_merges_controller.rb+++ b/app/controllers/pending_duplicate_merges_controller.rb@@ -71,14 +71,12 @@ class PendingDuplicateMergesController < ApplicationControllerdef find_eligible_posted_entry(entry_id)# Constrain to same account, currency, and ensure it's a posted transaction# Use the same logic as pending_duplicate_candidates to ensure consistency- conditions = Transaction::PENDING_PROVIDERS.map { |provider| "(transactions.extra -> '#{provider}' ->> 'pending')::boolean IS NOT TRUE" }-@transaction.entry.account.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(id: entry_id).where(currency: @transaction.entry.currency).where.not(id: @transaction.entry.id)- .where(conditions.join(" AND "))+ .where(Transaction.not_pending_sql).firstenddiff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rbindex 50e1c29ccb..581a19e290 100644--- a/app/models/account/provider_import_adapter.rb+++ b/app/models/account/provider_import_adapter.rb@@ -1,14 +1,4 @@class Account::ProviderImportAdapter- # Matches a transaction any provider has flagged pending, for the lookups below that- # join `transactions` directly. Derived from Transaction::PENDING_PROVIDERS rather- # than spelled out, so a newly supported provider cannot silently drop out of- # pending→posted reconciliation. Frozen constant built from a frozen provider list:- # no user input reaches the SQL (same reasoning as Transaction::PENDING_CHECK_SQL).- PENDING_LOOKUP_SQL = Transaction::PENDING_PROVIDERS- .map { |provider| "(transactions.extra -> '#{provider}' ->> 'pending')::boolean = true" }- .join(" OR ")- .freeze-attr_reader :account, :skipped_entries# @param account [Account] the account every import through this adapter lands on@@ -64,14 +54,7 @@ class Account::ProviderImportAdapter# Determine early whether the incoming transaction is pending — needed by both# the protection check (pending→booked bypass) and the auto-claim path below.- incoming_pending = false- if extra.is_a?(Hash)- pending_extra = extra.with_indifferent_access- boolean_type = ActiveModel::Type::Boolean.new- incoming_pending = Transaction::PENDING_PROVIDERS.any? do |provider|- boolean_type.cast(pending_extra.dig(provider, "pending"))- end- end+ incoming_pending = extra.is_a?(Hash) && Transaction.pending_extra?(extra.with_indifferent_access)# === PROTECTION CHECK: Skip entries that should not be overwritten ===# Check persisted Transaction entries for protection flags before making changes.@@ -92,8 +75,7 @@ class Account::ProviderImportAdapter# here (determine_skip_reason reports user_modified first) but is excluded# from that refresh, so this is the only thing that clears its pending flag.if skip_reason == "user_modified" && !incoming_pending && entry.entryable.is_a?(Transaction)- entry_is_pending = Transaction::PENDING_PROVIDERS.any? { |p| entry.transaction.extra&.dig(p, "pending") }- if entry_is_pending+ if entry.transaction.pending?entry.transaction.update!(extra: clear_pending_flags_from_extra(entry.transaction.extra))endend@@ -193,7 +175,7 @@ class Account::ProviderImportAdapter# must clear the stale pending flag here before the final save.# (The auto-claim path already clears it in-memory, so this is a no-op there.)if !incoming_pending && entry.entryable.is_a?(Transaction)- if Transaction::PENDING_PROVIDERS.any? { |p| entry.transaction.extra&.dig(p, "pending") }+ if entry.transaction.pending?entry.transaction.extra = clear_pending_flags_from_extra(entry.transaction.extra)endend@@ -847,7 +829,7 @@ class Account::ProviderImportAdapter.where(amount: amount).where(currency: currency).where(date: (date - date_window.days)..date) # Pending must be ON or BEFORE posted date- .where(PENDING_LOOKUP_SQL)+ .where(Transaction.pending_sql("transactions")).order(date: :desc) # Prefer most recent pending transactioncandidates.first@@ -889,7 +871,7 @@ class Account::ProviderImportAdapter.where(currency: currency).where(date: (date - date_window.days)..date) # Pending ON or BEFORE posted.where("ABS(entries.amount) BETWEEN ? AND ?", min_pending_abs, max_pending_abs)- .where(PENDING_LOOKUP_SQL)+ .where(Transaction.pending_sql("transactions"))# If merchant_id is provided, prioritize matching by merchantif merchant_id.present?@@ -954,7 +936,7 @@ class Account::ProviderImportAdapter.where(currency: currency).where(date: (date - date_window.days)..date).where("ABS(entries.amount) BETWEEN ? AND ?", min_pending_abs, max_pending_abs)- .where(PENDING_LOOKUP_SQL)+ .where(Transaction.pending_sql("transactions"))# For low confidence, require BOTH merchant AND name match (stronger signal needed)if merchant_id.present? && name.present?diff --git a/app/models/akahu_account/transactions/processor.rb b/app/models/akahu_account/transactions/processor.rbindex 48855193d3..ebabebc3da 100644--- a/app/models/akahu_account/transactions/processor.rb+++ b/app/models/akahu_account/transactions/processor.rb@@ -78,7 +78,7 @@ class AkahuAccount::Transactions::Processorstale_pending_entries = account.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(source: "akahu")- .where("(transactions.extra -> 'akahu' ->> 'pending')::boolean = true")+ .where(Transaction.pending_sql("transactions", providers: [ "akahu" ]))stale_pending_entries = stale_pending_entries.where.not(external_id: current_pending_external_ids) if current_pending_external_ids.any?count = stale_pending_entries.countdiff --git a/app/models/entry.rb b/app/models/entry.rbindex 2d4801f060..77303521a3 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -67,9 +67,8 @@ class Entry < ApplicationRecord# 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, -> {- conditions = Transaction::PENDING_PROVIDERS.map { |p| "(transactions.extra -> '#{p}' ->> 'pending')::boolean = true" }joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")- .where(conditions.join(" OR "))+ .where(Transaction.pending_sql)}scope :excluding_pending, -> {@@ -166,9 +165,7 @@ class Entry < ApplicationRecorddef self.reconcile_pending_duplicates(account: nil, dry_run: false, date_window: 8, amount_tolerance: 0.25)stats = { checked: 0, reconciled: 0, details: [] }- not_pending_sql = Transaction::PENDING_PROVIDERS- .map { |p| "(transactions.extra -> '#{p}' ->> 'pending')::boolean IS NOT TRUE" }- .join(" AND ")+ not_pending_sql = Transaction.not_pending_sql# Get pending entries to checkscope = Entry.pending.where(excluded: false)diff --git a/app/models/entry_search.rb b/app/models/entry_search.rbindex 6671cbcd86..d32867ca37 100644--- a/app/models/entry_search.rb+++ b/app/models/entry_search.rb@@ -73,8 +73,7 @@ class EntrySearchreturn scope if statuses.uniq.sort == %w[confirmed pending] # Both selected = no filter# Source the pending check from Transaction::PENDING_CHECK_SQL (aliased to- # "t") so every provider in PENDING_PROVIDERS is covered. Previously this- # hardcoded only simplefin/plaid/lunchflow, dropping enable_banking.+ # "t") so every supported provider is covered.pending_condition = <<~SQL.squishentries.entryable_type = 'Transaction'AND EXISTS (diff --git a/app/models/goal/withdrawal_detector.rb b/app/models/goal/withdrawal_detector.rbindex 2e5d35b01a..7b5a019221 100644--- a/app/models/goal/withdrawal_detector.rb+++ b/app/models/goal/withdrawal_detector.rb@@ -70,10 +70,7 @@ class Goal::WithdrawalDetector# no longer exists, while the posted twin arrives unstamped and gets# offered all over again.#- # `pending_providers_sql` is built to be appended to an existing WHERE,- # so it leads with AND; the rest of its clauses chain correctly once- # that first one is dropped.- .where(Transaction.pending_providers_sql("transactions").sub(/\AAND /, ""))+ .where(Transaction.not_pending_sql("transactions")).order(date: :desc, id: :desc)endenddiff --git a/app/models/monobank_account/transactions/processor.rb b/app/models/monobank_account/transactions/processor.rbindex b3b6512f9c..241d35a5b7 100644--- a/app/models/monobank_account/transactions/processor.rb+++ b/app/models/monobank_account/transactions/processor.rb@@ -121,7 +121,7 @@ class MonobankAccount::Transactions::Processorstale_pending_entries = account.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(source: "monobank")- .where("(transactions.extra -> 'monobank' ->> 'pending')::boolean = true")+ .where(Transaction.pending_sql("transactions", providers: [ "monobank" ]))stale_pending_entries = stale_pending_entries.where.not(external_id: current_pending_external_ids) if current_pending_external_ids.any?pruned = 0diff --git a/app/models/portfolio/flow_classifier.rb b/app/models/portfolio/flow_classifier.rbnew file mode 100644index 0000000000..819f0795c9--- /dev/null+++ b/app/models/portfolio/flow_classifier.rb@@ -0,0 +1,324 @@+# The one place that says what a cash movement in an investment account *is*.+#+# Every entry in an investment or crypto account is one of five things:+#+# :external_inflow money or assets arriving from outside the scope+# :external_outflow money or assets leaving the scope+# :income a dividend or interest payment+# :fee a fee or commission+# :internal cash turning into a security or back, or moving between+# places inside the scope (buy, sell, sweep, exchange, a+# transfer whose other leg is also in scope)+#+# Returns, allocation, income and contribution-room figures all need this+# split, and they need the same answer. Deriving it in each reader is how the+# same dividend ends up counted as income in one place and as a deposit in+# another. So one rule table lives here and both forms of the classifier --+# the Ruby #classify for tests and small sets, the SQL #sql_case for the daily+# queries a series needs -- are generated from it, with a parity test proving+# they agree.+#+# Scope is a required argument, not a default. A transfer between two+# brokerage accounts is internal to the family portfolio and external to+# either account on its own; a classifier that did not know which question+# was being asked would give the wrong family return the first time a user+# moved a position between brokers.+#+# Inputs, in the order they are consulted: whether the entry is excluded or+# pending; a transfer-fee leg; the activity label on the Trade or Transaction;+# for an unlabelled Transaction its `kind`; and for a transfer, whether the+# counterpart leg's account is inside the scope. Direction for an external+# flow comes from the Trade's quantity sign or the Transaction's amount sign+# (negative amount = money in).+#+# What a caller must do with the answer:+#+# - Sum signed amounts per class. :income and :fee are decided by the label+# alone, not by the sign of the amount, so a margin-interest charge labelled+# "Interest" is :income with a positive amount, and a fee rebate labelled+# "Fee" is :fee with a negative one. A signed sum nets them correctly; a sum+# of absolute values would count the charge as more income.+# - Scope to one family itself. Neither form filters by family: #classify_ids+# reads whichever entry ids it is given, and scope_account_ids is taken as+# given. Pass only ids and accounts the caller has already scoped.+class Portfolio::FlowClassifier+ CLASSES = %i[external_inflow external_outflow income fee internal].freeze++ # Activity label -> class. Two pseudo-classes resolve at classification+ # time, and both consult the link before the label: :external and :transfer+ # each become :internal when the entry is a linked Transfer whose other leg+ # is inside the scope, and an inflow or an outflow by direction otherwise.+ # A label describes what the borrower meant; a Transfer row records where+ # the money went, and between two accounts in scope it went nowhere. A nil rule means the label decides nothing and+ # the fallthrough applies (a Trade is internal; a Transaction goes by kind).+ #+ # "Exchange" is internal on both a Trade and a Transaction here, following+ # Transaction::INTERNAL_MOVEMENT_LABELS. Trade::INTERNAL_MOVEMENT_LABELS+ # excludes it because a security-for-security exchange can realise a gain;+ # that is a cost-basis question, not a cash-flow one, and this table only+ # answers the latter.+ #+ # "Reinvestment" is internal: the cash that bought the shares was a+ # dividend, but income is only counted when a separate Dividend entry+ # records it, as InvestmentStatement::Totals already assumes.+ LABEL_RULES = {+ "Dividend" => :income,+ "Interest" => :income,+ "Fee" => :fee,+ "Buy" => :internal,+ "Sell" => :internal,+ "Reinvestment" => :internal,+ "Sweep In" => :internal,+ "Sweep Out" => :internal,+ "Exchange" => :internal,+ "Contribution" => :external,+ "Withdrawal" => :external,+ "Transfer" => :transfer,+ "Other" => nil+ }.freeze++ # Every label the table knows, so a new Transaction::ACTIVITY_LABELS entry+ # without a rule fails the test that compares the two.+ def self.labels_for(klass)+ LABEL_RULES.select { |_, rule| rule == klass }.keys.freeze+ end++ # True for a `transactions` row the classifier calls pending, as SQL: the+ # rule Transaction#pending? applies, in Transaction.pending_sql's words, so+ # this class, InvestmentStatement::Totals and every other SQL reader of the+ # flag share one definition (P25). Kept as a method here so the CASE below+ # and Totals name the same thing.+ def self.pending_sql+ Transaction.pending_sql("transactions")+ end++ INCOME_LABELS = labels_for(:income)+ FEE_LABELS = labels_for(:fee)+ INTERNAL_LABELS = labels_for(:internal)+ EXTERNAL_LABELS = labels_for(:external)+ TRANSFER_LABEL = "Transfer".freeze++ attr_reader :scope_account_ids++ def initialize(scope_account_ids:)+ @scope_account_ids = Array(scope_account_ids).map(&:to_s).uniq.freeze+ end++ # One of CLASSES, or nil when the entry carries no flow: excluded entries,+ # pending transactions, valuations.+ def classify(entry)+ return nil if entry.excluded?++ case entry.entryable+ when Trade then classify_trade(entry, entry.entryable)+ when Transaction then classify_transaction(entry, entry.entryable)+ end+ end++ # The same decision as #classify for every id given, taken in SQL. Returns+ # { entry_id => class or nil }. Later drops embed #sql_case in their own+ # daily queries; this method is the reference the parity test holds them to.+ # The ids are not filtered by family; the caller passes ids it has scoped.+ def classify_ids(entry_ids)+ ids = Array(entry_ids).map(&:to_s)+ return {} if ids.empty?++ # The ids are bound by ActiveRecord rather than written into the string.+ # Building the whole statement and passing it back through+ # sanitize_sql_array would make Rails read any `:word` inside a label or+ # a literal as a bind variable it cannot find, and raise before the query+ # ever ran; #sql_case is already sanitized, and Arel.sql says so.+ Entry+ .where(id: ids)+ .joins(sql_joins)+ .pluck(Arel.sql("entries.id"), Arel.sql(sql_case))+ .to_h { |id, flow_class| [ id, flow_class&.to_sym ] }+ end++ # The joins #sql_case relies on. The caller's query must select FROM+ # `entries` and place this fragment before its WHERE clause.+ #+ # One row per entry, which an aggregate embedding this relies on: the+ # transfers join cannot fan out because Transfer validates+ # inflow_transaction_id and outflow_transaction_id as unique and requires+ # opposite amounts, so a transaction is a leg of at most one transfer. A+ # writer that bypasses validations (insert_all) could break that, and a SUM+ # over this join would then count the entry twice.+ def sql_joins+ <<~SQL.squish+ LEFT JOIN trades ON entries.entryable_type = 'Trade' AND trades.id = entries.entryable_id+ LEFT JOIN transactions ON entries.entryable_type = 'Transaction' AND transactions.id = entries.entryable_id+ LEFT JOIN transfers flow_transfers+ ON entries.entryable_type = 'Transaction'+ AND (flow_transfers.inflow_transaction_id = transactions.id OR flow_transfers.outflow_transaction_id = transactions.id)+ LEFT JOIN entries flow_counterpart_entries+ ON flow_counterpart_entries.entryable_type = 'Transaction'+ AND flow_counterpart_entries.entryable_id = CASE+ WHEN flow_transfers.inflow_transaction_id = transactions.id THEN flow_transfers.outflow_transaction_id+ ELSE flow_transfers.inflow_transaction_id+ END+ SQL+ end++ # A CASE expression yielding the class name as text, or NULL, for the row+ # `entries` / `trades` / `transactions` joined by #sql_joins. Every literal+ # in it comes from the constants above; the scope ids are the only bound+ # value.+ def sql_case+ <<~SQL.squish+ CASE+ WHEN entries.excluded THEN NULL+ WHEN entries.entryable_type NOT IN ('Trade', 'Transaction') THEN NULL+ WHEN entries.entryable_type = 'Transaction' AND (#{pending_sql}) THEN NULL+ WHEN transactions.transfer_id IS NOT NULL AND transactions.kind = 'standard' THEN 'fee'+ WHEN #{label_sql} IN (#{quote_list(INCOME_LABELS)}) THEN 'income'+ WHEN #{label_sql} IN (#{quote_list(FEE_LABELS)}) THEN 'fee'+ WHEN #{label_sql} IN (#{quote_list(INTERNAL_LABELS)}) THEN 'internal'+ WHEN #{label_sql} IN (#{quote_list(EXTERNAL_LABELS)}) THEN #{transfer_resolution_sql}+ WHEN #{label_sql} = '#{TRANSFER_LABEL}' AND entries.entryable_type = 'Trade'+ THEN CASE WHEN #{security_transfer_counterpart_in_scope_sql} THEN 'internal' ELSE #{direction_sql} END+ WHEN #{label_sql} = '#{TRANSFER_LABEL}' THEN #{transfer_resolution_sql}+ WHEN entries.entryable_type = 'Trade' THEN 'internal'+ WHEN transactions.kind IN (#{quote_list(Transaction::TRANSFER_KINDS)}) THEN #{transfer_resolution_sql}+ ELSE #{direction_sql}+ END+ SQL+ end++ private+ def classify_trade(entry, trade)+ rule = LABEL_RULES[trade.investment_activity_label]++ case rule+ when nil then :internal+ when :external then trade_direction(trade)+ when :transfer then security_transfer_counterpart_in_scope?(entry, trade) ? :internal : trade_direction(trade)+ else rule+ end+ end++ def classify_transaction(entry, transaction)+ return nil if transaction.pending?+ # The fee legs of a Transfer are plain standard transactions that point+ # back at their transfer; nothing else sets transfer_id.+ return :fee if transaction.transfer_id.present? && transaction.kind == "standard"++ rule = LABEL_RULES[transaction.investment_activity_label]++ case rule+ when nil+ transaction.transfer? ? transfer_resolution(entry, transaction) : transaction_direction(entry)+ # A Contribution or Withdrawal label says where the borrower thinks the+ # money went; a linked Transfer says where it actually went. When both+ # legs are inside the scope the movement is internal whatever either leg+ # is labelled, so the label cannot outrank the link. #transfer_resolution+ # falls back to the same direction this used to return whenever there is+ # no link, or the counterpart sits outside the scope.+ when :external then transfer_resolution(entry, transaction)+ when :transfer then transfer_resolution(entry, transaction)+ else rule+ end+ end++ def trade_direction(trade)+ trade.qty.negative? ? :external_outflow : :external_inflow+ end++ def transaction_direction(entry)+ entry.amount.negative? ? :external_inflow : :external_outflow+ end++ def transfer_resolution(entry, transaction)+ counterpart_account_id = transfer_counterpart_account_id(transaction)+ if counterpart_account_id && scope_account_ids.include?(counterpart_account_id)+ :internal+ else+ transaction_direction(entry)+ end+ end++ # The account on the other leg of a linked Transfer, by id only; the+ # counterpart account itself is never loaded, so a scope check cannot+ # leak an account the user is not allowed to see.+ def transfer_counterpart_account_id(transaction)+ transfer = transaction.transfer_as_inflow || transaction.transfer_as_outflow+ return nil unless transfer++ counterpart_id = transfer.inflow_transaction_id == transaction.id ? transfer.outflow_transaction_id : transfer.inflow_transaction_id+ Entry.where(entryable_type: "Transaction", entryable_id: counterpart_id).pick(:account_id)&.to_s+ end++ # A security moved between accounts has no Transfer row; its other leg is+ # the opposite-quantity Transfer trade on the same security and date in+ # another account. entries.excluded is nullable, and a NULL leg is live+ # here as it is to #classify, hence IS NOT TRUE rather than = false.+ def security_transfer_counterpart_in_scope?(entry, trade)+ Entry+ .joins("JOIN trades counterpart_trades ON counterpart_trades.id = entries.entryable_id AND entries.entryable_type = 'Trade'")+ .where(account_id: scope_account_ids)+ .where.not(account_id: entry.account_id)+ .where(date: entry.date)+ .where("entries.excluded IS NOT TRUE")+ .where(counterpart_trades: { security_id: trade.security_id, qty: -trade.qty, investment_activity_label: TRANSFER_LABEL })+ .exists?+ end++ def label_sql+ "COALESCE(trades.investment_activity_label, transactions.investment_activity_label)"+ end++ def direction_sql+ <<~SQL.squish+ CASE+ WHEN entries.entryable_type = 'Trade' THEN CASE WHEN trades.qty < 0 THEN 'external_outflow' ELSE 'external_inflow' END+ WHEN entries.amount < 0 THEN 'external_inflow'+ ELSE 'external_outflow'+ END+ SQL+ end++ def transfer_resolution_sql+ "CASE WHEN flow_counterpart_entries.account_id = ANY(#{scope_ids_sql}) THEN 'internal' ELSE #{direction_sql} END"+ end++ def security_transfer_counterpart_in_scope_sql+ <<~SQL.squish+ EXISTS (+ SELECT 1+ FROM entries counterpart_entries+ JOIN trades counterpart_trades+ ON counterpart_trades.id = counterpart_entries.entryable_id+ AND counterpart_entries.entryable_type = 'Trade'+ WHERE counterpart_entries.account_id = ANY(#{scope_ids_sql})+ AND counterpart_entries.account_id <> entries.account_id+ AND counterpart_entries.date = entries.date+ AND counterpart_entries.excluded IS NOT TRUE+ AND counterpart_trades.security_id = trades.security_id+ AND counterpart_trades.qty = -trades.qty+ AND counterpart_trades.investment_activity_label = '#{TRANSFER_LABEL}'+ )+ SQL+ end++ def pending_sql+ self.class.pending_sql+ end++ # The one bound value in the whole expression, sanitized on its own and+ # then written into the CASE as a literal.+ #+ # The alternative -- handing the finished CASE to sanitize_sql_array with+ # a named bind -- makes Rails scan a string that already contains every+ # label literal for `:name` placeholders, so the day a label carries a+ # colon ("Fee:Broker") it raises PreparedStatementInvalid before the+ # query runs, taking out whatever the CASE was embedded in.+ def scope_ids_sql+ @scope_ids_sql ||= ActiveRecord::Base.sanitize_sql_array(+ [ "ARRAY[:scope_account_ids]::uuid[]", { scope_account_ids: scope_account_ids } ]+ )+ end++ def quote_list(values)+ values.map { |value| ActiveRecord::Base.connection.quote(value) }.join(", ")+ end+enddiff --git a/app/models/simplefin_item/importer.rb b/app/models/simplefin_item/importer.rbindex ef4489bd08..b60bcbaf8d 100644--- a/app/models/simplefin_item/importer.rb+++ b/app/models/simplefin_item/importer.rb@@ -942,8 +942,7 @@ class SimplefinItem::Importerunless @reconciled_account_ids.include?(acct.id)@reconciled_account_ids << acct.idreconcile_and_track_pending_duplicates(acct)- exclude_and_track_stale_pending(acct)- track_stale_unmatched_pending(acct)+ review_and_exclude_stale_pending(acct)end# Refresh credit attributes when available-balance present@@ -1308,6 +1307,19 @@ class SimplefinItem::Importerrecord_reconciliation_error("pending_reconciliation", account, e)end+ # Stale pending entries are reported for review first, then excluded.+ #+ # The order matters and is the reason these two steps have one caller:+ # both steps decide "pending" with Transaction.pending_sql, and the+ # tracker counts only entries that are still `excluded: false`. Exclude+ # first and the tracker can never see anything -- the exclusion has just+ # marked every row it would have counted. Sync stats reported 0 under+ # "needs manual review" for that reason, whatever the account held.+ def review_and_exclude_stale_pending(account)+ track_stale_unmatched_pending(account)+ exclude_and_track_stale_pending(account)+ end+# Auto-exclude stale pending transactions (>8 days old with no matching posted version)# Prevents orphaned pending transactions from affecting budgets indefinitelydef exclude_and_track_stale_pending(account)@@ -1328,16 +1340,16 @@ class SimplefinItem::Importerend# Track stale pending transactions that couldn't be matched (for user awareness)- # These are >8 days old, still pending, and have no duplicate suggestion+ # These are >8 days old, still pending, and have no duplicate suggestion.+ # Pending under any provider, as exclude_and_track_stale_pending decides it,+ # which is why it must run before that exclusion (see+ # review_and_exclude_stale_pending).def track_stale_unmatched_pending(account)stale_unmatched = account.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(excluded: false).where("entries.date < ?", 8.days.ago.to_date)- .where(<<~SQL.squish)- (transactions.extra -> 'simplefin' ->> 'pending')::boolean = true- OR (transactions.extra -> 'plaid' ->> 'pending')::boolean = true- SQL+ .where(Transaction.pending_sql).where(<<~SQL.squish)transactions.extra -> 'potential_posted_match' IS NULLSQLdiff --git a/app/models/transaction.rb b/app/models/transaction.rbindex 2cc13f7c65..2284fef6e1 100644--- a/app/models/transaction.rb+++ b/app/models/transaction.rb@@ -117,31 +117,101 @@ class Transaction < ApplicationRecord# DataEnrichment sources that represent automatic category assignmentAUTO_CATEGORY_SOURCES = %w[ai bayes].freeze- # Pre-computed SQL fragment for subqueries that check if a transaction (aliased as "t") is pending.- # Stored as a constant so static analysis can verify it contains no user input.- PENDING_CHECK_SQL = PENDING_PROVIDERS- .map { |p| "(t.extra -> '#{p}' ->> 'pending')::boolean = true" }- .join(" OR ")- .freeze+ # Stored flag values that do not mark a transaction pending: the strings+ # ActiveModel::Type::Boolean casts to false, plus "" (which it casts to nil).+ # Any other present value is pending, as #pending? decides.+ PENDING_FLAG_FALSE_VALUES = (ActiveModel::Type::Boolean::FALSE_VALUES.grep(String) + [ "" ]).uniq.freeze+ PENDING_FLAG_TYPE = ActiveModel::Type::Boolean.new.freeze++ # PENDING_FLAG_FALSE_VALUES as a list of SQL string literals. Built from the+ # constant alone, so class loading needs no database connection, and shared by+ # pending_sql and PENDING_CHECK_SQL so the two cannot quote the values+ # differently.+ PENDING_FLAG_FALSE_VALUES_SQL = PENDING_FLAG_FALSE_VALUES.map { |value| "'#{value.gsub("'", "''")}'" }.join(", ").freeze++ # Canonical reusable SQL form of the pending? decision. Callers that inspect+ # only provider namespaces they own can pass that subset in `providers:`.+ #+ # Deliberately not `(... ->> 'pending')::boolean`. PostgreSQL raises+ # PG::InvalidTextRepresentation on a value it cannot parse ("maybe"), which+ # aborts the whole query rather than one row, and it reads "no", "False" and+ # "Off" as false where ActiveModel reads them as true. Providers write JSON+ # booleans, which ->> renders as 'true', 'false' or NULL and both rules+ # classify alike, so only other values are affected.+ #+ # COALESCE maps a missing flag or JSON null to "", a false value, so no+ # provider's term is ever NULL and NOT (...) is exact.+ #+ # A JSON number 0.0 renders as '0.0' and is pending here; #pending? agrees,+ # because FALSE_VALUES is a Set keyed by eql? and 0.0 is not eql? to 0. The+ # parity test carries the case.+ def self.pending_sql(table_alias = "transactions", providers: PENDING_PROVIDERS)+ quoted_table = connection.quote_table_name(table_alias)+ selected_providers = Array(providers).map(&:to_s).uniq & PENDING_PROVIDERS+ return "FALSE" if selected_providers.empty?++ selected_providers+ .map do |provider|+ "COALESCE(#{quoted_table}.extra -> #{connection.quote(provider)} ->> #{connection.quote("pending")}, #{connection.quote("")}) NOT IN (#{PENDING_FLAG_FALSE_VALUES_SQL})"+ end+ .join(" OR ")+ .then { |predicate| "(#{predicate})" }+ end++ # Fixed-alias fragment for correlated SQL. Build from model constants without+ # borrowing a database connection during class loading.+ PENDING_CHECK_SQL = begin+ PENDING_PROVIDERS+ .map do |provider|+ "COALESCE(t.extra -> '#{provider}' ->> 'pending', '') NOT IN (#{PENDING_FLAG_FALSE_VALUES_SQL})"+ end+ .join(" OR ")+ .then { |predicate| "(#{predicate})" }+ .freeze+ end++ # The negation of pending_sql, for queries that must leave pending rows out.+ def self.not_pending_sql(table_alias = "transactions", providers: PENDING_PROVIDERS)+ "NOT (#{pending_sql(table_alias, providers: providers)})"+ end++ # The Ruby form of the same decision, over a provider metadata hash rather+ # than a record. #pending? is this method; the import adapter also needs it+ # before any record exists, for the payload it is about to write.+ #+ # Reads keys as strings, so pass string-keyed metadata or a+ # HashWithIndifferentAccess. A provider key holding anything but an object+ # says nothing about that provider and is skipped, as pending_sql skips it:+ # Hash#dig would instead raise on a scalar and take the whole caller with it.+ def self.pending_extra?(extra)+ return false unless extra.is_a?(Hash)++ PENDING_PROVIDERS.any? do |provider|+ provider_data = extra[provider]+ provider_data.is_a?(Hash) && PENDING_FLAG_TYPE.cast(provider_data["pending"])+ end+ rescue StandardError+ false+ end# Pending transaction scopes - filter based on provider pending flags in extra JSONB# Works with any provider that stores pending status in extra["provider_name"]["pending"]- scope :pending, -> {- conditions = PENDING_PROVIDERS.map { |provider| "(transactions.extra -> '#{provider}' ->> 'pending')::boolean = true" }- where(conditions.join(" OR "))- }+ scope :pending, -> { where(Transaction.pending_sql) }- scope :excluding_pending, -> {- conditions = PENDING_PROVIDERS.map { |provider| "(transactions.extra -> '#{provider}' ->> 'pending')::boolean IS DISTINCT FROM true" }- where(conditions.join(" AND "))- }+ scope :excluding_pending, -> { where(Transaction.not_pending_sql) }# SQL snippet for raw queries that must exclude pending transactions.# Use in income statements, balance sheets, and raw analytics.- def self.pending_providers_sql(table_alias = "t")- PENDING_PROVIDERS.map do |provider|- "AND (#{table_alias}.extra -> '#{provider}' ->> 'pending')::boolean IS DISTINCT FROM true"- end.join("\n")+ #+ # Emits a LEADING `AND`, so it appends to a WHERE that already has at least+ # one condition -- which is how all three callers use it+ # (IncomeStatement::FamilyStats, ::CategoryStats, ::ScopedTransactionsQuery),+ # interpolating it after their own `AND` clauses. As the first condition in a+ # WHERE it produces `WHERE AND NOT (...)`, a syntax error. Use+ # `not_pending_sql` for that position; this method is only the `AND`-prefixed+ # form of it.+ def self.pending_providers_sql(table_alias = "t", providers: PENDING_PROVIDERS)+ "AND #{not_pending_sql(table_alias, providers: providers)}"end# Family-scoped query for Enrichable#clear_ai_cache@@ -229,12 +299,7 @@ class Transaction < ApplicationRecordenddef pending?- extra_data = extra.is_a?(Hash) ? extra : {}- PENDING_PROVIDERS.any? do |provider|- ActiveModel::Type::Boolean.new.cast(extra_data.dig(provider, "pending"))- end- rescue StandardError- false+ self.class.pending_extra?(extra)enddef activity_security_id@@ -435,13 +500,11 @@ class Transaction < ApplicationRecordcurrency = entry.currency# Find recent posted transactions from the same account- conditions = PENDING_PROVIDERS.map { |provider| "(transactions.extra -> '#{provider}' ->> 'pending')::boolean IS NOT TRUE" }-account.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where.not(id: entry.id).where(currency: currency)- .where(conditions.join(" AND "))+ .where(Transaction.not_pending_sql).order(date: :desc, created_at: :desc).limit(limit).offset(offset)diff --git a/app/models/up_account/transactions/processor.rb b/app/models/up_account/transactions/processor.rbindex 0efe87ceb1..5d664e64d5 100644--- a/app/models/up_account/transactions/processor.rb+++ b/app/models/up_account/transactions/processor.rb@@ -98,7 +98,7 @@ class UpAccount::Transactions::Processorstale_pending_entries = account.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(source: "up")- .where("(transactions.extra -> 'up' ->> 'pending')::boolean = true")+ .where(Transaction.pending_sql("transactions", providers: [ "up" ]))stale_pending_entries = stale_pending_entries.where.not(external_id: current_pending_external_ids) if current_pending_external_ids.any?count = stale_pending_entries.countdiff --git a/lib/tasks/simplefin_pending_cleanup.rake b/lib/tasks/simplefin_pending_cleanup.rakeindex 147adda8b7..841a671764 100644--- a/lib/tasks/simplefin_pending_cleanup.rake+++ b/lib/tasks/simplefin_pending_cleanup.rake@@ -16,7 +16,7 @@ namespace :simplefin dopending_entries = Entry.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(source: "simplefin")- .where("transactions.extra -> 'simplefin' ->> 'pending' = ?", "true")+ .where(Transaction.pending_sql("transactions", providers: %w[simplefin])).includes(:account)puts "Found #{pending_entries.count} pending SimpleFIN transactions"@@ -35,7 +35,7 @@ namespace :simplefin do.where(currency: pending_entry.currency).where(date: pending_entry.date..(pending_entry.date + date_window.days)) # Posted must be ON or AFTER pending.where.not(id: pending_entry.id)- .where("transactions.extra -> 'simplefin' ->> 'pending' != ? OR transactions.extra -> 'simplefin' ->> 'pending' IS NULL", "true")+ .where(Transaction.not_pending_sql("transactions", providers: %w[simplefin])).firstif posted_match@@ -86,10 +86,7 @@ namespace :simplefin doexcluded_pending = Entry.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(excluded: true)- .where(<<~SQL.squish)- (transactions.extra -> 'simplefin' ->> 'pending')::boolean = true- OR (transactions.extra -> 'plaid' ->> 'pending')::boolean = true- SQL+ .where(Transaction.pending_sql("transactions", providers: %w[simplefin plaid]))puts "Found #{excluded_pending.count} excluded pending transactions to evaluate"puts ""@@ -105,10 +102,7 @@ namespace :simplefin do.where(currency: pending_entry.currency).where(amount: pending_entry.amount).where(date: pending_entry.date..(pending_entry.date + date_window.days))- .where(<<~SQL.squish)- (transactions.extra -> 'simplefin' ->> 'pending')::boolean IS NOT TRUE- AND (transactions.extra -> 'plaid' ->> 'pending')::boolean IS NOT TRUE- SQL+ .where(Transaction.not_pending_sql("transactions", providers: %w[simplefin plaid])).exists?unless valid_match@@ -142,7 +136,7 @@ namespace :simplefin dopending_entries = Entry.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(source: "simplefin")- .where("transactions.extra -> 'simplefin' ->> 'pending' = ?", "true")+ .where(Transaction.pending_sql("transactions", providers: %w[simplefin])).includes(:account).order(date: :desc)diff --git a/test/controllers/pending_duplicate_merges_controller_test.rb b/test/controllers/pending_duplicate_merges_controller_test.rbindex 91ed723a48..801f18bc66 100644--- a/test/controllers/pending_duplicate_merges_controller_test.rb+++ b/test/controllers/pending_duplicate_merges_controller_test.rb@@ -138,6 +138,25 @@ class PendingDuplicateMergesControllerTest < ActionDispatch::IntegrationTestassert_equal "Invalid transaction selected for merge", flash[:alert]end+ # Transaction#pending? calls "no" pending, and pending_duplicate_candidates+ # does not offer it; the controller must not accept it when posted directly.+ test "create rejects merge with a transaction whose pending flag is \"no\"" do+ pending_transaction = create_pending_transaction(amount: -50, account: @account)+ said_no = create_transaction(amount: -50, account: @account)+ said_no.entryable.update!(extra: { "simplefin" => { "pending" => "no" } })++ assert_no_difference "Entry.count" do+ post transaction_pending_duplicate_merges_path(pending_transaction), params: {+ pending_duplicate_merges: {+ posted_entry_id: said_no.id+ }+ }+ end++ assert_redirected_to transactions_path+ assert_equal "Invalid transaction selected for merge", flash[:alert]+ end+test "create rejects merge with transaction from different account" dopending_transaction = create_pending_transaction(amount: -50, account: @account)different_account_transaction = create_transaction(amount: -50, account: accounts(:investment))diff --git a/test/lib/tasks/simplefin_pending_cleanup_test.rb b/test/lib/tasks/simplefin_pending_cleanup_test.rbnew file mode 100644index 0000000000..30ef2f5b79--- /dev/null+++ b/test/lib/tasks/simplefin_pending_cleanup_test.rb@@ -0,0 +1,93 @@+# frozen_string_literal: true++require "test_helper"++RakeTaskTestHelper.load_task("simplefin:pending_restore", "simplefin_pending_cleanup")++class SimplefinPendingCleanupTest < ActiveSupport::TestCase+ setup do+ RakeTaskTestHelper.prepare("simplefin:pending_restore", "simplefin:pending_cleanup", "simplefin:pending_list")+ @family = families(:empty)+ @account = @family.accounts.create!(name: "Pending restore", balance: 0, currency: "USD", accountable: Depository.new)+ @previous_dry_run = ENV["DRY_RUN"]+ @previous_date_window = ENV["DATE_WINDOW"]+ ENV["DRY_RUN"] = "true"+ ENV["DATE_WINDOW"] = "8"+ end++ teardown do+ ENV["DRY_RUN"] = @previous_dry_run+ ENV["DATE_WINDOW"] = @previous_date_window+ end++ test "pending restore handles malformed pending values and leaves false or unrelated flags out" do+ malformed = create_excluded_entry("simplefin", "maybe", 10)+ false_flag = create_excluded_entry("simplefin", "off", 11)+ unrelated_provider = create_excluded_entry("lunchflow", true, 12)++ output, = capture_io { Rake::Task["simplefin:pending_restore"].invoke }++ assert_includes output, "ID=#{malformed.id}"+ assert_not_includes output, "ID=#{false_flag.id}"+ assert_not_includes output, "ID=#{unrelated_provider.id}"+ assert malformed.reload.excluded?, "dry run only reports rows; it must not mutate them"+ end++ test "pending list reads the pending flag the way Transaction#pending? does" do+ pending = create_entry("simplefin", true, 20)+ unknown = create_entry("simplefin", "maybe", 21)+ off = create_entry("simplefin", "off", 22)+ no = create_entry("simplefin", "no", 23) # not one of Rails' false values, so pending+ posted = create_entry("simplefin", false, 24)+ absent = create_entry("simplefin", nil, 25, flagless: true)++ output, = capture_io { Rake::Task["simplefin:pending_list"].invoke }++ assert_includes output, "ID=#{pending.id}"+ assert_includes output, "ID=#{unknown.id}"+ assert_includes output, "ID=#{no.id}"+ [ off, posted, absent ].each { |entry| assert_not_includes output, "ID=#{entry.id}" }+ end++ test "pending cleanup matches the posted side with Transaction#pending? semantics" do+ unknown = create_entry("simplefin", "maybe", 30)+ posted_off = create_entry("simplefin", "off", 30, date: 9.days.ago.to_date)+ false_flag = create_entry("simplefin", "off", 31)+ create_entry("simplefin", false, 31, date: 9.days.ago.to_date)+ still_pending = create_entry("simplefin", true, 32)+ posted_unknown = create_entry("simplefin", "maybe", 32, date: 9.days.ago.to_date)+ posted_no = create_entry("simplefin", "no", 32, date: 8.days.ago.to_date)+ genuine = create_entry("simplefin", true, 33)+ posted_absent = create_entry("simplefin", nil, 33, date: 9.days.ago.to_date, flagless: true)++ output, = capture_io { Rake::Task["simplefin:pending_cleanup"].invoke }++ assert_includes output, "Pending: ID=#{unknown.id}"+ assert_includes output, "Posted: ID=#{posted_off.id}"+ assert_includes output, "Pending: ID=#{genuine.id}"+ assert_includes output, "Posted: ID=#{posted_absent.id}"+ assert_not_includes output, "Pending: ID=#{false_flag.id}", "a Rails false value is not pending"+ assert_not_includes output, "Pending: ID=#{still_pending.id}", "an unknown flag is pending, so it is not a posted match"+ assert_not_includes output, "Posted: ID=#{posted_unknown.id}"+ assert_not_includes output, "Posted: ID=#{posted_no.id}"+ assert_includes output, "Summary: 2 duplicate pending transactions found"+ assert_equal 9, @account.entries.count, "dry run must not delete anything"+ end++ private+ def create_entry(provider, pending, amount, date: 10.days.ago.to_date, flagless: false)+ extra = flagless ? { provider => {} } : { provider => { "pending" => pending } }+ @account.entries.create!(+ name: "#{provider}-#{amount}-#{date}", date: date, amount: amount, currency: "USD",+ source: provider, entryable: Transaction.new(extra: extra)+ )+ end++ def create_excluded_entry(provider, pending, amount)+ @account.entries.create!(+ name: "#{provider}-#{amount}", date: 10.days.ago.to_date, amount: amount, currency: "USD",+ excluded: true,+ entryable: Transaction.new(extra: { provider => { "pending" => pending } })+ )+ end+enddiff --git a/test/lib/tasks/simplefin_pending_restore_test.rb b/test/lib/tasks/simplefin_pending_restore_test.rbnew file mode 100644index 0000000000..3473381d36--- /dev/null+++ b/test/lib/tasks/simplefin_pending_restore_test.rb@@ -0,0 +1,82 @@+# frozen_string_literal: true++require "test_helper"++RakeTaskTestHelper.load_task("simplefin:pending_restore", "simplefin_pending_cleanup")++# simplefin:pending_restore un-excludes SimpleFIN/Plaid pending entries that have+# no posted match. "Pending" -- for the excluded entry and for its would-be+# match -- is decided as Transaction#pending? decides it, for those two providers.+class SimplefinPendingRestoreTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ RakeTaskTestHelper.prepare("simplefin:pending_restore")++ @account = families(:empty).accounts.create!(name: "SF Checking", balance: 0, currency: "USD", accountable: Depository.new)+ end++ test "restores an excluded entry whose flag a boolean cast cannot parse" do+ entry = excluded_entry("simplefin" => { "pending" => "maybe" })++ restore++ assert_not entry.reload.excluded+ end++ test "restores an excluded entry flagged \"no\", which pending? calls pending" do+ entry = excluded_entry("plaid" => { "pending" => "no" })++ restore++ assert_not entry.reload.excluded+ end++ test "a companion flagged \"no\" is still pending, so it is not a posted match" do+ entry = excluded_entry("simplefin" => { "pending" => true })+ companion(entry, "plaid" => { "pending" => "no" })++ restore++ assert_not entry.reload.excluded+ end++ test "keeps an excluded entry that has a posted match" do+ entry = excluded_entry("simplefin" => { "pending" => true })+ companion(entry, {})++ restore++ assert entry.reload.excluded+ end++ test "leaves entries flagged pending by other providers alone" do+ entry = excluded_entry("lunchflow" => { "pending" => true })++ restore++ assert entry.reload.excluded+ end++ private++ def excluded_entry(extra)+ create_transaction(account: @account, amount: 25, date: 20.days.ago.to_date, excluded: true).tap do |entry|+ entry.entryable.update!(extra: extra)+ end+ end++ def companion(entry, extra)+ create_transaction(account: @account, amount: entry.amount, currency: entry.currency, date: entry.date + 2.days).tap do |companion_entry|+ companion_entry.entryable.update!(extra: extra)+ end+ end++ def restore+ previous = ENV["DRY_RUN"]+ ENV["DRY_RUN"] = "false"+ capture_io { Rake::Task["simplefin:pending_restore"].invoke }+ ensure+ ENV["DRY_RUN"] = previous+ end+enddiff --git a/test/models/account/entry_test.rb b/test/models/account/entry_test.rbindex 05826f8b01..01ee4163b4 100644--- a/test/models/account/entry_test.rb+++ b/test/models/account/entry_test.rb@@ -106,6 +106,29 @@ class EntryTest < ActiveSupport::TestCaseassert_not_includes pending_ids, confirmed.idend+ # reconcile_pending_duplicates excludes a pending entry once it finds exactly+ # one posted twin. "Posted" has to mean what Transaction#pending? means: a twin+ # flagged "no" is itself pending, so there is nothing to reconcile against.+ test "reconcile_pending_duplicates matches only twins pending? calls posted" do+ family = families(:empty)+ account = family.accounts.create! name: "Said no", balance: 0, currency: "USD", accountable: Depository.new+ control_account = family.accounts.create! name: "Control", balance: 0, currency: "USD", accountable: Depository.new++ pending_entry = create_transaction(account: account, amount: 42, name: "Coffee")+ pending_entry.entryable.update!(extra: { "simplefin" => { "pending" => true } })+ create_transaction(account: account, amount: 42, name: "Coffee").entryable.update!(extra: { "simplefin" => { "pending" => "no" } })++ control_pending = create_transaction(account: control_account, amount: 42, name: "Coffee")+ control_pending.entryable.update!(extra: { "simplefin" => { "pending" => true } })+ create_transaction(account: control_account, amount: 42, name: "Coffee").entryable.update!(extra: { "simplefin" => { "pending" => false } })++ assert_equal 0, Entry.reconcile_pending_duplicates(account: account)[:reconciled]+ assert_not pending_entry.reload.excluded?++ assert_equal 1, Entry.reconcile_pending_duplicates(account: control_account)[:reconciled]+ assert control_pending.reload.excluded?+ end+test "visible scope only returns entries from visible accounts" do# Create transactions for all account typesvisible_transaction = create_transaction(account: accounts(:depository), name: "Visible transaction")diff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rbindex acbda23b77..de422d819c 100644--- a/test/models/account/provider_import_adapter_test.rb+++ b/test/models/account/provider_import_adapter_test.rb@@ -1634,6 +1634,102 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCaseassert_nil resultend+ test "all pending reconciliation finders use transaction semantics for malformed flags" do+ exact = @adapter.import_transaction(+ external_id: "simplefin_unparseable_exact",+ amount: 49_231.17,+ currency: "USD",+ date: Date.today - 1.day,+ name: "Exact Pending",+ source: "simplefin",+ extra: { "simplefin" => { "pending" => "maybe" } }+ )+ fuzzy = @adapter.import_transaction(+ external_id: "simplefin_unparseable_fuzzy",+ amount: 77.00,+ currency: "USD",+ date: Date.today - 2.days,+ name: "Fuzzy Pending",+ source: "simplefin",+ extra: { "simplefin" => { "pending" => "maybe" } }+ )+ merchant = ProviderMerchant.create!(+ provider_merchant_id: "pending-low-confidence",+ name: "Low Confidence Merchant",+ source: "simplefin"+ )+ low_confidence = @adapter.import_transaction(+ external_id: "simplefin_unparseable_low_confidence",+ amount: 50.00,+ currency: "USD",+ date: Date.today - 3.days,+ name: "Low Confidence Pending",+ source: "simplefin",+ merchant: merchant,+ extra: { "simplefin" => { "pending" => "maybe" } }+ )++ [ exact, fuzzy, low_confidence ].each { |entry| assert entry.transaction.pending? }+ assert_equal exact.id, @adapter.find_pending_transaction(+ date: Date.today, amount: 49_231.17, currency: "USD", source: "simplefin"+ ).id+ assert_equal fuzzy.id, @adapter.find_pending_transaction_fuzzy(+ date: Date.today, amount: 100, currency: "USD", source: "simplefin", name: "Fuzzy Pending"+ ).id+ assert_equal low_confidence.id, @adapter.find_pending_transaction_low_confidence(+ date: Date.today, amount: 100, currency: "USD", source: "simplefin",+ merchant_id: merchant.id, name: "Low Confidence Pending"+ ).id+ end++ test "all pending reconciliation finders exclude explicit false flags" do+ exact = @adapter.import_transaction(+ external_id: "simplefin_false_exact",+ amount: 49_232.17,+ currency: "USD",+ date: Date.today - 1.day,+ name: "Exact Posted",+ source: "simplefin",+ extra: { "simplefin" => { "pending" => "false" } }+ )+ fuzzy = @adapter.import_transaction(+ external_id: "simplefin_false_fuzzy",+ amount: 77.00,+ currency: "USD",+ date: Date.today - 2.days,+ name: "Fuzzy Posted",+ source: "simplefin",+ extra: { "simplefin" => { "pending" => "false" } }+ )+ merchant = ProviderMerchant.create!(+ provider_merchant_id: "pending-false-low-confidence",+ name: "False Low Confidence Merchant",+ source: "simplefin"+ )+ low_confidence = @adapter.import_transaction(+ external_id: "simplefin_false_low_confidence",+ amount: 50.00,+ currency: "USD",+ date: Date.today - 3.days,+ name: "Low Confidence Posted",+ source: "simplefin",+ merchant: merchant,+ extra: { "simplefin" => { "pending" => "false" } }+ )++ [ exact, fuzzy, low_confidence ].each { |entry| assert_not entry.transaction.pending? }+ assert_nil @adapter.find_pending_transaction(+ date: Date.today, amount: 49_232.17, currency: "USD", source: "simplefin"+ )+ assert_nil @adapter.find_pending_transaction_fuzzy(+ date: Date.today, amount: 100, currency: "USD", source: "simplefin", name: "Fuzzy Posted"+ )+ assert_nil @adapter.find_pending_transaction_low_confidence(+ date: Date.today, amount: 100, currency: "USD", source: "simplefin",+ merchant_id: merchant.id, name: "Low Confidence Posted"+ )+ end+# ============================================================================# Critical Direction Fix Tests (CITGO Bug Prevention)# ============================================================================@@ -2015,6 +2111,119 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCase"the provider's own namespace should still refresh"end+ # A provider key holding anything but an object says nothing about that+ # provider, and Transaction.pending_extra? skips it the way pending_sql does.+ # Hash#dig raised TypeError on such a value instead, and these reads sit+ # inside Account.transaction with no rescue between them and the caller, so a+ # single malformed namespace aborted the whole import. simplefin is first in+ # PENDING_PROVIDERS, so the malformed key is always reached.+ test "a scalar provider value in an incoming payload does not abort the import" do+ entry = nil++ assert_difference "@account.entries.count", 1 do+ entry = @adapter.import_transaction(+ external_id: "scalar_incoming_flag",+ amount: 12.0,+ currency: "EUR",+ date: Date.today,+ name: "Scalar Provider",+ source: "enable_banking",+ extra: { "simplefin" => "oops", "akahu" => { "pending" => true } }+ )+ end++ assert entry.transaction.pending?,+ "the well-formed provider flag still decides when another namespace is malformed"+ end++ test "a scalar provider value in a stored flag does not abort clearing it" do+ pending_entry = @adapter.import_transaction(+ external_id: "eb_scalar_stored",+ amount: 30.0,+ currency: "EUR",+ date: Date.today - 2.days,+ name: "Scalar Stored",+ source: "enable_banking",+ extra: { "enable_banking" => { "pending" => true } }+ )+ pending_entry.transaction.update!(extra: { "simplefin" => "oops", "enable_banking" => { "pending" => true } })+ assert pending_entry.transaction.reload.pending?, "entry should start as pending"++ assert_no_difference "@account.entries.count" do+ booked_entry = @adapter.import_transaction(+ external_id: "eb_scalar_stored",+ amount: 30.0,+ currency: "EUR",+ date: Date.today,+ name: "Scalar Stored",+ source: "enable_banking",+ extra: nil+ )++ assert_not booked_entry.transaction.reload.pending?,+ "the stale flag is cleared past the malformed namespace"+ end+ end++ test "a scalar provider value in a stored flag does not abort the user-modified path" do+ pending_entry = @adapter.import_transaction(+ external_id: "eb_scalar_user_mod",+ amount: 50.0,+ currency: "EUR",+ date: Date.today - 3.days,+ name: "Scalar User Modified",+ source: "enable_banking",+ extra: { "enable_banking" => { "pending" => true } }+ )+ pending_entry.transaction.update!(extra: { "simplefin" => "oops", "enable_banking" => { "pending" => true } })+ pending_entry.mark_user_modified!++ assert_no_difference "@account.entries.count" do+ booked_entry = @adapter.import_transaction(+ external_id: "eb_scalar_user_mod",+ amount: 50.0,+ currency: "EUR",+ date: Date.today,+ name: "Scalar User Modified",+ source: "enable_banking",+ extra: nil+ )++ assert_not booked_entry.transaction.reload.pending?,+ "the stale flag is cleared for a user-modified entry past the malformed namespace"+ end+ end++ # The stored flag is cast the way #pending? casts it. Read for truthiness+ # instead, the string "false" counted as pending and the booked sync deleted+ # a flag that was never set.+ test "a stored pending flag of \"false\" is left alone when the booked version arrives" do+ pending_entry = @adapter.import_transaction(+ external_id: "eb_false_flag",+ amount: 18.0,+ currency: "EUR",+ date: Date.today - 1.day,+ name: "False Flag",+ source: "enable_banking",+ extra: { "enable_banking" => { "pending" => true } }+ )+ pending_entry.transaction.update!(extra: { "enable_banking" => { "pending" => "false" } })+ assert_not pending_entry.transaction.reload.pending?, "\"false\" does not mark a transaction pending"++ @adapter.import_transaction(+ external_id: "eb_false_flag",+ amount: 18.0,+ currency: "EUR",+ date: Date.today,+ name: "False Flag",+ source: "enable_banking",+ extra: nil+ )++ assert_equal "false", pending_entry.transaction.reload.extra.dig("enable_banking", "pending"),+ "a flag that does not mark the transaction pending is not cleared"+ end+privatedef capture_sql_queriesdiff --git a/test/models/akahu_account/processor_test.rb b/test/models/akahu_account/processor_test.rbindex 456ef3578c..e34927f35c 100644--- a/test/models/akahu_account/processor_test.rb+++ b/test/models/akahu_account/processor_test.rb@@ -37,6 +37,20 @@ class AkahuAccount::ProcessorTest < ActiveSupport::TestCaseassert_equal "NZD", @account.currencyend+ test "transaction processor prunes malformed pending rows but keeps false and current rows" do+ malformed = create_pending_entry("akahu_malformed", "maybe")+ false_flag = create_pending_entry("akahu_false", "off")+ current = create_pending_entry("akahu_current", "maybe")++ pruned = AkahuAccount::Transactions::Processor.new(@akahu_account)+ .send(:prune_stale_pending_entries, [ current.external_id ])++ assert_equal 1, pruned+ assert_not Entry.exists?(malformed.id)+ assert Entry.exists?(false_flag.id)+ assert Entry.exists?(current.id)+ end+test "logs account processing failures without raw exception message" dosensitive_message = "provider returned account holder details"error = RuntimeError.new(sensitive_message)@@ -135,4 +149,13 @@ class AkahuAccount::ProcessorTest < ActiveSupport::TestCase@contexts[name] = contextendend++ private+ def create_pending_entry(external_id, pending)+ @account.entries.create!(+ name: external_id, date: 10.days.ago.to_date, amount: 10, currency: "NZD",+ source: "akahu", external_id: external_id,+ entryable: Transaction.new(extra: { "akahu" => { "pending" => pending } })+ )+ endenddiff --git a/test/models/akahu_item/importer_test.rb b/test/models/akahu_item/importer_test.rbindex 0f48e6a0bf..06d2df1687 100644--- a/test/models/akahu_item/importer_test.rb+++ b/test/models/akahu_item/importer_test.rb@@ -124,6 +124,37 @@ class AkahuItem::ImporterTest < ActiveSupport::TestCaseassert_empty @akahu_account.raw_transactions_payload.select { |tx| tx["_pending"] }end+ # Pruning decides "pending" as Transaction#pending? does. A ::boolean cast+ # raised on "maybe", failing the step on every sync, and read "no" as posted.+ [ "maybe", "no" ].each do |flag|+ test "prunes a disappeared pending transaction whose stored flag is #{flag.inspect}" do+ import_with(pending_transactions: [ pending_transaction(description: "Pending card auth", amount: -8.00) ], posted_transactions: [])+ process_transactions+ entry = pending_entries.sole+ reflag(entry, flag)+ assert entry.reload.entryable.pending?++ import_with(pending_transactions: [], posted_transactions: [])+ result = process_transactions++ assert_equal 1, result[:pruned_pending]+ assert_not Entry.exists?(entry.id), "a #{flag.inspect}-flagged pending entry missing from the fetch should be pruned"+ end+ end++ test "keeps a disappeared transaction whose stored flag is the string \"false\"" do+ import_with(pending_transactions: [ pending_transaction(description: "Pending card auth", amount: -8.00) ], posted_transactions: [])+ process_transactions+ entry = pending_entries.sole+ reflag(entry, "false")++ import_with(pending_transactions: [], posted_transactions: [])+ result = process_transactions++ assert_equal 0, result[:pruned_pending]+ assert Entry.exists?(entry.id)+ end+test "keeps unchanged pending transactions without creating duplicates" dopending = [ pending_transaction(description: "Pending card auth", amount: -8.00) ]import_with(pending_transactions: pending, posted_transactions: [])@@ -213,7 +244,12 @@ class AkahuItem::ImporterTest < ActiveSupport::TestCase@account.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(source: "akahu")- .where("(transactions.extra -> 'akahu' ->> 'pending')::boolean = true")+ .where(Transaction.pending_sql("transactions", providers: %w[akahu]))+ end++ def reflag(entry, flag)+ transaction = entry.entryable+ transaction.update!(extra: transaction.extra.merge("akahu" => transaction.extra["akahu"].merge("pending" => flag)))enddef pending_transaction(description:, amount:, date: "2026-01-15")diff --git a/test/models/goal/withdrawal_detector_test.rb b/test/models/goal/withdrawal_detector_test.rbindex 68e5b07199..a66452530c 100644--- a/test/models/goal/withdrawal_detector_test.rb+++ b/test/models/goal/withdrawal_detector_test.rb@@ -126,6 +126,25 @@ class Goal::WithdrawalDetectorTest < ActiveSupport::TestCaseassert_equal [ entry.id ], detect.map(&:id)end+ # A flag PostgreSQL cannot cast to boolean used to raise and take the whole+ # panel down, hiding the posted outflow beside it too.+ test "ignores an outflow whose pending flag PostgreSQL cannot cast" do+ posted = outflow(1_000)+ outflow(1_200).entryable.update!(extra: { "simplefin" => { "pending" => "maybe" } })++ assert_equal [ posted.id ], detect.map(&:id)+ end++ # Transaction#pending? calls "no" pending, so the detector must not offer it.+ test "ignores an outflow whose pending flag is \"no\", as Transaction#pending? does" do+ posted = outflow(1_000)+ flagged = outflow(1_200)+ flagged.entryable.update!(extra: { "simplefin" => { "pending" => "no" } })++ assert flagged.entryable.pending?+ assert_equal [ posted.id ], detect.map(&:id)+ end+privatedef detect(limit: 3)Goal::WithdrawalDetector.new(@goal).unattributed_outflows(limit: limit)diff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rbindex ed049e527d..9ca882b7b5 100644--- a/test/models/income_statement_test.rb+++ b/test/models/income_statement_test.rb@@ -297,6 +297,18 @@ class IncomeStatementTest < ActiveSupport::TestCaseassert_equal Money.new(900, @family.currency), totals.expense_moneyend+ # A flag PostgreSQL cannot cast to boolean used to raise+ # PG::InvalidTextRepresentation and take the whole statement down.+ test "a pending flag PostgreSQL cannot cast neither raises nor counts" do+ assert_statement_leaves_out_flagged_expense("maybe")+ end++ # Transaction#pending? (and so the Pending badge) calls "no" pending;+ # PostgreSQL's ::boolean called it posted and counted it.+ test "a \"no\" pending flag is pending, as Transaction#pending? says" do+ assert_statement_leaves_out_flagged_expense("no")+ end+# NEW TESTS: Interval-Based Calculationstest "different intervals return different statistical results with multi-period data" do# Clear existing transactions@@ -773,4 +785,24 @@ class IncomeStatementTest < ActiveSupport::TestCaseassert_equal 1, totals_query_callsend++ private+ # Adds a 250 grocery expense whose pending flag is +flag+ and asserts every+ # figure is the one without it: totals (Transaction.excluding_pending), the+ # family median and average (FamilyStats) and the category median+ # (CategoryStats), each of which reads the flag in its own SQL.+ def assert_statement_leaves_out_flagged_expense(flag)+ flagged = create_transaction(account: @checking_account, amount: 250, category: @groceries_category)+ flagged.entryable.update!(extra: { "plaid" => { "pending" => flag } })+ assert flagged.entryable.pending?, "pending? should call #{flag.inspect} pending"++ income_statement = IncomeStatement.new(@family)+ totals = income_statement.totals(date_range: Period.last_30_days.date_range)++ assert_equal 4, totals.transactions_count+ assert_equal Money.new(900, @family.currency), totals.expense_money+ assert_equal 900.0, income_statement.median_expense(interval: "month")+ assert_equal 900.0, income_statement.avg_expense(interval: "month")+ assert_equal 900.0, income_statement.median_expense(interval: "month", category: @groceries_category)+ endenddiff --git a/test/models/monobank_account/transactions/processor_test.rb b/test/models/monobank_account/transactions/processor_test.rbindex d3924bb72a..c0cc5486a2 100644--- a/test/models/monobank_account/transactions/processor_test.rb+++ b/test/models/monobank_account/transactions/processor_test.rb@@ -111,8 +111,33 @@ class MonobankAccount::Transactions::ProcessorTest < ActiveSupport::TestCaseassert_empty pending_entries, "it is no longer held, so the pending flag is gone"end+ # The prune decides pending the way Transaction#pending? does. A flag PostgreSQL+ # cannot cast to boolean ("maybe") must neither abort the prune nor survive it,+ # and a false value ActiveModel recognises ("off") must not be pruned as pending.+ test "prunes malformed pending rows but keeps false and current rows" do+ malformed = create_pending_entry("monobank_malformed", "maybe")+ false_flag = create_pending_entry("monobank_false", "off")+ current = create_pending_entry("monobank_current", "maybe")++ result = MonobankAccount::Transactions::Processor.new(@monobank_account)+ .send(:prune_stale_pending_entries, [ current.external_id ])++ assert_equal({ pruned: 1, protected: 0 }, result)+ assert_not Entry.exists?(malformed.id)+ assert Entry.exists?(false_flag.id)+ assert Entry.exists?(current.id)+ end+private+ def create_pending_entry(external_id, pending)+ @account.entries.create!(+ name: external_id, date: 10.days.ago.to_date, amount: 10, currency: "UAH",+ source: "monobank", external_id: external_id,+ entryable: Transaction.new(extra: { "monobank" => { "pending" => pending } })+ )+ end+def transaction(id:, mcc: 5411, hold: false, amount: -4_000){"id" => id,@@ -137,6 +162,6 @@ class MonobankAccount::Transactions::ProcessorTest < ActiveSupport::TestCase@account.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(source: "monobank")- .where("(transactions.extra -> 'monobank' ->> 'pending')::boolean = true")+ .where(Transaction.pending_sql("transactions", providers: [ "monobank" ]))endenddiff --git a/test/models/portfolio/flow_classifier_test.rb b/test/models/portfolio/flow_classifier_test.rbnew file mode 100644index 0000000000..879d483cee--- /dev/null+++ b/test/models/portfolio/flow_classifier_test.rb@@ -0,0 +1,398 @@+require "test_helper"++# Each test here demonstrates one rule of the classifier's contract, which is+# stated in full at the top of Portfolio::FlowClassifier: what counts as+# income, fee, internal movement or external flow, how scope decides a+# transfer, and what a caller must do with the answer. One test per rule, so a+# rule that loses its evidence loses a named test with it.+class Portfolio::FlowClassifierTest < ActiveSupport::TestCase+ include PortfolioFlowTestHelper++ setup do+ @family = families(:empty)+ @brokerage = create_portfolio_account(@family, name: "Brokerage")+ @ira = create_portfolio_account(@family, name: "IRA")+ @checking = @family.accounts.create!(name: "Checking", balance: 5000, currency: "USD", accountable: Depository.new)++ @family_scope = Portfolio::FlowClassifier.new(scope_account_ids: [ @brokerage.id, @ira.id ])+ @brokerage_scope = Portfolio::FlowClassifier.new(scope_account_ids: [ @brokerage.id ])+ end++ test "a Dividend income trade is income" do+ entry = create_income_trade(account: @brokerage, label: "Dividend", amount: 50)++ assert_equal :income, @family_scope.classify(entry)+ assert_equal :income, @brokerage_scope.classify(entry)+ end++ test "a Dividend transaction carrying the security id in extra is income" do+ flat = create_income_transaction(account: @brokerage, label: "Dividend", amount: 12.5, extra_shape: :flat)+ nested = create_income_transaction(account: @brokerage, label: "Dividend", amount: 7, extra_shape: :nested)+ bare = create_income_transaction(account: @brokerage, label: "Dividend", amount: 3, extra_shape: :none)++ assert_equal :income, @family_scope.classify(flat)+ assert_equal :income, @family_scope.classify(nested)+ assert_equal :income, @family_scope.classify(bare)+ end++ test "a Plaid-shaped zero-amount Dividend trade is income" do+ entry = create_plaid_dividend_trade(account: @brokerage)++ assert_equal 0, entry.amount+ assert_equal :income, @family_scope.classify(entry),+ "the cash is invisible (amount 0) but the entry is still income, not a deposit"+ end++ test "Interest is income whether stored as a trade or a transaction" do+ trade = create_income_trade(account: @brokerage, label: "Interest", amount: 4)+ transaction = create_income_transaction(account: @brokerage, label: "Interest", amount: 4, extra_shape: :none)++ assert_equal :income, @family_scope.classify(trade)+ assert_equal :income, @family_scope.classify(transaction)+ end++ test "a Fee label is a fee whether stored as a trade or a transaction" do+ trade = create_portfolio_trade(account: @brokerage, qty: 0, price: 0, fee: 0, label: "Fee")+ trade.update!(amount: 9.95)+ transaction = create_labelled_transaction(account: @brokerage, label: "Fee", amount: 1.5)++ assert_equal :fee, @family_scope.classify(trade)+ assert_equal :fee, @family_scope.classify(transaction)+ end++ # Income and fee are decided by the label alone; the amount keeps its sign,+ # so a caller summing signed amounts per class nets a reversal correctly.+ test "income and fee are decided by label, not by the sign of the amount" do+ interest_charge = create_labelled_transaction(account: @brokerage, label: "Interest", amount: 7.5)+ fee_rebate = create_labelled_transaction(account: @brokerage, label: "Fee", amount: -2)+ interest_trade_charge = create_income_trade(account: @brokerage, label: "Interest", amount: 4)+ interest_trade_charge.update_columns(amount: 4)++ assert interest_charge.amount.positive?, "precondition: money out, as a margin-interest charge"+ assert fee_rebate.amount.negative?, "precondition: money in, as a fee rebate"+ assert interest_trade_charge.reload.amount.positive?, "precondition: money out on a trade"++ sql = @family_scope.classify_ids([ interest_charge.id, fee_rebate.id, interest_trade_charge.id ])++ [ interest_charge, interest_trade_charge ].each do |entry|+ assert_equal :income, @family_scope.classify(entry)+ assert_equal :income, sql[entry.id]+ end+ assert_equal :fee, @family_scope.classify(fee_rebate)+ assert_equal :fee, sql[fee_rebate.id]+ end++ test "the fee leg of a linked transfer is a fee" do+ transfer = create_linked_transfer(family: @family, from: @checking, to: @brokerage, amount: 500, source_fee_amount: 2)+ fee_entry = transfer.fee_transactions.first.entry++ assert_equal "standard", fee_entry.entryable.kind+ assert_nil fee_entry.entryable.investment_activity_label+ assert_equal :fee, Portfolio::FlowClassifier.new(scope_account_ids: [ @checking.id ]).classify(fee_entry)+ end++ test "Buy, Sell and Reinvestment trades are internal" do+ buy = create_portfolio_trade(account: @brokerage, qty: 10, price: 100)+ sell = create_portfolio_trade(account: @brokerage, qty: -4, price: 110)+ reinvestment = create_portfolio_trade(account: @brokerage, qty: 1, price: 50, label: "Reinvestment")++ assert_equal :internal, @family_scope.classify(buy)+ assert_equal :internal, @family_scope.classify(sell)+ assert_equal :internal, @family_scope.classify(reinvestment),+ "reinvested dividends are only income when a separate Dividend entry records them"+ assert_equal :internal, @brokerage_scope.classify(buy)+ end++ test "Sweep In, Sweep Out and Exchange are internal at both scopes" do+ [ "Sweep In", "Sweep Out", "Exchange" ].each do |label|+ trade = create_portfolio_trade(account: @brokerage, qty: 5, price: 1, label: label)+ transaction = create_labelled_transaction(account: @brokerage, label: label, amount: -5)++ assert_equal :internal, @family_scope.classify(trade), "#{label} trade"+ assert_equal :internal, @brokerage_scope.classify(transaction), "#{label} transaction"+ end+ end++ test "Contribution and Withdrawal labels are external in the direction of the money" do+ deposit = create_labelled_transaction(account: @brokerage, label: "Contribution", amount: -1000)+ withdrawal = create_labelled_transaction(account: @brokerage, label: "Withdrawal", amount: 250)+ # Kraken's ledger writes these with kind funds_movement and no Transfer+ # row; the label still decides.+ kraken_deposit = create_labelled_transaction(account: @brokerage, label: "Contribution", amount: -300, kind: "funds_movement")++ assert_equal :external_inflow, @family_scope.classify(deposit)+ assert_equal :external_outflow, @family_scope.classify(withdrawal)+ assert_equal :external_inflow, @family_scope.classify(kraken_deposit)+ end++ test "a linked transfer is internal at family scope and external at account scope" do+ transfer = create_linked_transfer(family: @family, from: @brokerage, to: @ira, amount: 400)+ outflow = transfer.outflow_transaction.entry+ inflow = transfer.inflow_transaction.entry++ assert_equal "funds_movement", transfer.outflow_transaction.kind++ assert_equal :internal, @family_scope.classify(outflow)+ assert_equal :internal, @family_scope.classify(inflow)++ assert_equal :external_outflow, @brokerage_scope.classify(outflow)+ assert_equal :external_inflow, Portfolio::FlowClassifier.new(scope_account_ids: [ @ira.id ]).classify(inflow)+ end++ # A provider that labels both legs of a real transfer used to outrank the+ # transfer itself, so money moved between two accounts inside the scope read+ # as money leaving the portfolio and arriving from outside it -- twice over,+ # once on each leg.+ test "a Contribution or Withdrawal label does not outrank a linked transfer in scope" do+ transfer = create_linked_transfer(family: @family, from: @brokerage, to: @ira, amount: 100)+ transfer.outflow_transaction.update!(investment_activity_label: "Withdrawal")+ transfer.inflow_transaction.update!(investment_activity_label: "Contribution")+ outflow = transfer.outflow_transaction.entry.reload+ inflow = transfer.inflow_transaction.entry.reload++ assert_equal :internal, @family_scope.classify(outflow)+ assert_equal :internal, @family_scope.classify(inflow)++ by_sql = @family_scope.classify_ids([ outflow.id, inflow.id ])+ assert_equal :internal, by_sql[outflow.id]+ assert_equal :internal, by_sql[inflow.id]++ # The label still decides when the other leg is outside the scope, which is+ # what makes this a precedence fix rather than a label the classifier stopped+ # reading.+ assert_equal :external_outflow, @brokerage_scope.classify(outflow)+ assert_equal :external_outflow, @brokerage_scope.classify_ids([ outflow.id ])[outflow.id]+ end++ test "an investment contribution from outside the scope is an external inflow" do+ transfer = create_linked_transfer(family: @family, from: @checking, to: @brokerage, amount: 1000)+ inflow = transfer.inflow_transaction.entry+ outflow = transfer.outflow_transaction.entry++ assert_equal "investment_contribution", transfer.outflow_transaction.kind+ assert_equal :external_inflow, @family_scope.classify(inflow)+ assert_equal :external_inflow, @brokerage_scope.classify(inflow)++ # Seen from a scope that contains both accounts, the same pair is internal.+ household = Portfolio::FlowClassifier.new(scope_account_ids: [ @checking.id, @brokerage.id ])+ assert_equal :internal, household.classify(inflow)+ assert_equal :internal, household.classify(outflow)+ end++ test "a transfer-kind transaction with no linked counterpart is external by sign" do+ unlinked_in = create_labelled_transaction(account: @brokerage, label: nil, amount: -800, kind: "funds_movement")+ unlinked_out = create_labelled_transaction(account: @brokerage, label: nil, amount: 200, kind: "investment_contribution")++ assert_equal :external_inflow, @family_scope.classify(unlinked_in)+ assert_equal :external_outflow, @family_scope.classify(unlinked_out)+ end++ test "a security transfer is internal only when its opposite leg is in scope" do+ security = create_portfolio_security+ out_leg, in_leg = create_security_transfer(security: security, from: @brokerage, to: @ira, qty: 10, price: 50)++ assert_equal :internal, @family_scope.classify(out_leg)+ assert_equal :internal, @family_scope.classify(in_leg)++ assert_equal :external_outflow, @brokerage_scope.classify(out_leg)+ assert_equal :external_inflow, Portfolio::FlowClassifier.new(scope_account_ids: [ @ira.id ]).classify(in_leg)++ # A Transfer trade with no opposite leg anywhere (position moved in from+ # a broker that is not tracked) is external even at family scope.+ orphan = create_portfolio_trade(account: @brokerage, security: create_portfolio_security, qty: 3, price: 20, label: "Transfer")+ assert_equal :external_inflow, @family_scope.classify(orphan)+ end++ # entries.excluded is nullable. #classify reads a NULL as live (excluded? is+ # false), and so does the SQL CASE (WHEN NULL is not taken), so the opposite+ # leg's lookup has to read it the same way; `excluded = false` dropped it and+ # turned an in-scope move into an external flow. An excluded leg still does+ # not count, which is the other side of the boundary.+ test "a security transfer leg with a NULL excluded flag still counts as the opposite leg" do+ security = create_portfolio_security+ out_leg, in_leg = create_security_transfer(security: security, from: @brokerage, to: @ira, qty: 10, price: 50)++ in_leg.update_columns(excluded: nil)+ assert_nil in_leg.reload.excluded, "precondition: the opposite leg's flag is NULL, not false"++ assert_equal :internal, @family_scope.classify(out_leg)+ assert_equal :internal, @family_scope.classify_ids([ out_leg.id ])[out_leg.id]++ in_leg.update_columns(excluded: true)++ assert_equal :external_outflow, @family_scope.classify(out_leg)+ assert_equal :external_outflow, @family_scope.classify_ids([ out_leg.id ])[out_leg.id]+ end++ test "an unlabelled or Other trade is internal" do+ unlabelled = create_portfolio_trade(account: @brokerage, qty: 2, price: 10, label: nil)+ unlabelled.entryable.update!(investment_activity_label: nil)+ other = create_portfolio_trade(account: @brokerage, qty: -2, price: 10, label: "Other")++ assert_nil unlabelled.entryable.reload.investment_activity_label+ assert_equal :internal, @family_scope.classify(unlabelled)+ assert_equal :internal, @family_scope.classify(other)+ end++ test "an unlabelled standard transaction is external by sign" do+ deposit = create_labelled_transaction(account: @brokerage, label: nil, amount: -150)+ withdrawal = create_labelled_transaction(account: @brokerage, label: "Other", amount: 75)++ assert_equal :external_inflow, @family_scope.classify(deposit)+ assert_equal :external_outflow, @family_scope.classify(withdrawal)+ end++ test "a pending flag that is not a boolean is read the same way by both forms" do+ # ActiveModel::Type::Boolean is the Ruby definition, so anything present+ # that is not one of its false values is pending. The SQL form used to+ # cast with ::boolean, which disagrees ('no' is false to PostgreSQL and+ # true to ActiveModel) and raises on anything it cannot parse.+ shapes = { "no" => nil, "maybe" => nil, "true" => nil, "false" => :income, "0" => :income, "" => :income }++ shapes.each do |flag, expected|+ entry = create_labelled_transaction(account: @brokerage, label: "Dividend", amount: -10, extra: { "plaid" => { "pending" => flag } })++ assert_equal expected, @family_scope.classify(entry.reload), "Ruby, pending=#{flag.inspect}"+ assert_equal expected, @family_scope.classify_ids([ entry.id ])[entry.id], "SQL, pending=#{flag.inspect}"+ end+ end++ test "excluded entries, pending transactions and valuations are not classified" do+ excluded = create_portfolio_trade(account: @brokerage, qty: 1, price: 10, excluded: true)+ pending = create_labelled_transaction(account: @brokerage, label: "Dividend", amount: -10, extra: { "simplefin" => { "pending" => true } })+ valuation = @brokerage.entries.create!(name: "Valuation", date: Date.current, amount: 1000, currency: "USD", entryable: Valuation.new(kind: "reconciliation"))++ assert_nil @family_scope.classify(excluded)+ assert_nil @family_scope.classify(pending)+ assert_nil @family_scope.classify(valuation)+ end++ test "direction follows the trade quantity sign or the transaction amount sign" do+ inflow_trade = create_portfolio_trade(account: @brokerage, qty: 5, price: 10, label: "Contribution")+ outflow_trade = create_portfolio_trade(account: @brokerage, qty: -5, price: 10, label: "Withdrawal")+ inflow_transaction = create_labelled_transaction(account: @brokerage, label: "Withdrawal", amount: -20)++ assert_equal :external_inflow, @family_scope.classify(inflow_trade)+ assert_equal :external_outflow, @family_scope.classify(outflow_trade)+ # The label says withdrawal but money came in: the sign wins, so a+ # mislabelled row cannot flip the direction of a return.+ assert_equal :external_inflow, @family_scope.classify(inflow_transaction)+ end++ test "every activity label has a rule" do+ assert_equal Transaction::ACTIVITY_LABELS.sort, Portfolio::FlowClassifier::LABEL_RULES.keys.sort+ assert_equal Trade::ACTIVITY_LABELS.sort, Portfolio::FlowClassifier::LABEL_RULES.keys.sort+ assert_includes Portfolio::FlowClassifier.labels_for(:income), "Dividend"+ assert_equal %w[Fee], Portfolio::FlowClassifier.labels_for(:fee)+ end++ test "scope_account_ids is required" do+ assert_raises(ArgumentError) { Portfolio::FlowClassifier.new }+ end++ test "the SQL form agrees with the Ruby form on every corpus entry at both scopes" do+ corpus = build_corpus++ [ @family_scope, @brokerage_scope, Portfolio::FlowClassifier.new(scope_account_ids: [ @checking.id, @brokerage.id ]) ].each do |classifier|+ ruby = corpus.to_h { |entry| [ entry.id, classifier.classify(entry.reload) ] }+ sql = classifier.classify_ids(corpus.map(&:id))++ assert_equal corpus.size, sql.size+ ruby.each do |id, ruby_class|+ entry = corpus.find { |e| e.id == id }+ # assert_nil / assert_equal split so a nil expectation does not trip+ # Minitest's deprecation of assert_equal nil.+ message =+ "scope #{classifier.scope_account_ids.size} accounts: #{entry.name} (#{entry.entryable_type}, #{entry.entryable.try(:investment_activity_label).inspect}, kind #{entry.entryable.try(:kind).inspect})"+ if ruby_class.nil?+ assert_nil sql.fetch(id), message+ else+ assert_equal ruby_class, sql.fetch(id), message+ end+ end+ end++ assert_equal Portfolio::FlowClassifier::CLASSES.sort, @family_scope.classify_ids(corpus.map(&:id)).values.compact.uniq.sort,+ "the corpus must exercise every class"+ end++ test "the SQL form only binds the scope ids and never interpolates entry data" do+ sql = @family_scope.sql_case++ assert_includes sql, "ARRAY['#{@brokerage.id}','#{@ira.id}']::uuid[]"+ Portfolio::FlowClassifier::LABEL_RULES.keys.each do |label|+ next if label == "Other"+ assert_includes sql, "'#{label}'"+ end+ assert_no_match(/#\{/, sql)++ # Finished SQL, not a template. If any `:name` survived here, handing the+ # CASE to sanitize_sql_array (as an earlier version did) would read it as+ # a bind variable and raise before the query ran -- which is what a label+ # carrying a colon used to do. `::` casts are not placeholders.+ placeholders = sql.gsub("::", "").scan(/:[a-zA-Z]\w*/)+ assert_empty placeholders, "sql_case must be final SQL, not a bind template"+ end++ private+ # One entry per contract row plus the shapes each provider writes, at+ # every position the classifier branches on.+ def build_corpus+ security = create_portfolio_security+ entries = []+ entries << create_income_trade(account: @brokerage, label: "Dividend", amount: 50)+ entries << create_income_transaction(account: @brokerage, label: "Dividend", amount: 12, extra_shape: :flat)+ entries << create_income_transaction(account: @ira, label: "Dividend", amount: 12, extra_shape: :nested)+ entries << create_plaid_dividend_trade(account: @brokerage)+ entries << create_income_trade(account: @brokerage, label: "Interest", amount: 4)+ entries << create_income_transaction(account: @brokerage, label: "Interest", amount: 4, extra_shape: :none)+ entries << create_portfolio_trade(account: @brokerage, qty: 0, price: 0, label: "Fee").tap { |e| e.update!(amount: 9.95) }+ entries << create_labelled_transaction(account: @brokerage, label: "Fee", amount: 1.5)+ entries << create_portfolio_trade(account: @brokerage, qty: 10, price: 100, fee: 5)+ entries << create_portfolio_trade(account: @brokerage, qty: -4, price: 110, fee: 5, fee_in_amount: false)+ entries << create_portfolio_trade(account: @ira, qty: 1, price: 50, label: "Reinvestment")+ [ "Sweep In", "Sweep Out", "Exchange" ].each do |label|+ entries << create_portfolio_trade(account: @brokerage, qty: 5, price: 1, label: label)+ entries << create_labelled_transaction(account: @ira, label: label, amount: -5)+ end+ entries << create_labelled_transaction(account: @brokerage, label: "Contribution", amount: -1000)+ entries << create_labelled_transaction(account: @brokerage, label: "Withdrawal", amount: 250)+ entries << create_labelled_transaction(account: @ira, label: "Contribution", amount: -300, kind: "funds_movement")+ entries << create_portfolio_trade(account: @brokerage, qty: 5, price: 10, label: "Contribution")+ entries << create_portfolio_trade(account: @brokerage, qty: -5, price: 10, label: "Withdrawal")++ internal_transfer = create_linked_transfer(family: @family, from: @brokerage, to: @ira, amount: 400, source_fee_amount: 1)+ entries << internal_transfer.outflow_transaction.entry+ entries << internal_transfer.inflow_transaction.entry+ entries << internal_transfer.fee_transactions.first.entry++ contribution = create_linked_transfer(family: @family, from: @checking, to: @brokerage, amount: 1000)+ entries << contribution.outflow_transaction.entry+ entries << contribution.inflow_transaction.entry++ entries << create_labelled_transaction(account: @brokerage, label: nil, amount: -800, kind: "funds_movement")+ entries << create_labelled_transaction(account: @ira, label: nil, amount: 200, kind: "investment_contribution")+ entries << create_labelled_transaction(account: @brokerage, label: "Transfer", amount: 60)++ entries.concat(create_security_transfer(security: security, from: @brokerage, to: @ira, qty: 10, price: 50))+ entries << create_portfolio_trade(account: @brokerage, security: create_portfolio_security, qty: 3, price: 20, label: "Transfer")+ entries << create_portfolio_trade(account: @brokerage, security: security, qty: -10, price: 50, label: "Transfer", date: 1.day.ago.to_date)++ entries << create_portfolio_trade(account: @brokerage, qty: 2, price: 10).tap { |e| e.entryable.update!(investment_activity_label: nil) }+ entries << create_portfolio_trade(account: @brokerage, qty: -2, price: 10, label: "Other")+ entries << create_labelled_transaction(account: @brokerage, label: nil, amount: -150)+ entries << create_labelled_transaction(account: @brokerage, label: "Other", amount: 75)++ entries << create_portfolio_trade(account: @brokerage, qty: 1, price: 10, excluded: true)+ entries << create_labelled_transaction(account: @brokerage, label: "Dividend", amount: -10, extra: { "plaid" => { "pending" => true } })+ # Providers write real booleans, but the flag is whatever arrived. A+ # string PostgreSQL would read as a boolean and one it cannot read at+ # all both have to classify the same way in Ruby and in SQL -- the+ # second used to abort the whole query rather than one entry.+ entries << create_labelled_transaction(account: @brokerage, label: "Dividend", amount: -11, extra: { "plaid" => { "pending" => "no" } })+ entries << create_labelled_transaction(account: @brokerage, label: "Dividend", amount: -12, extra: { "plaid" => { "pending" => "maybe" } })+ entries << create_labelled_transaction(account: @brokerage, label: "Dividend", amount: -13, extra: { "plaid" => { "pending" => "false" } })+ entries << @brokerage.entries.create!(name: "Valuation", date: Date.current, amount: 1000, currency: "USD", entryable: Valuation.new(kind: "reconciliation"))+ entries+ end+enddiff --git a/test/models/simplefin_item/importer_stale_unmatched_pending_test.rb b/test/models/simplefin_item/importer_stale_unmatched_pending_test.rbnew file mode 100644index 0000000000..2bc0c34679--- /dev/null+++ b/test/models/simplefin_item/importer_stale_unmatched_pending_test.rb@@ -0,0 +1,68 @@+require "test_helper"++# track_stale_unmatched_pending counts stale pending entries that have no posted+# match. It decides "pending" as Transaction#pending? does, across every pending+# provider, like the stale-pending exclusion that runs straight after it. The+# order of the two is pinned in SimplefinItem::ImporterTest; these tests cover+# the predicate alone.+class SimplefinItem::ImporterStaleUnmatchedPendingTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:empty)+ @item = SimplefinItem.create!(family: @family, name: "SF Conn", access_url: "https://example.com/access")+ @account = @family.accounts.create!(name: "SF Checking", balance: 0, currency: "USD", accountable: Depository.new)+ @importer = SimplefinItem::Importer.new(@item, simplefin_provider: mock(), sync: Sync.create!(syncable: @item))+ end++ test "counts a stale entry whose flag a boolean cast cannot parse, without recording an error" do+ stale_entry("simplefin" => { "pending" => "maybe" })++ track++ assert_nil stats["reconciliation_errors"]+ assert_equal 1, stats["stale_unmatched_pending"]+ end++ test "counts a stale entry flagged \"no\", which pending? calls pending" do+ stale_entry("simplefin" => { "pending" => "no" })++ track++ assert_equal 1, stats["stale_unmatched_pending"]+ end++ test "counts a stale entry pending under any provider, not only SimpleFIN and Plaid" do+ stale_entry("lunchflow" => { "pending" => true })++ track++ assert_equal 1, stats["stale_unmatched_pending"]+ end++ test "does not count stale entries that are not pending" do+ stale_entry("plaid" => { "pending" => "false" })+ stale_entry({})++ track++ assert_nil stats["reconciliation_errors"]+ assert_nil stats["stale_unmatched_pending"]+ end++ private++ def stale_entry(extra)+ create_transaction(account: @account, amount: 10, date: 10.days.ago.to_date).tap do |entry|+ entry.entryable.update!(extra: extra)+ end+ end++ def track+ @importer.send(:track_stale_unmatched_pending, @account)+ end++ def stats+ @importer.send(:stats)+ end+enddiff --git a/test/models/simplefin_item/importer_test.rb b/test/models/simplefin_item/importer_test.rbindex c38c2f1b6a..a4e67f98ef 100644--- a/test/models/simplefin_item/importer_test.rb+++ b/test/models/simplefin_item/importer_test.rb@@ -119,8 +119,35 @@ class SimplefinItem::ImporterTest < ActiveSupport::TestCaseassert_equal 1_000, depository.cash_balanceend+ # Both steps read every provider's flag and decide "pending" the same way, so+ # the sync must count for review before it excludes: run through their one+ # caller and the stale Lunch Flow entry is reported and then excluded, rather+ # than excluded by the first step and invisible to the second. Swap the two+ # calls and stale_unmatched_pending goes to nil here.+ test "stale pending review counts every provider's flag before the exclusion hides it" do+ account = @family.accounts.create!(name: "Stale pending", balance: 0, currency: "USD", accountable: Depository.new)+ create_pending_entry(account, "simplefin_maybe", "simplefin", "maybe", 10)+ create_pending_entry(account, "simplefin_false", "simplefin", "off", 11)+ create_pending_entry(account, "lunchflow_pending", "lunchflow", true, 12)++ @importer.send(:review_and_exclude_stale_pending, account)++ stats = @importer.send(:stats)+ assert_equal 2, stats["stale_unmatched_pending"]+ assert_equal 2, stats["stale_pending_excluded"]+ assert_empty stats.fetch("reconciliation_errors", [])+ assert_equal [ "simplefin_false" ], account.entries.where(excluded: false).pluck(:name)+ end+private+ def create_pending_entry(account, name, provider, pending, amount)+ account.entries.create!(+ name: name, date: 10.days.ago.to_date, amount: amount, currency: "USD",+ entryable: Transaction.new(extra: { provider => { "pending" => pending } })+ )+ end+def create_simplefin_account(account_id, name, account_type, current_balance)@item.simplefin_accounts.create!(name: name,diff --git a/test/models/transaction_test.rb b/test/models/transaction_test.rbindex e4f8f1f202..f35c70766a 100644--- a/test/models/transaction_test.rb+++ b/test/models/transaction_test.rb@@ -125,6 +125,130 @@ class TransactionTest < ActiveSupport::TestCaseassert_not transaction.pending?end+ # The SQL forms of "is this pending?" must give the answer pending? gives for+ # whatever is stored. PostgreSQL's ::boolean reads "no", "False", "Off" and+ # " false" as false where ActiveModel::Type::Boolean reads them as true.+ test "every SQL pending predicate agrees with pending? on any stored flag" do+ account = families(:empty).accounts.create! name: "Pending parity", balance: 0, currency: "USD", accountable: Depository.new++ [ true, false, nil, "true", "false", "no", "False", "Off", " false", "", "0", "1", "t", "f", 1, 0, 0.0 ].each do |flag|+ transaction = create_transaction(account: account, amount: 10).entryable+ transaction.update!(extra: { "plaid" => { "pending" => flag } })++ sql_pending_answers(transaction).each do |form, answer|+ assert_equal transaction.pending?, answer, "#{form} disagrees with pending? on #{flag.inspect}"+ end+ end+ end++ # ::boolean raises PG::InvalidTextRepresentation on a value it cannot parse,+ # which aborts the whole query -- an income statement, a balance sync -- not+ # just the one row.+ test "no SQL pending predicate raises on a flag PostgreSQL cannot cast" do+ account = families(:empty).accounts.create! name: "Pending parity", balance: 0, currency: "USD", accountable: Depository.new+ transaction = create_transaction(account: account, amount: 10).entryable+ transaction.update!(extra: { "simplefin" => { "pending" => "maybe" } })++ assert transaction.pending?+ sql_pending_answers(transaction).each do |form, answer|+ assert answer, "#{form} should call a \"maybe\" flag pending, as pending? does"+ end+ end++ test "SQL false values stay in sync with ActiveModel boolean casting" do+ expected_false_values = Set.new(ActiveModel::Type::Boolean::FALSE_VALUES.grep(String)).add("")++ assert_equal expected_false_values, Transaction::PENDING_FLAG_FALSE_VALUES.to_set+ end++ # pending_sql and PENDING_CHECK_SQL share one connection-free literal list;+ # it must quote exactly as the database adapter would.+ test "the shared SQL false-value list matches the adapter's quoting" do+ adapter_quoted = Transaction::PENDING_FLAG_FALSE_VALUES.map { |value| Transaction.connection.quote(value) }.join(", ")++ assert_equal adapter_quoted, Transaction::PENDING_FLAG_FALSE_VALUES_SQL+ assert_includes Transaction.pending_sql, "NOT IN (#{adapter_quoted})"+ assert_includes Transaction::PENDING_CHECK_SQL, "NOT IN (#{adapter_quoted})"+ end++ test "provider-specific SQL only considers the requested pending namespaces" do+ account = families(:empty).accounts.create! name: "Provider pending scope", balance: 0,+ currency: "USD", accountable: Depository.new+ akahu_pending = create_transaction(account: account, amount: 10).entryable+ akahu_pending.update!(extra: { "akahu" => { "pending" => "maybe" } })+ akahu_false = create_transaction(account: account, amount: 11).entryable+ akahu_false.update!(extra: { "akahu" => { "pending" => "off" } })+ other_provider = create_transaction(account: account, amount: 12).entryable+ other_provider.update!(extra: { "simplefin" => { "pending" => true } })++ matches = Transaction.where(Transaction.pending_sql("transactions", providers: [ :akahu ]))++ assert_equal [ akahu_pending.id ], matches.pluck(:id)+ assert_equal [ akahu_pending.id ], Transaction.where(+ Transaction.pending_sql("transactions", providers: [ "akahu", "unsupported" ])+ ).pluck(:id)+ assert_empty Transaction.where(Transaction.pending_sql("transactions", providers: [])).pluck(:id)+ end++ # Narrowed to some providers, the SQL is the same rule applied to those+ # providers' flags only: another provider's flag must not leak in.+ test "pending_sql for a provider subset agrees with pending? on that provider's flag alone" do+ account = families(:empty).accounts.create! name: "Pending subset", balance: 0, currency: "USD", accountable: Depository.new++ [ true, false, nil, "true", "false", "no", "False", "Off", " false", "", "0", "1", "t", "f", "maybe", 1, 0 ].each do |flag|+ transaction = create_transaction(account: account, amount: 10).entryable+ transaction.update!(extra: { "up" => { "pending" => flag }, "plaid" => { "pending" => true } })+ expected = Transaction.new(extra: { "up" => { "pending" => flag } }).pending?++ assert_equal expected, Transaction.where(Transaction.pending_sql(providers: %w[up])).exists?(transaction.id),+ "pending_sql(providers: up) disagrees with pending? on #{flag.inspect}"+ assert_equal !expected, Transaction.where(Transaction.not_pending_sql(providers: %w[up])).exists?(transaction.id),+ "not_pending_sql(providers: up) disagrees with pending? on #{flag.inspect}"+ end+ end++ test "pending SQL quotes the table alias and JSON keys" do+ connection = ActiveRecord::Base.connection+ table_alias = "pending alias"+ sql = Transaction.pending_sql(table_alias)++ assert_includes sql, "#{connection.quote_table_name(table_alias)}.extra"+ assert_includes sql, "-> #{connection.quote(Transaction::PENDING_PROVIDERS.first)} ->> #{connection.quote('pending')}"+ false_values = Transaction::PENDING_FLAG_FALSE_VALUES.map { |value| connection.quote(value) }.join(", ")+ assert_includes sql, "NOT IN (#{false_values})"+ assert_not_includes sql, "#{table_alias}.extra"+ end++ # A provider key holding something other than an object says nothing about+ # that provider, and must not stop another provider's flag from counting.+ # SQL reads NULL for it and moves on; pending? used to raise inside+ # Hash#dig and rescue the whole row to false.+ test "malformed metadata under one provider does not hide another provider's flag" do+ account = families(:empty).accounts.create! name: "Pending parity", balance: 0, currency: "USD", accountable: Depository.new++ [ "bad", [ "pending" ], 1 ].each do |malformed|+ transaction = create_transaction(account: account, amount: 10).entryable+ transaction.update!(extra: { "simplefin" => malformed, "plaid" => { "pending" => true } })++ assert transaction.pending?, "pending? should see plaid's flag past simplefin => #{malformed.inspect}"+ sql_pending_answers(transaction).each do |form, answer|+ assert answer, "#{form} should see plaid's flag past simplefin => #{malformed.inspect}"+ end+ end+ end++ test "pending_duplicate_candidates offers only transactions pending? calls posted" do+ account = families(:empty).accounts.create! name: "Merge", balance: 0, currency: "USD", accountable: Depository.new+ pending_entry = create_transaction(account: account, amount: 10)+ pending_entry.entryable.update!(extra: { "plaid" => { "pending" => true } })++ posted = create_transaction(account: account, amount: 10)+ create_transaction(account: account, amount: 10).entryable.update!(extra: { "plaid" => { "pending" => "no" } })+ create_transaction(account: account, amount: 10).entryable.update!(extra: { "plaid" => { "pending" => "maybe" } })++ assert_equal [ posted.id ], pending_entry.entryable.pending_duplicate_candidates.map(&:id)+ end+test "investment_contribution is a valid kind" dotransaction = Transaction.new(kind: "investment_contribution")@@ -419,4 +543,23 @@ class TransactionTest < ActiveSupport::TestCaseassert_equal [ tags(:one).id, tags(:two).id ].sort, transaction.reload.tag_ids.sortend++ private+ # Whether each SQL form of "is this transaction pending?" says it is.+ def sql_pending_answers(transaction)+ entry_id = transaction.entry.id+ posted_row = ActiveRecord::Base.connection.select_value(+ ActiveRecord::Base.sanitize_sql_array([+ "SELECT 1 FROM transactions t WHERE t.id = ? #{Transaction.pending_providers_sql("t")}", transaction.id+ ])+ )++ {+ "Transaction.pending" => Transaction.pending.exists?(transaction.id),+ "Transaction.excluding_pending" => !Transaction.excluding_pending.exists?(transaction.id),+ "Entry.pending" => Entry.pending.exists?(entry_id),+ "Entry.excluding_pending (pending_check_sql)" => !Entry.excluding_pending.exists?(entry_id),+ "Transaction.pending_providers_sql" => posted_row.nil?+ }+ endenddiff --git a/test/models/up_account/transactions/processor_test.rb b/test/models/up_account/transactions/processor_test.rbindex 24f8c5f95d..44d67b0543 100644--- a/test/models/up_account/transactions/processor_test.rb+++ b/test/models/up_account/transactions/processor_test.rb@@ -65,4 +65,27 @@ class UpAccount::Transactions::ProcessorTest < ActiveSupport::TestCaseentry = @account.entries.find_by(external_id: "up_tx_2")assert_equal "Groceries", entry.transaction.category&.nameend++ test "prunes malformed pending rows but keeps false and current rows" do+ malformed = create_pending_entry("up_malformed", "maybe")+ false_flag = create_pending_entry("up_false", "off")+ current = create_pending_entry("up_current", "maybe")++ pruned = UpAccount::Transactions::Processor.new(@up_account)+ .send(:prune_stale_pending_entries, [ current.external_id ])++ assert_equal 1, pruned+ assert_not Entry.exists?(malformed.id)+ assert Entry.exists?(false_flag.id)+ assert Entry.exists?(current.id)+ end++ private+ def create_pending_entry(external_id, pending)+ @account.entries.create!(+ name: external_id, date: 10.days.ago.to_date, amount: 10, currency: "AUD",+ source: "up", external_id: external_id,+ entryable: Transaction.new(extra: { "up" => { "pending" => pending } })+ )+ endenddiff --git a/test/models/up_item/importer_test.rb b/test/models/up_item/importer_test.rbindex 73ff169255..09c0ce1160 100644--- a/test/models/up_item/importer_test.rb+++ b/test/models/up_item/importer_test.rb@@ -112,8 +112,44 @@ class UpItem::ImporterTest < ActiveSupport::TestCaseassert_empty @up_account.raw_transactions_payload.select { |tx| UpEntry::Processor.pending?(tx) }end+ # Pruning decides "pending" as Transaction#pending? does. A ::boolean cast+ # raised on "maybe", failing the step on every sync, and read "no" as settled.+ [ "maybe", "no" ].each do |flag|+ test "prunes a disappeared held transaction whose stored flag is #{flag.inspect}" do+ import_with(transactions: [ held_transaction(id: "tx_h3", amount: "-8.00") ])+ process_transactions+ entry = pending_entries.sole+ reflag(entry, flag)+ assert entry.reload.entryable.pending?++ import_with(transactions: [])+ result = process_transactions++ assert_equal 1, result[:pruned_pending]+ assert_not Entry.exists?(entry.id), "a #{flag.inspect}-flagged held entry missing from the fetch should be pruned"+ end+ end++ test "keeps a disappeared transaction whose stored flag is the string \"false\"" do+ import_with(transactions: [ held_transaction(id: "tx_h4", amount: "-8.00") ])+ process_transactions+ entry = pending_entries.sole+ reflag(entry, "false")++ import_with(transactions: [])+ result = process_transactions++ assert_equal 0, result[:pruned_pending]+ assert Entry.exists?(entry.id)+ end+private+ def reflag(entry, flag)+ transaction = entry.entryable+ transaction.update!(extra: transaction.extra.merge("up" => transaction.extra["up"].merge("pending" => flag)))+ end+def import_with(transactions:)provider = FakeUpProvider.new(transactions: transactions)UpItem::Importer.new(@up_item, up_provider: provider).import@@ -127,7 +163,7 @@ class UpItem::ImporterTest < ActiveSupport::TestCase@account.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'").where(source: "up")- .where("(transactions.extra -> 'up' ->> 'pending')::boolean = true")+ .where(Transaction.pending_sql("transactions", providers: %w[up]))enddef held_transaction(id:, amount:, date: "2026-01-15T00:00:00+11:00")diff --git a/test/support/portfolio_flow_test_helper.rb b/test/support/portfolio_flow_test_helper.rbnew file mode 100644index 0000000000..be3b6f394c--- /dev/null+++ b/test/support/portfolio_flow_test_helper.rb@@ -0,0 +1,120 @@+# Builders for the entry shapes providers actually write into investment+# accounts, so classifier and totals tests exercise real storage shapes+# rather than one idealised trade. Each builder names the provider whose+# storage shape it reproduces.+module PortfolioFlowTestHelper+ def create_portfolio_account(family, name: "Investment #{SecureRandom.hex(3)}", balance: 1000, cash_balance: 0, currency: "USD", accountable: Investment.new)+ family.accounts.create!(+ name: name,+ balance: balance,+ cash_balance: cash_balance,+ currency: currency,+ accountable: accountable+ )+ end++ def create_portfolio_security(ticker: "T#{SecureRandom.hex(6)}")+ Security.create!(ticker: ticker, name: "Test #{ticker}")+ end++ # Manual buy/sell (Trade::CreateForm) and provider trades. The manual form+ # folds the fee into the entry amount; pass `fee_in_amount: false` for the+ # Kraken / Binance-spot shape whose amount excludes it.+ def create_portfolio_trade(account:, security: create_portfolio_security, qty:, price:, fee: 0, label: nil, date: Date.current, fee_in_amount: true, excluded: false)+ label ||= qty.negative? ? "Sell" : "Buy"+ amount = qty.to_d * price.to_d+ amount += fee.to_d if fee_in_amount++ account.entries.create!(+ name: "#{label} #{security.ticker}",+ date: date,+ amount: amount,+ currency: account.currency,+ excluded: excluded,+ entryable: Trade.new(+ qty: qty,+ price: price,+ fee: fee,+ currency: account.currency,+ security: security,+ investment_activity_label: label+ )+ )+ end++ # Trade::CreateForm#create_income_trade: qty 0, price 0, negative amount.+ def create_income_trade(account:, label:, amount:, security: create_portfolio_security, date: Date.current)+ account.entries.create!(+ name: "#{label}: #{security.ticker}",+ date: date,+ amount: -amount.to_d.abs,+ currency: account.currency,+ entryable: Trade.new(qty: 0, price: 0, fee: 0, currency: account.currency, security: security, investment_activity_label: label)+ )+ end++ # Trading212 / IBKR / Questrade: a Transaction with the label and the+ # security id in extra. Negative amount = cash in.+ def create_income_transaction(account:, label:, amount:, security: create_portfolio_security, date: Date.current, extra_shape: :flat)+ extra = case extra_shape+ when :flat then { "security_id" => security.id }+ when :nested then { "security" => { "id" => security.id } }+ else {}+ end++ account.entries.create!(+ name: "#{label} from #{security.ticker}",+ date: date,+ amount: -amount.to_d.abs,+ currency: account.currency,+ entryable: Transaction.new(investment_activity_label: label, extra: extra)+ )+ end++ # PlaidAccount::Investments::TransactionsProcessor routes a cash dividend+ # through the trade path with quantity 0, so the amount is 0 * price = 0.+ def create_plaid_dividend_trade(account:, security: create_portfolio_security, price: 100, date: Date.current)+ account.entries.create!(+ name: "Dividend #{security.ticker}",+ date: date,+ amount: 0,+ currency: account.currency,+ entryable: Trade.new(qty: 0, price: price, fee: 0, currency: account.currency, security: security, investment_activity_label: "Dividend")+ )+ end++ def create_labelled_transaction(account:, label:, amount:, kind: "standard", date: Date.current, extra: {}, excluded: false)+ account.entries.create!(+ name: "#{label || 'Transaction'} #{SecureRandom.hex(2)}",+ date: date,+ amount: amount,+ currency: account.currency,+ excluded: excluded,+ entryable: Transaction.new(investment_activity_label: label, kind: kind, extra: extra)+ )+ end++ # A linked Transfer exactly as Transfer::Creator writes it: the outflow leg+ # is investment_contribution when the destination is an investment account,+ # the inflow leg is funds_movement, and optional fee legs point back at the+ # transfer through transfer_id.+ def create_linked_transfer(family:, from:, to:, amount:, date: Date.current, source_fee_amount: nil)+ Transfer::Creator.new(+ family: family,+ source_account_id: from.id,+ destination_account_id: to.id,+ date: date,+ amount: amount,+ source_fee_amount: source_fee_amount+ ).create+ end++ # A position moved between two accounts: no Transfer row, two Transfer+ # trades with opposite quantities on the same security and date.+ def create_security_transfer(security:, from:, to:, qty:, price:, date: Date.current)+ [+ create_portfolio_trade(account: from, security: security, qty: -qty, price: price, label: "Transfer", date: date),+ create_portfolio_trade(account: to, security: security, qty: qty, price: price, label: "Transfer", date: date)+ ]+ end+enddiff --git a/test/support/rake_task_test_helper.rb b/test/support/rake_task_test_helper.rbnew file mode 100644index 0000000000..30bf6f2fc8--- /dev/null+++ b/test/support/rake_task_test_helper.rb@@ -0,0 +1,33 @@+# frozen_string_literal: true++# How a new test should make a rake task available.+#+# `Rails.application.load_tasks` re-reads every file in lib/tasks. Loading a+# rake file whose tasks are already defined does not replace them: Rake appends+# another action, so a task loaded twice runs its body twice per `invoke`. That+# stays invisible while the task is idempotent and the assertions only match+# patterns in its output, which a doubled run does not change.+#+# `load_tasks` also enhances the `environment` task, which reloads .env over the+# environment the test run was started with.+#+# So: load one file, only if its task is not already defined, and clear the+# `environment` prerequisite, which is already satisfied inside a test process+# and is not defined at all unless something loaded every task.+module RakeTaskTestHelper+ # Call at file scope, after `require "test_helper"`.+ def self.load_task(task_name, rake_file)+ return if Rake::Task.task_defined?(task_name)++ load Rails.root.join("lib/tasks/#{rake_file}.rake")+ end++ # Call from `setup`. Re-enabling matters because an invoked task stays+ # invoked; clearing prerequisites drops `:environment`.+ def self.prepare(*task_names)+ task_names.flatten.each do |name|+ Rake::Task[name].clear_prerequisites+ Rake::Task[name].reenable+ end+ end+enddiff --git a/test/test_helper.rb b/test/test_helper.rbindex 969cfcce82..d60dc5ad85 100644--- a/test/test_helper.rb+++ b/test/test_helper.rb@@ -27,6 +27,7 @@ require "rack/test"require "tempfile"require "uri"require Rails.root.join("test/support/sql_query_capture").to_s+require Rails.root.join("test/support/rake_task_test_helper").to_sVCR.configure do |config|config.cassette_library_dir = "test/vcr_cassettes"