The personal finance app for everyone (by everyone)
Ruby
Match bills to charges that were split before the matcher ran (#5134)
David Gilecb806521abf
diff --git a/app/controllers/recurring_allocations_controller.rb b/app/controllers/recurring_allocations_controller.rbindex c6d67e5998..8c2cc800c4 100644--- a/app/controllers/recurring_allocations_controller.rb+++ b/app/controllers/recurring_allocations_controller.rb@@ -113,11 +113,12 @@ class RecurringAllocationsController < ApplicationControllerdef allocation_error_message(error)case error- # The two subclasses before OverAllocationError, which would otherwise- # claim them.+ # The subclasses before OverAllocationError, which would otherwise claim+ # them.when RecurringTransaction::Allocator::AlreadyAllocatedError,ActiveRecord::RecordNotUnique then t("recurring_allocations.already_allocated")when RecurringTransaction::Allocator::EntryExhaustedError then t("recurring_allocations.entry_exhausted")+ when RecurringTransaction::Allocator::SplitCounterpartAllocatedError then t("recurring_allocations.split_counterpart_allocated")when RecurringTransaction::Allocator::OverAllocationError then t("recurring_allocations.over_allocation")when RecurringTransaction::Allocator::MissingRateError then t("recurring_allocations.missing_rate")else t("recurring_allocations.invalid")diff --git a/app/controllers/recurring_occurrences_controller.rb b/app/controllers/recurring_occurrences_controller.rbindex 703e129726..5ee6802d34 100644--- a/app/controllers/recurring_occurrences_controller.rb+++ b/app/controllers/recurring_occurrences_controller.rb@@ -144,7 +144,7 @@ class RecurringOccurrencesController < ApplicationControllerscope = candidate_scope.where(date: candidate_window)- .where(excluded: false)+ .not_excluded_or_split_parent.where.not(id: RecurringMatchRejection.where(recurring_transaction: series).select(:entry_id))# preload, not includes: entryable is polymorphic so it can never be# joined, and naming it keeps the raw transactions join above out ofdiff --git a/app/models/entry.rb b/app/models/entry.rbindex 455e53ae66..52a54cf574 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -145,13 +145,17 @@ class Entry < ApplicationRecordSQL}- scope :excluding_split_parents, -> {- where(<<~SQL.squish)- NOT EXISTS (- SELECT 1 FROM entries ce WHERE ce.parent_entry_id = entries.id- )- SQL- }+ SPLIT_PARENT_SQL = "EXISTS (SELECT 1 FROM entries ce WHERE ce.parent_entry_id = entries.id)".freeze+ private_constant :SPLIT_PARENT_SQL++ scope :excluding_split_parents, -> { where("NOT #{SPLIT_PARENT_SQL}") }++ # Non-excluded entries plus split parents. split! excludes the parent so its+ # children are not counted twice, but the parent is still the charge the bank+ # made, so anything matching real payments (bills) keeps it. Every other+ # excluded entry is dropped: user exclusions and system ones alike (stale+ # pending entries, pending duplicates of a posted transaction).+ scope :not_excluded_or_split_parent, -> { where("entries.excluded = FALSE OR #{SPLIT_PARENT_SQL}") }# Balance updates: reconciliation valuations. On linked accounts most of them# are the provider's daily balance, kept as a waypoint by@@ -630,6 +634,12 @@ class Entry < ApplicationRecordparent_entry_id.present?end+ # The other side of a split: a child's parent, or a parent's children. Both+ # sides are the same money. Siblings are not: each child is its own part.+ def split_counterparts+ self.class.where(id: parent_entry_id).or(self.class.where(parent_entry_id: id))+ end+# Splits this entry into child entries. Marks parent as excluded.## @param splits [Array<Hash>] array of { name:, amount:, category_id:, merchant_id:, tag_ids:, excluded: } hashes.diff --git a/app/models/recurring_transaction/allocator.rb b/app/models/recurring_transaction/allocator.rbindex 5a32a3ef14..54504b271f 100644--- a/app/models/recurring_transaction/allocator.rb+++ b/app/models/recurring_transaction/allocator.rb@@ -22,6 +22,9 @@ class RecurringTransaction# holding the entry.class EntryExhaustedError < OverAllocationError; endclass AlreadyAllocatedError < OverAllocationError; end+ # The entry is one side of a split (the parent, or one of its children)+ # and the other side already pays a bill. Both sides are the same money.+ class SplitCounterpartAllocatedError < OverAllocationError; endclass MissingRateError < StandardError; end# Postgres keeps single-key and two-key advisory locks in separate spaces,@@ -42,24 +45,57 @@ class RecurringTransaction)end+ # Keyed on the split root, so a split parent and its children share one+ # lock: their counterpart checks then see each other's committed writes.def self.entry_lock_id(entry)- Digest::MD5.hexdigest(entry.id.to_s).to_i(16) % (2**31)+ Digest::MD5.hexdigest((entry.parent_entry_id || entry.id).to_s).to_i(16) % (2**31)+ end++ # Allocations that count toward an entry's capacity: everything except+ # tombstones from ended series (a deleted or dismissed bill). Counting+ # those would permanently consume the entry and block re-use on a new+ # bill (see #3592). Defined once so the capacity checks stay in sync.+ def self.active_allocations(allocations = RecurringAllocation.all)+ allocations.joins(recurring_occurrence: :recurring_transaction)+ .where.not(recurring_transactions: { status: "ended" })end# What guard_entry_capacity! would leave of each entry for another bill,# for many entries in one query. Entries no bill uses yet are omitted.# Pass a narrower allocations scope to count only the bills a viewer can# see; the guard itself always counts every allocation.+ #+ # The query also reads the allocations of each entry's split counterparts+ # (see Entry#split_counterparts): once one side of a split pays a bill, the+ # other side has nothing left.def self.remaining_by_entry(entries, allocations: RecurringAllocation.all)by_id = entries.index_by(&:id)+ scope = active_allocations(allocations).joins(:entry)++ rows = scope.where(entry_id: by_id.keys + entries.filter_map(&:parent_entry_id))+ .or(scope.where(entries: { parent_entry_id: by_id.keys }))+ .group(:entry_id, "entries.parent_entry_id")+ .pluck(+ :entry_id,+ "entries.parent_entry_id",+ Arel.sql("SUM(COALESCE(source_amount, allocated_amount))"),+ Arel.sql("BOOL_OR(source_amount IS NULL)")+ )++ paying_ids = rows.map(&:first).to_set+ paying_parent_ids = rows.filter_map(&:second).to_set+ spent_by_counterpart = entries.select do |entry|+ paying_ids.include?(entry.parent_entry_id) || paying_parent_ids.include?(entry.id)+ end- allocations.where(entry_id: by_id.keys).group(:entry_id).pluck(- :entry_id,- Arel.sql("SUM(COALESCE(source_amount, allocated_amount))"),- Arel.sql("BOOL_OR(source_amount IS NULL)")- ).to_h do |entry_id, used, unmeasurable|- [ entry_id, unmeasurable ? 0 : [ by_id[entry_id].amount.abs - used, 0 ].max ]+ remaining = rows.each_with_object({}) do |(entry_id, _parent_id, used, unmeasurable), result|+ entry = by_id[entry_id]+ next unless entry++ result[entry_id] = unmeasurable ? 0 : [ entry.amount.abs - used, 0 ].maxend+ spent_by_counterpart.each { |entry| remaining[entry.id] = 0 }+ remainingenddef initialize(occurrence)@@ -345,15 +381,8 @@ class RecurringTransactionallocationend- # Allocations that count toward an entry's capacity: everything except- # tombstones from ended series (a deleted or dismissed bill). Counting- # those would permanently consume the entry and block re-use on a new- # bill (see #3592). Defined once so the capacity checks stay in sync.def active_allocations_for(entry)- RecurringAllocation- .where(entry: entry)- .joins(recurring_occurrence: :recurring_transaction)- .where.not(recurring_transactions: { status: "ended" })+ self.class.active_allocations.where(entry: entry)end# True once any allocation on this entry (excluding those from ended@@ -431,6 +460,14 @@ class RecurringTransaction# than one. Allocations from ended series are excluded throughout so a# deleted bill never blocks re-use of the same entry on a replacement.def guard_entry_capacity!(entry, source_amount)+ # A split parent and its children are the same money, so whichever+ # side pays a bill first (a suggestion included) takes the other side+ # out. Otherwise the parent could pay one bill and a child another,+ # counting more than the bank charged.+ if active_allocations_for(entry.split_counterparts).exists?+ raise SplitCounterpartAllocatedError, I18n.t("recurring_transactions.allocator.split_counterpart_allocated")+ end+if source_amount.nil? || unmeasurable_entry?(entry)return if active_allocations_for(entry).none?diff --git a/app/models/recurring_transaction/matcher.rb b/app/models/recurring_transaction/matcher.rbindex 7cee936aab..ad3f257e92 100644--- a/app/models/recurring_transaction/matcher.rb+++ b/app/models/recurring_transaction/matcher.rb@@ -114,10 +114,15 @@ class RecurringTransactionwritten = 0# Highest confidence claims first; each entry and occurrence is assigned- # at most once per run. The id tiebreak only makes equally confident+ # at most once per run. A split child whose parent is also a candidate+ # waits until every other candidate had its turn: the parent claims its+ # bill as if the split came after matching, and the Allocator then+ # refuses the child. The id tiebreak only makes equally confident# candidates resolve deterministically, since sort_by is not stable.+ candidate_entry_ids = candidates.to_set { |candidate| candidate.entry.id }ordered = candidates.sort_by do |candidate|- [ -candidate.confidence, candidate.occurrence.id, candidate.entry.id ]+ parent_competes = candidate_entry_ids.include?(candidate.entry.parent_entry_id)+ [ parent_competes ? 1 : 0, -candidate.confidence, candidate.occurrence.id, candidate.entry.id ]endordered.each do |candidate|@@ -128,7 +133,8 @@ class RecurringTransactionnext if tier.nil?next if tier == :high && !suggest- write_allocation(candidate, tier)+ next unless write_allocation(candidate, tier)+taken_entries << candidate.entry.idtaken_occurrences << candidate.occurrence.idwritten += 1@@ -164,21 +170,26 @@ class RecurringTransactionrunner_up.nil? || candidate.confidence - runner_up.confidence >= AMBIGUITY_MARGINend+ # False when the occurrence should stay open to the next candidate.def write_allocation(candidate, tier)- occurrence = candidate.occurrence- entry = candidate.entry-- Allocator.new(occurrence).allocate_matched!(- entry: entry,+ Allocator.new(candidate.occurrence).allocate_matched!(+ entry: candidate.entry,state: tier == :exact ? "confirmed" : "suggested",confidence: candidate.confidence,signals: candidate.signals)+ true+ rescue Allocator::SplitCounterpartAllocatedError+ # The other side of this split already pays a bill, so this entry is+ # not money the occurrence can have. Another charge still can.+ falserescue ActiveRecord::RecordNotUnique# Already allocated (a previous run wrote it); nothing to do.+ truerescue Allocator::OverAllocationError# Another occurrence already claimed the entry's capacity. Skip the# candidate rather than aborting the run.+ trueend# The hard filters depend on the series and the entry, not the individual@@ -252,7 +263,8 @@ class RecurringTransaction# One query over the envelope of every open occurrence's window.# Transfer legs are left out, except the outflow side of a transfer that- # a recurring transfer series could be paid by.+ # a recurring transfer series could be paid by. A split charge stays in:+ # its parent is excluded by the split, not by the user, and is the payment.def entries_for(occurrences, include_closed_window)window_min = occurrences.map { |occurrence| window_for(occurrence).begin }.minwindow_max = occurrences.map { |occurrence| window_for(occurrence).end }.max@@ -264,7 +276,7 @@ class RecurringTransactionfamily.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id").where(entryable_type: "Transaction")- .where(excluded: false)+ .not_excluded_or_split_parent.where(date: window_min..window_max).where("transactions.kind NOT IN (?) OR transactions.id IN (?)", Transaction::TRANSFER_KINDS, transfer_destinations.keys).where.not(id: RecurringAllocation.where.not(entry_id: nil).where(state: "confirmed").select(:entry_id))diff --git a/config/locales/models/recurring_transaction/en.yml b/config/locales/models/recurring_transaction/en.ymlindex a186c72ff6..77befefc41 100644--- a/config/locales/models/recurring_transaction/en.yml+++ b/config/locales/models/recurring_transaction/en.yml@@ -6,6 +6,7 @@ en:unmeasurable: "this transaction carries an allocation that cannot be converted to %{currency}, so what is left of it cannot be measured. Add an exchange rate for %{date} or remove the existing payment first"over_allocated: "allocating %{amount} exceeds the transaction's remaining %{capacity} %{currency}"entry_exhausted: "this transaction's full amount is already applied to other payments due"+ split_counterpart_allocated: "this transaction is split, and the original charge or one of its parts is already applied to a bill"already_allocated: "this transaction is already applied to this bill"exceeds_remaining: "%{amount} exceeds the %{remaining} remaining on this cycle"activerecord:diff --git a/config/locales/models/recurring_transaction/es.yml b/config/locales/models/recurring_transaction/es.ymlindex 4d8ac2213e..96c75e35c2 100644--- a/config/locales/models/recurring_transaction/es.yml+++ b/config/locales/models/recurring_transaction/es.yml@@ -6,6 +6,7 @@ es:unmeasurable: esta transacción tiene una asignación que no se puede convertir a %{currency}, así que no se puede medir lo que queda de ella. Añade un tipo de cambio para %{date} o quita primero el pago existenteover_allocated: asignar %{amount} supera lo que queda de la transacción, %{capacity} %{currency}entry_exhausted: el importe completo de esta transacción ya está aplicado a otros pagos pendientes+ split_counterpart_allocated: esta transacción está dividida y el cargo original o una de sus partes ya paga un reciboalready_allocated: esta transacción ya está aplicada a este reciboexceeds_remaining: "%{amount} supera los %{remaining} pendientes de este ciclo"activerecord:diff --git a/config/locales/views/recurring_allocations/en.yml b/config/locales/views/recurring_allocations/en.ymlindex 60cf48a72a..d516d9f2b1 100644--- a/config/locales/views/recurring_allocations/en.yml+++ b/config/locales/views/recurring_allocations/en.yml@@ -4,6 +4,7 @@ en:over_allocation: That would allocate more than the transaction's amountmissing_rate: No exchange rate available; enter the amount explicitlyalready_allocated: That transaction is already applied to this bill+ split_counterpart_allocated: That transaction is split, and the original charge or one of its parts is already applied to a billentry_exhausted: That transaction's full amount is already applied to other payments dueinvalid: The payment could not be recordedcreate:diff --git a/config/locales/views/recurring_allocations/es.yml b/config/locales/views/recurring_allocations/es.ymlindex cc08624dbe..0261caeb73 100644--- a/config/locales/views/recurring_allocations/es.yml+++ b/config/locales/views/recurring_allocations/es.yml@@ -4,6 +4,7 @@ es:over_allocation: Eso asignaría más que el importe de la transacciónmissing_rate: No hay tipo de cambio disponible; introduce el importe a manoalready_allocated: Esa transacción ya está aplicada a este recibo+ split_counterpart_allocated: Esa transacción está dividida y el cargo original o una de sus partes ya paga un reciboentry_exhausted: El importe completo de esa transacción ya está aplicado a otros pagos pendientesinvalid: No se ha podido registrar el pagocreate:diff --git a/test/controllers/recurring_allocations_controller_test.rb b/test/controllers/recurring_allocations_controller_test.rbindex b548f65f13..b5c60074f7 100644--- a/test/controllers/recurring_allocations_controller_test.rb+++ b/test/controllers/recurring_allocations_controller_test.rb@@ -89,6 +89,25 @@ class RecurringAllocationsControllerTest < ActionDispatch::IntegrationTest"a nil-cast date would have silently defaulted the payment to today"end+ test "paying with a part of a split whose original charge already pays a bill says why" do+ parent = accounts(:credit_card).entries.create!(+ date: Date.current, amount: 95, currency: "USD", name: "Card Annual Fee", entryable: Transaction.new+ )+ child, = parent.split!([ { name: "Fee", amount: 60 }, { name: "Insurance", amount: 35 } ])+ post recurring_occurrence_allocations_url(@occurrence), params: { entry_id: parent.id }++ other = @family.recurring_transactions.create!(+ name: "Card Insurance", account: accounts(:credit_card), amount: 35,+ currency: "USD", expected_day_of_month: Date.current.day,+ anchor_date: Date.current, last_occurrence_date: Date.current,+ next_expected_date: Date.current, status: "active", manual: true+ ).recurring_occurrences.order(:due_on).first+ post recurring_occurrence_allocations_url(other), params: { entry_id: child.id }++ assert_equal I18n.t("recurring_allocations.split_counterpart_allocated"), flash[:alert]+ assert_empty other.reload.allocations+ end+test "allocation feedback is available in German" doexpected_translations = {"recurring_allocations.over_allocation" => "Damit würdest du mehr als den Transaktionsbetrag zuordnen.",diff --git a/test/controllers/recurring_occurrences_controller_test.rb b/test/controllers/recurring_occurrences_controller_test.rbindex 52785c3849..06fc0953b8 100644--- a/test/controllers/recurring_occurrences_controller_test.rb+++ b/test/controllers/recurring_occurrences_controller_test.rb@@ -272,6 +272,30 @@ class RecurringOccurrencesControllerTest < ActionDispatch::IntegrationTestassert_empty @controller.view_assigns["ranked_candidates"]end+ # The picker ranks with the matcher, so it must offer what the matcher would+ # link: a split charge's parent is excluded by the split, not by the user.+ test "a split charge is still offered, an excluded one is not" do+ series = @family.recurring_transactions.create!(+ name: "MORTGAGE", account: accounts(:depository), amount: 1000, currency: "USD",+ expected_day_of_month: Date.current.day, anchor_date: Date.current,+ last_occurrence_date: Date.current, next_expected_date: Date.current,+ status: "active", manual: true+ )+ occurrence = series.recurring_occurrences.order(:due_on).first+ split, excluded = 2.times.map do+ accounts(:depository).entries.create!(+ date: occurrence.due_on, amount: 1000, currency: "USD",+ name: "MORTGAGE", entryable: Transaction.new+ )+ end+ split.split!([ { name: "Interest", amount: 400 }, { name: "Principal", amount: 600 } ])+ excluded.update!(excluded: true)++ get recurring_occurrence_url(occurrence), headers: { "Turbo-Frame" => "drawer" }++ assert_equal [ split.id ], @controller.view_assigns["ranked_candidates"].map { |candidate, _| candidate.id }+ end+# One transaction can legitimately pay more than one bill, which is why the# Allocator guards capacity at write time rather than at read time. Excluding# every entry that already has a confirmed allocation would have quietlydiff --git a/test/models/recurring_transaction/allocator_test.rb b/test/models/recurring_transaction/allocator_test.rbindex 1cdc6f3455..5371764756 100644--- a/test/models/recurring_transaction/allocator_test.rb+++ b/test/models/recurring_transaction/allocator_test.rb@@ -329,13 +329,7 @@ class RecurringTransaction::AllocatorTest < ActiveSupport::TestCasetest "one entry can pay several occurrences but never more than itself" dolump = entry_for(1612.50)- # A mid-month date the day-29 series never generates, so this manual- # row can never collide with the generator's rows regardless of what- # Date.current is when the suite runs.- free_date = (Date.current + 2.months).beginning_of_month + 9- september = @rent.recurring_occurrences.create!(- family: @family, original_due_on: free_date, due_on: free_date, currency: "USD"- )+ september = free_occurrence@allocator.allocate!(entry: lump, amount: 1000)Allocator.new(september).allocate!(entry: lump, amount: 612.50)@@ -348,10 +342,7 @@ class RecurringTransaction::AllocatorTest < ActiveSupport::TestCasetest "an entry another occurrence already uses up is refused as exhausted" dolump = entry_for(500)@allocator.allocate!(entry: lump)- free_date = (Date.current + 2.months).beginning_of_month + 9- september = @rent.recurring_occurrences.create!(- family: @family, original_due_on: free_date, due_on: free_date, currency: "USD"- )+ september = free_occurrence# With no amount the default is what the entry has left, which is zero.# That used to reach the allocation's "greater than 0" validation instead.@@ -383,6 +374,68 @@ class RecurringTransaction::AllocatorTest < ActiveSupport::TestCaseassert_equal({ partly.id => 300, fully.id => 0 }, remaining)end+ # A split parent and its children are the same money: whichever side pays a+ # bill first, the other side is spent, suggestions included.+ test "a split parent and its children never both pay" do+ parent = entry_for(1612.50)+ child, = parent.split!([ { name: "Rent", amount: 1000 }, { name: "Parking", amount: 612.50 } ])+ september = free_occurrence++ @allocator.allocate!(entry: parent, amount: 1000)+ assert_raises(Allocator::SplitCounterpartAllocatedError) { Allocator.new(september).allocate!(entry: child) }++ @occurrence.allocations.destroy_all+ Allocator.new(september).allocate_matched!(entry: child, state: "suggested", confidence: 0.7, signals: {})+ assert_raises(Allocator::SplitCounterpartAllocatedError) { @allocator.allocate!(entry: parent) }+ assert_empty @occurrence.allocations+ end++ test "the parts of a split can each pay a bill" do+ rent, parking = entry_for(1612.50).split!([ { name: "Rent", amount: 1000 }, { name: "Parking", amount: 612.50 } ])++ @allocator.allocate!(entry: rent)+ Allocator.new(free_occurrence).allocate!(entry: parking)++ assert_equal 2, RecurringAllocation.where(entry: [ rent, parking ]).count+ end++ test "remaining_by_entry reports the other side of a paying split as used up, in one query" do+ parent = entry_for(1612.50)+ rent, parking = parent.split!([ { name: "Rent", amount: 1000 }, { name: "Parking", amount: 612.50 } ])+ @allocator.allocate!(entry: rent, amount: 400)++ remaining = assert_queries_count(1) { Allocator.remaining_by_entry([ parent, rent, parking ]) }++ assert_equal({ parent.id => 0, rent.id => 600 }, remaining)++ other_parent = entry_for(500)+ other_child, = other_parent.split!([ { name: "A", amount: 200 }, { name: "B", amount: 300 } ])+ @allocator.allocate!(entry: other_parent, amount: 100)++ assert_equal({ other_child.id => 0 }, Allocator.remaining_by_entry([ other_child ]))+ end++ # The guard ignores ended series, so the drawer must too: a deleted bill+ # that a child paid leaves the parent free.+ test "remaining_by_entry ignores what an ended bill took, on the entry or its counterpart" do+ parent = entry_for(1612.50)+ rent, = parent.split!([ { name: "Rent", amount: 1000 }, { name: "Parking", amount: 612.50 } ])+ @allocator.allocate!(entry: rent, amount: 400)+ @rent.update!(status: "ended")++ assert_empty Allocator.remaining_by_entry([ parent, rent ])+ end++ # Different locks would let a parent and a child pass their counterpart+ # checks at once, each blind to the other's uncommitted allocation.+ test "a split parent and its children share one entry lock" do+ parent = entry_for(1612.50)+ children = parent.split!([ { name: "Rent", amount: 1000 }, { name: "Parking", amount: 612.50 } ])++ assert_equal [ Allocator.entry_lock_id(parent) ], children.map { |child| Allocator.entry_lock_id(child) }.uniq+ assert_not_equal Allocator.entry_lock_id(parent), Allocator.entry_lock_id(entry_for(10))+ end+test "remaining_by_entry treats an unmeasurable entry as used up" doExchangeRate.delete_allentry = foreign_entry(amount: 100, currency: "EUR")@@ -435,10 +488,7 @@ class RecurringTransaction::AllocatorTest < ActiveSupport::TestCase)@allocator.allocate!(entry: foreign, amount: 55)- free_date = (Date.current + 2.months).beginning_of_month + 9- other = @rent.recurring_occurrences.create!(- family: @family, original_due_on: free_date, due_on: free_date, currency: "USD"- )+ other = free_occurrence# 50 EUR of the entry is spoken for, so the default is the 50 EUR# leftover converted, not the full 100 the old default reached for.allocation = Allocator.new(other).allocate!(entry: foreign)@@ -672,4 +722,14 @@ class RecurringTransaction::AllocatorTest < ActiveSupport::TestCaseentryable: Transaction.new)end++ # A mid-month date the day-29 series never generates, so this manual+ # row can never collide with the generator's rows regardless of what+ # Date.current is when the suite runs.+ def free_occurrence+ free_date = (Date.current + 2.months).beginning_of_month + 9+ @rent.recurring_occurrences.create!(+ family: @family, original_due_on: free_date, due_on: free_date, currency: "USD"+ )+ endenddiff --git a/test/models/recurring_transaction/matcher_test.rb b/test/models/recurring_transaction/matcher_test.rbindex 75a68c909d..563da3b4dc 100644--- a/test/models/recurring_transaction/matcher_test.rb+++ b/test/models/recurring_transaction/matcher_test.rb@@ -31,7 +31,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "a merchant charge near the expected amount auto-links and settles the bill" do# The mission's own example: Comcast expected at $119.99, charged $121.74.series = create_series(name: nil, merchant: merchants(:netflix), amount: 119.99, day_offset: 2)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)entry = create_entry(amount: 121.74, date: Date.current, merchant: merchants(:netflix))assert_equal 1, @matcher.run!@@ -49,7 +49,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCase# A week overdue, paid today at the edge of the amount band: plausible,# not certain.series = create_series(name: "CITY WATER", amount: 80, day_offset: -7)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)create_entry(amount: 85.50, date: Date.current, name: "CITY WATER")@matcher.run!@@ -66,15 +66,15 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCase@matcher.run!- states = (twin_a.recurring_occurrences.order(:due_on).first.allocations.to_a +- twin_b.recurring_occurrences.order(:due_on).first.allocations.to_a).map(&:state)+ states = (first_occurrence(twin_a).allocations.to_a ++ first_occurrence(twin_b).allocations.to_a).map(&:state)assert_equal [ "suggested" ], states.uniqassert_equal 1, states.size, "one entry is proposed once, to the better candidate"endtest "a rejected pair is never suggested again" doseries = create_series(name: "CITY WATER", amount: 80, day_offset: -7)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)create_entry(amount: 85.50, date: Date.current, name: "CITY WATER")@matcher.run!@@ -87,7 +87,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "a pending charge is suggested at most, never auto-linked" doseries = create_series(name: nil, merchant: merchants(:netflix), amount: 119.99, day_offset: 1)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)create_entry(amount: 119.99, date: Date.current, merchant: merchants(:netflix),extra: { "simplefin" => { "pending" => true } })@@ -96,6 +96,104 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCaseassert occurrence.allocations.sole.allocation_suggested?end+ # Splitting a charge excludes the parent so its children are not counted+ # twice, but the parent is still the payment the bank made. Split before the+ # matcher ran, the bill used to stay overdue although it had been paid.+ test "a charge split before matching still settles the bill" do+ series = create_series(name: "MORTGAGE", amount: 1000, day_offset: 0)+ occurrence = first_occurrence(series)+ entry = create_entry(amount: 1000, date: Date.current, name: "MORTGAGE")+ entry.split!([ { name: "Interest", amount: 400 }, { name: "Principal", amount: 600 } ])++ assert_equal 1, @matcher.run!++ allocation = occurrence.allocations.sole+ assert allocation.allocation_confirmed?+ assert_equal entry.id, allocation.entry_id+ assert occurrence.reload.paid?+ end++ # The bank took the money whatever the user does with the parts, and the+ # matcher already settled the bill this way when it ran before the split.+ test "a split charge whose children are all excluded still settles the bill" do+ series = create_series(name: "MORTGAGE", amount: 1000, day_offset: 0)+ occurrence = first_occurrence(series)+ entry = create_entry(amount: 1000, date: Date.current, name: "MORTGAGE")+ entry.split!([ { name: "Interest", amount: 400, excluded: "1" }, { name: "Principal", amount: 600, excluded: "1" } ])+ assert entry.child_entries.all?(&:excluded?)++ assert_equal 1, @matcher.run!++ assert_equal entry.id, occurrence.allocations.sole.entry_id+ assert occurrence.reload.paid?+ end++ # A split parent and its children are the same money. With two bills from+ # one merchant, the parent paying one and a child paying the other would+ # count 20.99 of bills against 15.99 spent.+ test "a charge split before matching pays one bill, never one through the parent and another through a child" do+ subscription = create_series(merchant: merchants(:netflix), amount: 15.99, day_offset: 0)+ add_on = create_series(merchant: merchants(:netflix), amount: 5, day_offset: 0, dedup_scope: "add-on")+ entry = create_entry(amount: 15.99, date: Date.current, merchant: merchants(:netflix))+ entry.split!([ { name: "Add-on", amount: 5 }, { name: "Plan", amount: 10.99 } ])++ @matcher.run!++ assert_equal [ entry.id ], first_occurrence(subscription).allocations.map(&:entry_id),+ "the parent is the bank charge, so on a tie it pays before a child"+ assert_empty first_occurrence(add_on).allocations+ end++ test "a charge split after matching keeps paying only the bill it already paid" do+ subscription = create_series(merchant: merchants(:netflix), amount: 15.99, day_offset: 0)+ add_on = create_series(merchant: merchants(:netflix), amount: 5, day_offset: 0, dedup_scope: "add-on")+ entry = create_entry(amount: 15.99, date: Date.current, merchant: merchants(:netflix))++ @matcher.run!+ entry.split!([ { name: "Add-on", amount: 5 }, { name: "Plan", amount: 10.99 } ])+ Matcher.new(@family).run!++ assert_equal [ entry.id ], first_occurrence(subscription).allocations.map(&:entry_id)+ assert_empty first_occurrence(add_on).allocations+ end++ # The subscription is 16.00, so the parent scores below the exact 5.00 child.+ # Confidence alone would hand the charge to the add-on, where matching+ # before the split pays the subscription.+ test "a split parent pays its bill even when a child outscores it" do+ subscription = create_series(merchant: merchants(:netflix), amount: 16, day_offset: 0)+ add_on = create_series(merchant: merchants(:netflix), amount: 5, day_offset: 0, dedup_scope: "add-on")+ entry = create_entry(amount: 15.99, date: Date.current, merchant: merchants(:netflix))+ entry.split!([ { name: "Add-on", amount: 5 }, { name: "Plan", amount: 10.99 } ])++ @matcher.run!++ assert_equal [ entry.id ], first_occurrence(subscription).allocations.map(&:entry_id)+ assert_empty first_occurrence(add_on).allocations+ end++ # Siblings are different money: each part can pay its own bill.+ test "the parts of a split charge can each pay their own bill" do+ subscription = create_series(merchant: merchants(:netflix), amount: 15.99, day_offset: 0)+ add_on = create_series(merchant: merchants(:netflix), amount: 5, day_offset: 0, dedup_scope: "add-on")+ entry = create_entry(amount: 20.99, date: Date.current, merchant: merchants(:netflix))+ plan, extra = entry.split!([ { name: "Plan", amount: 15.99 }, { name: "Add-on", amount: 5 } ])++ assert_equal 2, @matcher.run!++ assert_equal [ plan.id ], first_occurrence(subscription).allocations.map(&:entry_id)+ assert_equal [ extra.id ], first_occurrence(add_on).allocations.map(&:entry_id)+ end++ test "a charge the user excluded never settles a bill" do+ series = create_series(name: "MORTGAGE", amount: 1000, day_offset: 0)+ occurrence = first_occurrence(series)+ create_entry(amount: 1000, date: Date.current, name: "MORTGAGE").update!(excluded: true)++ assert_equal 0, @matcher.run!+ assert_empty occurrence.allocations+ end+# The payment review queue is where suggestions land, and income review has# no home there: a paycheck is not a bill anyone needs to approve paying.test "an income series never suggests, while the same shape on a bill does" do@@ -106,15 +204,15 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCase@matcher.run!- assert_equal 0, income.recurring_occurrences.order(:due_on).first.allocations.count,+ assert_equal 0, first_occurrence(income).allocations.count,"a near-miss deposit must not queue income for payment review"- assert bill.recurring_occurrences.order(:due_on).first.allocations.sole.allocation_suggested?,+ assert first_occurrence(bill).allocations.sole.allocation_suggested?,"the identical near-miss on a bill still suggests"endtest "an exact income match still auto-links and closes the payday" doincome = create_series(name: "ACME PAYROLL", amount: -1840, day_offset: 0, bill_type: "income")- occurrence = income.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(income)create_entry(amount: -1840, date: Date.current, name: "ACME PAYROLL")assert_equal 1, @matcher.run!@@ -137,7 +235,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "an overdue occurrence stays matchable, and a very late payment queues for review" doseries = create_series(name: "OLD RENT", amount: 500, day_offset: -20)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)assert_equal :overdue, occurrence.derived_statecreate_entry(amount: 500, date: Date.current, name: "OLD RENT")@@ -177,7 +275,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCase# the window of an overdue leftover runs to today, paused or not.test "a late payment still matches a paused bill's overdue leftover" doseries = create_series(name: "POWER CO", amount: 60, day_offset: -20)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)series.mark_inactive!assert_not occurrence.overdue?entry = create_entry(amount: 60, date: Date.current, name: "POWER CO")@@ -195,13 +293,13 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCase@matcher.run_backfill!- assert_equal 0, series.recurring_occurrences.order(:due_on).first.allocations.count- assert exact_series.recurring_occurrences.order(:due_on).first.allocations.sole.allocation_confirmed?+ assert_equal 0, first_occurrence(series).allocations.count+ assert first_occurrence(exact_series).allocations.sole.allocation_confirmed?endtest "repair re-attaches an allocation whose entry was replaced under it" doseries = create_series(name: "POWER CO", amount: 60, day_offset: 2)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)original = create_entry(amount: 60, date: Date.current, name: "POWER CO")@matcher.run!allocation = occurrence.allocations.sole@@ -217,7 +315,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "repair re-attaches a recurring transfer's payment by its account pair, not its name" doseries = create_series(name: "Payment to Loan", amount: 500, day_offset: 0, destination: accounts(:loan))- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)original = create_transfer(amount: 500, date: Date.current, to: accounts(:loan), name: "LOAN DD 1234")@matcher.run!allocation = occurrence.allocations.sole@@ -246,7 +344,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "manually attaching an alien-named entry teaches an alias" doseries = create_series(name: "Watson Property", amount: 2150, day_offset: 5)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)entry = create_entry(amount: 2150, date: Date.current + 4, name: "WPM LLC WEB PMT")RecurringTransaction::Allocator.new(occurrence).allocate!(entry: entry)@@ -256,13 +354,13 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "a single out-of-band settlement widens the learned tolerance; a partial teaches nothing" doseries = create_series(name: "POWER CO", amount: 100, day_offset: 5)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)settlement = create_entry(amount: 118, date: Date.current + 4, name: "POWER CO")RecurringTransaction::Allocator.new(occurrence).allocate!(entry: settlement)assert_in_delta 18.0, series.reload.matcher_hints["learned_tolerance_pct"], 0.1rent = create_series(name: "BIG RENT", amount: 2150, day_offset: 5)- rent_occurrence = rent.recurring_occurrences.order(:due_on).first+ rent_occurrence = first_occurrence(rent)partial = create_entry(amount: 537.50, date: Date.current + 4, name: "BIG RENT")RecurringTransaction::Allocator.new(rent_occurrence).allocate!(entry: partial)@@ -272,7 +370,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "confirming a suggestion settles the bill" doseries = create_series(name: "CITY WATER", amount: 80, day_offset: -7)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)create_entry(amount: 85.50, date: Date.current, name: "CITY WATER")@matcher.run!@@ -288,7 +386,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCase# a 7-Eleven bill.test "explain returns the signals behind a strong match" doseries = create_series(name: nil, merchant: merchants(:netflix), amount: 15.99, day_offset: 0)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)entry = create_entry(amount: 15.99, date: occurrence.due_on, merchant: merchants(:netflix))explanation = @matcher.explain(occurrence, entry)@@ -302,7 +400,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "explain refuses an entry from another merchant outright" doseries = create_series(name: nil, merchant: merchants(:netflix), amount: 15.99, day_offset: 0)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)other = create_entry(amount: 15.99, date: occurrence.due_on, merchant: merchants(:amazon))assert_nil @matcher.explain(occurrence, other),@@ -311,7 +409,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "explain refuses an entry outside the date window" doseries = create_series(name: "CITY WATER", amount: 80, day_offset: 0)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)entry = create_entry(amount: 80, date: occurrence.due_on - 60, name: "CITY WATER")assert_nil @matcher.explain(occurrence, entry)@@ -319,7 +417,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "explain refuses an amount outside the tolerance band" doseries = create_series(name: "CITY WATER", amount: 80, day_offset: 0)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)entry = create_entry(amount: 400, date: occurrence.due_on, name: "CITY WATER")assert_nil @matcher.explain(occurrence, entry),@@ -331,7 +429,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCase# never matched a reposted paycheck, so orphaned income stayed orphaned.test "repair finds a reposted income entry by its signed amount" doseries = create_series(name: "PAYCHECK CO", amount: -1840, day_offset: 0, bill_type: "income")- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)original = create_entry(amount: -1840, date: Date.current, name: "PAYCHECK CO")@matcher.run!allocation = occurrence.allocations.sole@@ -349,7 +447,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCase# bill's own repost, and attaching it reports the bill paid by a stranger.test "repair refuses a same-amount entry that is not the series' identity" doseries = create_series(name: "POWER CO", amount: 60, day_offset: 0)- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)original = create_entry(amount: 60, date: Date.current, name: "POWER CO")@matcher.run!allocation = occurrence.allocations.sole@@ -364,7 +462,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "a recurring transfer is paid by the transfer into its destination account" doseries = create_series(name: "Payment to Loan", amount: 500, day_offset: 0, destination: accounts(:loan))- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)outflow = create_transfer(amount: 500, date: Date.current, to: accounts(:loan))assert_equal 1, @matcher.run!@@ -395,7 +493,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "backfill closes a recurring transfer's past occurrence from its transfer" doseries = create_series(name: "Payment to Loan", amount: 500, day_offset: -30, destination: accounts(:loan))- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)create_transfer(amount: 500, date: occurrence.due_on, to: accounts(:loan))@matcher.run_backfill!@@ -405,7 +503,7 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCasetest "explain scores a recurring transfer's own transfer and refuses others" doseries = create_series(name: "Payment to Loan", amount: 500, day_offset: 0, destination: accounts(:loan))- occurrence = series.recurring_occurrences.order(:due_on).first+ occurrence = first_occurrence(series)own = create_transfer(amount: 500, date: Date.current, to: accounts(:loan))other = create_transfer(amount: 500, date: Date.current, to: accounts(:credit_card))@@ -465,4 +563,8 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCaseentryable: Transaction.new(merchant: merchant, extra: extra))end++ def first_occurrence(series)+ series.recurring_occurrences.order(:due_on).first+ endend