The personal finance app for everyone (by everyone)
Ruby
Show how much of a transaction other bills already use (#4550)
Dov Benyomin Sohacheskid194118a3b80
diff --git a/app/controllers/recurring_occurrences_controller.rb b/app/controllers/recurring_occurrences_controller.rbindex 279be12829..703e129726 100644--- a/app/controllers/recurring_occurrences_controller.rb+++ b/app/controllers/recurring_occurrences_controller.rb@@ -17,6 +17,12 @@ class RecurringOccurrencesController < ApplicationController# The amount-nearness list is the fallback, so it must not repeat what the# ranked list promoted. The extra fetch keeps it full after subtraction.@other_entries = candidate_entries.reject { |entry| ranked_ids.include?(entry.id) }.first(FALLBACK_SHOWN)+ @remaining_by_entry = RecurringTransaction::Allocator.remaining_by_entry(+ @ranked_candidates.map(&:first) + @other_entries,+ # A bill hidden from this user must not show through what it took.+ allocations: RecurringAllocation.joins(recurring_occurrence: :recurring_transaction)+ .merge(RecurringTransaction.accessible_by(Current.user))+ )render layout: dialog_layoutenddiff --git a/app/models/recurring_transaction/allocator.rb b/app/models/recurring_transaction/allocator.rbindex 01262c5a6e..84f147495b 100644--- a/app/models/recurring_transaction/allocator.rb+++ b/app/models/recurring_transaction/allocator.rb@@ -46,6 +46,22 @@ class RecurringTransactionDigest::MD5.hexdigest(entry.id.to_s).to_i(16) % (2**31)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.+ def self.remaining_by_entry(entries, allocations: RecurringAllocation.all)+ by_id = entries.index_by(&:id)++ 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 ]+ end+ end+def initialize(occurrence)@occurrence = occurrenceenddiff --git a/app/views/recurring_occurrences/_candidate.html.erb b/app/views/recurring_occurrences/_candidate.html.erbindex c118f0ba5f..82e4f16b8a 100644--- a/app/views/recurring_occurrences/_candidate.html.erb+++ b/app/views/recurring_occurrences/_candidate.html.erb@@ -1,4 +1,4 @@-<%# locals: (occurrence:, entry:, reasons: [], promoted: false) %>+<%# locals: (occurrence:, entry:, reasons: [], promoted: false, remaining: nil) %><%# One transaction offered as the payment for this bill.@@ -15,6 +15,16 @@would shrink-wrap inside the divider stack. %><% amount = format_money(entry.amount_money.abs) %>+<% used_up = remaining&.zero? %>+<% usage_pill = capture do %>+ <% if used_up %>+ <%= render DS::Pill.new(label: t("recurring_occurrences.show.used_up"), title: t("recurring_occurrences.show.used_up_hint"), tone: :warning, marker: false) %>+ <% elsif remaining %>+ <span class="privacy-sensitive">+ <%= render DS::Pill.new(label: t("recurring_occurrences.show.amount_left", amount: format_money(Money.new(remaining, entry.currency))), tone: :neutral, marker: false) %>+ </span>+ <% end %>+<% end %><% if promoted %><div class="bg-container-inset rounded-lg p-3 space-y-3">@@ -31,8 +41,9 @@<p class="text-sm font-medium text-primary privacy-sensitive shrink-0"><%= amount %></p></div>- <% if reasons.any? %>+ <% if reasons.any? || usage_pill.present? %><div class="flex flex-wrap gap-1.5">+ <%= usage_pill %><% reasons.each do |reason| %><%= render DS::Pill.new(label: reason, tone: :neutral, marker: false) %><% end %>@@ -44,20 +55,25 @@variant: "primary",full_width: true,href: recurring_occurrence_allocations_path(occurrence, entry_id: entry.id),- method: :post+ method: :post,+ disabled: used_up) %></div><% else %><%# py-3 rather than py-2 so the row clears 44px on a phone. %><%= button_to recurring_occurrence_allocations_path(occurrence, entry_id: entry.id),form_class: "w-full",- class: "w-full text-left flex items-center justify-between gap-3 px-3 py-3 rounded-lg hover:bg-container-inset" do %>+ disabled: used_up,+ class: "w-full text-left flex items-center justify-between gap-3 px-3 py-3 rounded-lg hover:bg-container-inset disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:bg-transparent" do %><span class="min-w-0"><span class="block text-sm text-primary truncate"><%= entry.name %></span><span class="block text-xs text-secondary truncate"><%= l(entry.date, format: :short_with_year) %><%= " · #{reasons.join(" · ")}" if reasons.any? %></span></span>- <span class="text-sm text-primary privacy-sensitive shrink-0"><%= amount %></span>+ <span class="flex items-center gap-2 shrink-0">+ <%= usage_pill %>+ <span class="text-sm text-primary privacy-sensitive"><%= amount %></span>+ </span><% end %><% end %>diff --git a/app/views/recurring_occurrences/show.html.erb b/app/views/recurring_occurrences/show.html.erbindex b4828521d3..544421b26f 100644--- a/app/views/recurring_occurrences/show.html.erb+++ b/app/views/recurring_occurrences/show.html.erb@@ -163,6 +163,7 @@occurrence: @occurrence,entry: best_entry,promoted: true,+ remaining: @remaining_by_entry[best_entry.id],reasons: bills_match_reasons(best_explanation.signals,currency: @occurrence.currency,@@ -180,6 +181,7 @@<%= render "recurring_occurrences/candidate",occurrence: @occurrence,entry: entry,+ remaining: @remaining_by_entry[entry.id],reasons: bills_match_reasons(explanation.signals,currency: @occurrence.currency,@@ -222,7 +224,7 @@<% if @other_entries.any? %><div class="divide-y divide-subdued"><% @other_entries.each do |entry| %>- <%= render "recurring_occurrences/candidate", occurrence: @occurrence, entry: entry %>+ <%= render "recurring_occurrences/candidate", occurrence: @occurrence, entry: entry, remaining: @remaining_by_entry[entry.id] %><% end %></div><% else %>diff --git a/config/locales/views/recurring_occurrences/ca.yml b/config/locales/views/recurring_occurrences/ca.ymlindex a6aac0e7d5..3d0c8186d5 100644--- a/config/locales/views/recurring_occurrences/ca.yml+++ b/config/locales/views/recurring_occurrences/ca.yml@@ -28,6 +28,9 @@ ca:no_candidates: No hi ha transaccions properes per enllaçar.no_search_results: No hi ha res que coincideixi amb %{query}.link_payment: Enllaça el pagament+ amount_left: "Queden %{amount}"+ used_up: Ja utilitzada+ used_up_hint: "Altres factures ja utilitzen l'import complet d'aquesta transacció."not_this_one: No és aquestacant_find: No trobes la transacció?manual_explainer: Registra un pagament que saps que s'ha fet quan cap transacció d'aquí no hi coincideix.diff --git a/config/locales/views/recurring_occurrences/de.yml b/config/locales/views/recurring_occurrences/de.ymlindex 3f2a68c788..fcd1406185 100644--- a/config/locales/views/recurring_occurrences/de.yml+++ b/config/locales/views/recurring_occurrences/de.yml@@ -26,6 +26,9 @@ de:no_candidates: Keine passenden Transaktionen in zeitlicher Nähe gefunden.no_search_results: "Keine Treffer für „%{query}“."link_payment: Zahlung verknüpfen+ amount_left: "%{amount} übrig"+ used_up: Bereits verwendet+ used_up_hint: Andere Rechnungen verwenden bereits den vollen Betrag dieser Transaktion.not_this_one: Nicht diese Transaktioncant_find: Transaktion nicht gefunden?manual_explainer: Erfasse eine tatsächlich erfolgte Zahlung, wenn hier keine passende Transaktion dabei ist.diff --git a/config/locales/views/recurring_occurrences/en.yml b/config/locales/views/recurring_occurrences/en.ymlindex 5f805f0f85..c2feb5865b 100644--- a/config/locales/views/recurring_occurrences/en.yml+++ b/config/locales/views/recurring_occurrences/en.yml@@ -28,6 +28,9 @@ en:no_candidates: No nearby transactions to link.no_search_results: "Nothing matching %{query}."link_payment: Link payment+ amount_left: "%{amount} left"+ used_up: Already used+ used_up_hint: Other bills already use the full amount of this transaction.not_this_one: Not this onecant_find: Can't find the transaction?manual_explainer: Record a payment you know happened when no transaction here matches it.diff --git a/config/locales/views/recurring_occurrences/fr.yml b/config/locales/views/recurring_occurrences/fr.ymlindex 7939bdddc7..85d8d890db 100644--- a/config/locales/views/recurring_occurrences/fr.yml+++ b/config/locales/views/recurring_occurrences/fr.yml@@ -14,6 +14,7 @@ fr:success: Facture rouverteshow:add_heading: Ajouter un autre paiement+ amount_left: "%{amount} restants"cant_find: Vous ne trouvez pas la transaction ?due_on: Échéance le %{date}find_heading: Trouver un paiement@@ -45,6 +46,8 @@ fr:skipped: Ignoréesnooze_week: Reporter d'une semaineunlink: Délier+ used_up: Déjà utilisée+ used_up_hint: "D'autres factures utilisent déjà tout le montant de cette transaction."view_bill: Voir la factureskip:success: Facture ignoréediff --git a/config/locales/views/recurring_occurrences/pl.yml b/config/locales/views/recurring_occurrences/pl.ymlindex 26a2ea2566..85ee9b4423 100644--- a/config/locales/views/recurring_occurrences/pl.yml+++ b/config/locales/views/recurring_occurrences/pl.yml@@ -14,6 +14,7 @@ pl:success: Rachunek ponownie otwartyshow:add_heading: Dodaj kolejną płatność+ amount_left: "Pozostało %{amount}"cant_find: Nie możesz znaleźć transakcji?due_on: 'Termin: %{date}'find_heading: Znajdź płatność@@ -46,6 +47,8 @@ pl:skipped: Pominiętosnooze_week: Odłóż o tydzieńunlink: Odłącz+ used_up: Już wykorzystana+ used_up_hint: Inne rachunki wykorzystują już pełną kwotę tej transakcji.view_bill: Zobacz rachunekskip:success: Rachunek pominiętydiff --git a/config/locales/views/recurring_occurrences/ru.yml b/config/locales/views/recurring_occurrences/ru.ymlindex a73bf5c171..5aa4057d7c 100644--- a/config/locales/views/recurring_occurrences/ru.yml+++ b/config/locales/views/recurring_occurrences/ru.yml@@ -28,6 +28,9 @@ ru:no_candidates: Нет подходящих операций поблизости по дате для привязки.no_search_results: По запросу %{query} ничего не найдено.link_payment: Привязать оплату+ amount_left: "Осталось %{amount}"+ used_up: Уже использована+ used_up_hint: Другие счета уже используют всю сумму этой транзакции.not_this_one: Не этаcant_find: Не можете найти операцию?manual_explainer: Запишите оплату, которая точно была, если ни одна операция здесь ей не соответствует.diff --git a/config/locales/views/recurring_occurrences/tr.yml b/config/locales/views/recurring_occurrences/tr.ymlindex fa0b5d25d6..d1fa4106ce 100644--- a/config/locales/views/recurring_occurrences/tr.yml+++ b/config/locales/views/recurring_occurrences/tr.yml@@ -28,6 +28,9 @@ tr:no_candidates: Bağlanabilecek yakın tarihli işlem yok.no_search_results: '%{query} ile eşleşen sonuç yok.'link_payment: Ödemeyi bağla+ amount_left: "%{amount} kaldı"+ used_up: Zaten kullanıldı+ used_up_hint: Diğer faturalar bu işlemin tutarının tamamını zaten kullanıyor.not_this_one: Bu değilcant_find: İşlemi bulamıyor musunuz?manual_explainer: Burada eşleşen bir işlem olmadığında, yapıldığını bildiğiniz bir ödemeyi kaydedin.diff --git a/config/locales/views/recurring_occurrences/uk.yml b/config/locales/views/recurring_occurrences/uk.ymlindex c71853bce7..e26c548e22 100644--- a/config/locales/views/recurring_occurrences/uk.yml+++ b/config/locales/views/recurring_occurrences/uk.yml@@ -28,6 +28,9 @@ uk:no_candidates: Немає транзакцій поблизу цієї дати, які можна пов'язати.no_search_results: Нічого не знайдено за запитом %{query}.link_payment: Пов'язати оплату+ amount_left: "Залишилося %{amount}"+ used_up: Уже використана+ used_up_hint: Інші рахунки вже використовують усю суму цієї транзакції.not_this_one: Не цяcant_find: Не можете знайти транзакцію?manual_explainer: Зареєструйте оплату, яка точно відбулася, якщо жодна транзакція тут їй не відповідає.diff --git a/test/controllers/recurring_occurrences_controller_test.rb b/test/controllers/recurring_occurrences_controller_test.rbindex de133c729a..52785c3849 100644--- a/test/controllers/recurring_occurrences_controller_test.rb+++ b/test/controllers/recurring_occurrences_controller_test.rb@@ -298,6 +298,40 @@ class RecurringOccurrencesControllerTest < ActionDispatch::IntegrationTest"the rest of that charge can still pay another bill; over-allocation is refused when it is written"end+ test "a transaction another bill partly uses shows what is left of it" do+ entry = accounts(:depository).entries.create!(+ date: Date.current, amount: 25, currency: "USD", name: "Netflix charge",+ entryable: Transaction.new(merchant: merchants(:netflix))+ )+ earlier = @series.recurring_occurrences.create!(+ family: @family, original_due_on: Date.current - 25, due_on: Date.current - 25, currency: "USD"+ )+ RecurringTransaction::Allocator.new(earlier).allocate!(entry: entry, amount: 10)++ get recurring_occurrence_url(@occurrence), headers: { "Turbo-Frame" => "drawer" }++ assert_response :success+ assert_select "span", text: I18n.t("recurring_occurrences.show.amount_left", amount: "$15.00")+ assert_select "form[action=?] button:not([disabled])", recurring_occurrence_allocations_path(@occurrence, entry_id: entry.id)+ end++ test "a transaction other bills use in full is shown but cannot be linked" do+ entry = accounts(:depository).entries.create!(+ date: Date.current, amount: 10, currency: "USD", name: "Netflix charge",+ entryable: Transaction.new(merchant: merchants(:netflix))+ )+ earlier = @series.recurring_occurrences.create!(+ family: @family, original_due_on: Date.current - 25, due_on: Date.current - 25, currency: "USD"+ )+ RecurringTransaction::Allocator.new(earlier).allocate!(entry: entry, amount: 10)++ get recurring_occurrence_url(@occurrence), headers: { "Turbo-Frame" => "drawer" }++ assert_response :success+ assert_select "form[action=?] button[disabled]", recurring_occurrence_allocations_path(@occurrence, entry_id: entry.id)+ assert_select "span", text: I18n.t("recurring_occurrences.show.used_up")+ end+test "searching looks past the date window" doold = accounts(:depository).entries.create!(date: @occurrence.due_on - 300, amount: 15.99, currency: "USD",@@ -534,6 +568,41 @@ class RecurringOccurrencesControllerTest < ActionDispatch::IntegrationTest"positive control: the same-shaped entry on a shared account must render"end+ # A transfer into investment is hidden from family_member, who sees only+ # depository. What it took from a depository charge must not show through.+ test "usage by a bill the viewer cannot see does not badge the transaction" do+ visible = @family.recurring_transactions.create!(+ name: "Gym", account: accounts(:depository), amount: 30, 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, dedup_scope: "visible"+ ).recurring_occurrences.order(:due_on).first+ hidden = @family.recurring_transactions.create!(+ name: "To brokerage", account: accounts(:depository), destination_account: accounts(:investment),+ amount: 20, 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, dedup_scope: "hidden"+ ).recurring_occurrences.order(:due_on).first++ entry = accounts(:depository).entries.create!(+ date: Date.current, amount: 50, currency: "USD", name: "Gym and brokerage", entryable: Transaction.new+ )+ RecurringTransaction::Allocator.new(hidden).allocate!(entry: entry, amount: 20)+ left = I18n.t("recurring_occurrences.show.amount_left", amount: "$30.00")++ get recurring_occurrence_url(visible, q: entry.name), headers: { "Turbo-Frame" => "drawer" }+ assert_select "span", text: left++ member = users(:family_member)+ member.update!(preferences: (member.preferences || {}).merge("preview_features_enabled" => true))+ sign_in member+ get recurring_occurrence_url(visible, q: entry.name), headers: { "Turbo-Frame" => "drawer" }++ assert_response :success+ assert_match entry.name, response.body+ assert_select "span", text: left, count: 0+ end+# credit_card is shared read-only with family_member in the fixtures; a# read-only share can look at the bill but never move its payment state.test "a read-only account share cannot mutate an occurrence" dodiff --git a/test/models/recurring_transaction/allocator_test.rb b/test/models/recurring_transaction/allocator_test.rbindex 61e2d4a11a..5e453d628d 100644--- a/test/models/recurring_transaction/allocator_test.rb+++ b/test/models/recurring_transaction/allocator_test.rb@@ -223,6 +223,26 @@ class RecurringTransaction::AllocatorTest < ActiveSupport::TestCaseassert_equal 1, @occurrence.allocations.where(entry: lump).countend+ test "remaining_by_entry reports what each used entry has left in one query" do+ partly = entry_for(500)+ fully = entry_for(300)+ unused = entry_for(100)+ @allocator.allocate!(entry: partly, amount: 200)+ @allocator.allocate!(entry: fully, amount: 300)++ remaining = assert_queries_count(1) { Allocator.remaining_by_entry([ partly, fully, unused ]) }++ assert_equal({ partly.id => 300, fully.id => 0 }, remaining)+ end++ test "remaining_by_entry treats an unmeasurable entry as used up" do+ ExchangeRate.delete_all+ entry = foreign_entry(amount: 100, currency: "EUR")+ Allocator.new(usd_occurrence(expected: 150)).allocate!(amount: 150, entry: entry)++ assert_equal({ entry.id => 0 }, Allocator.remaining_by_entry([ entry ]))+ end+test "the same entry cannot be allocated twice to one occurrence" do# Partial amounts so the capacity guard passes; the unique index is the# backstop this test pins.