The personal finance app for everyone (by everyone)
Ruby
Give the bill forms the inputs every other form uses (#4095)
Guillem Arias Faustef029b6f3f926
diff --git a/app/controllers/recurring_transactions_controller.rb b/app/controllers/recurring_transactions_controller.rbindex c7d8653aa1..e5e56ef6f4 100644--- a/app/controllers/recurring_transactions_controller.rb+++ b/app/controllers/recurring_transactions_controller.rb@@ -129,7 +129,8 @@ class RecurringTransactionsController < ApplicationController@recurring_transaction = Current.family.recurring_transactions.new(# Paychecks default to the most common pay cadence; bills to monthly.frequency_preset: income ? "biweekly" : "monthly",- first_due_on: Date.current+ first_due_on: Date.current,+ currency: Current.family.currency)@recurring_transaction.is_income = income@@ -259,6 +260,7 @@ class RecurringTransactionsController < ApplicationControllerdef prefill_recurring_from_entry(entry)@recurring_transaction.name = entry.entryable.try(:merchant)&.name.presence || entry.name@recurring_transaction.amount = entry.amount.abs+ @recurring_transaction.currency = entry.currency@recurring_transaction.account_id = entry.account_id# A negative entry is an inflow: pre-fill as income, not as a bill.@recurring_transaction.is_income = true if entry.amount.negative?@@ -373,7 +375,7 @@ class RecurringTransactionsController < ApplicationControllerdef new_recurring_transaction_paramsparams.require(:recurring_transaction).permit(- :name, :amount, :account_id, :first_due_on, :frequency_preset,+ :name, :amount, :currency, :account_id, :first_due_on, :frequency_preset,:frequency_interval, :frequency_interval_unit,:payment_url, :autopay, :notes, :is_income)@@ -429,8 +431,13 @@ class RecurringTransactionsController < ApplicationControllerif attrs[:amount].present?magnitude = attrs[:amount].to_d.abs- @recurring_transaction.amount =- @recurring_transaction.typed_income? ? -magnitude : magnitude+ # Checked on the input: assigning it already rounded to the column.+ if RecurringTransaction.storable_amount?(magnitude)+ @recurring_transaction.amount =+ @recurring_transaction.typed_income? ? -magnitude : magnitude+ else+ @recurring_transaction.errors.add(:base, t("recurring_transactions.create.amount_too_precise"))+ endendif attrs.key?(:account_id)diff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rbindex 52efa4079d..047ed38ad5 100644--- a/app/models/recurring_transaction.rb+++ b/app/models/recurring_transaction.rb@@ -111,6 +111,23 @@ class RecurringTransaction < ApplicationRecordfalseend+ # Bill amounts and their payments are stored to the column's four decimal+ # places: finer than most currencies, coarser than crypto's eight. An amount+ # finer than that would be rounded on save, and a small enough one to zero,+ # which leaves a bill that can never close. Digits past the finest currency's+ # places are float noise, like 16.990000000000002 from an assistant's JSON+ # number, and are still just rounded away.+ def self.storable_amount?(amount)+ finest = Money::Currency.all.each_value.map { |data| data["default_precision"].to_i }.max+ amount.round(finest) == amount.round(columns_hash["amount"].scale)+ end++ # The step an amount input takes: the currency's own, but never finer than+ # what the column keeps.+ def self.amount_step(currency)+ [ Money::Currency.new(currency).step, 10.0**-columns_hash["amount"].scale ].max+ end+def payment_url?payment_url.present?enddiff --git a/app/models/recurring_transaction/declared_bill.rb b/app/models/recurring_transaction/declared_bill.rbindex 54c692c940..2985b658f1 100644--- a/app/models/recurring_transaction/declared_bill.rb+++ b/app/models/recurring_transaction/declared_bill.rb@@ -42,7 +42,7 @@ class RecurringTransactionamount: amount,bill_type: is_income ? "income" : "bill",account: account,- currency: account&.currency || family.currency,+ currency: chosen_currency || account&.currency || family.currency,payment_url: attrs[:payment_url],autopay: ActiveModel::Type::Boolean.new.cast(attrs[:autopay]) || false,notes: attrs[:notes],@@ -68,6 +68,12 @@ class RecurringTransactionreturn recurringend+ # Checked on the input: assigning it already rounded to the column.+ unless RecurringTransaction.storable_amount?(amount)+ recurring.errors.add(:base, I18n.t("recurring_transactions.create.amount_too_precise"))+ return recurring+ end+if due.nil?recurring.errors.add(:base, I18n.t("recurring_transactions.create.due_date_required"))return recurring@@ -133,5 +139,17 @@ class RecurringTransactionscope.exists?(name: recurring.name, merchant_id: nil)endend++ private+ # A currency picked on the form wins, the way a transaction's does: a USD+ # subscription charged to a EUR card is a USD bill. With none, the bill+ # takes its account's currency. A code the app doesn't know is ignored+ # rather than saved, since formatting it would raise later.+ def chosen_currency+ code = attrs[:currency].to_s.strip.presence+ Money::Currency.new(code).iso_code if code+ rescue Money::Currency::UnknownCurrencyError+ nil+ endendenddiff --git a/app/views/bills/all.html.erb b/app/views/bills/all.html.erbindex f1c0853ac4..8caf210af7 100644--- a/app/views/bills/all.html.erb+++ b/app/views/bills/all.html.erb@@ -3,7 +3,10 @@<div class="space-y-4 pb-6 lg:pb-12"><%= render "bills/view_switcher", active: "all" %>- <%= form_with url: bills_path, method: :get, scope: :q,+ <%# Built with the styled form builder, so each filter sits in the boxed field+ every form uses, one height with the search box. As bare selects they read+ as loose words with a chevron, and had no focus ring at all. %>+ <%= styled_form_with url: bills_path, method: :get, scope: :q,data: { controller: "auto-submit-form" },class: "flex flex-wrap items-center gap-2" do |form| %><%= hidden_field_tag :view, "all" %>@@ -18,21 +21,21 @@[ [ t(".any_status"), "" ] ] + BillsController::STATUS_FILTERS.map { |status| [ t(".status_filters.#{status}"), status ] },params.dig(:q, :status)),- {},+ { container_class: "w-auto py-2.5" },{ class: "form-field__input w-auto", "data-auto-submit-form-target": "auto" } %><%= form.select :bill_type,options_for_select([ [ t(".any_type"), "" ] ] + RecurringTransaction.bill_types.keys.map { |type| [ t(".types.#{type}"), type ] },params.dig(:q, :bill_type)),- {},+ { container_class: "w-auto py-2.5" },{ class: "form-field__input w-auto", "data-auto-submit-form-target": "auto" } %><%= form.select :sort,options_for_select([ [ t(".sort_due"), "" ], [ t(".sort_name"), "name" ], [ t(".sort_amount"), "amount" ] ],params.dig(:q, :sort)),- {},+ { container_class: "w-auto py-2.5" },{ class: "form-field__input w-auto", "data-auto-submit-form-target": "auto" } %><% end %>diff --git a/app/views/recurring_occurrences/show.html.erb b/app/views/recurring_occurrences/show.html.erbindex 090eb47e83..6597b3f8e0 100644--- a/app/views/recurring_occurrences/show.html.erb+++ b/app/views/recurring_occurrences/show.html.erb@@ -250,18 +250,27 @@<%= render DS::Disclosure.new(title: t(".cant_find"), align: "left") do %><div class="space-y-2 pt-1"><p class="text-xs text-secondary"><%= t(".manual_explainer") %></p>- <%= form_with url: recurring_occurrence_allocations_path(@occurrence), class: "flex items-end gap-2" do |form| %>- <div class="grow">- <%= form.label :amount, t(".manual_amount_label"), class: "form-field__label" %>- <%= form.number_field :amount, step: 0.01, min: 0.01,- value: @occurrence.remaining_amount.positive? ? @occurrence.remaining_amount : nil,- class: "form-field__input" %>+ <%# The same boxed fields as every other form. Bare inputs under+ a bare label read as text, not as something to fill in. The+ payment is recorded in the bill's currency, so that shows+ and stays put. %>+ <%= styled_form_with url: recurring_occurrence_allocations_path(@occurrence), class: "space-y-2" do |form| %>+ <div class="grid grid-cols-2 gap-2">+ <%# The minimum is one step, so a whole-unit currency like JPY+ keeps whole amounts valid: a 0.01 minimum would have+ been the step base and put 1000 off-step. %>+ <% step = RecurringTransaction.amount_step(@occurrence.currency) %>+ <%= form.money_field :amount,+ label: t(".manual_amount_label"),+ input_class: "privacy-sensitive privacy-sensitive-interactive",+ value: (@occurrence.remaining_amount if @occurrence.remaining_amount.positive?),+ currency_value_override: @occurrence.currency,+ disable_currency: true,+ step: step,+ min: step %>+ <%= form.date_field :paid_on, label: t(".manual_date_label"), value: Date.current %></div>- <div class="grow">- <%= form.label :paid_on, t(".manual_date_label"), class: "form-field__label" %>- <%= form.date_field :paid_on, value: Date.current, class: "form-field__input" %>- </div>- <%= render DS::Button.new(text: t(".record_payment"), variant: "secondary") %>+ <%= render DS::Button.new(text: t(".record_payment"), variant: "secondary", full_width: true) %><% end %></div><% end %>diff --git a/app/views/recurring_transactions/_form.html.erb b/app/views/recurring_transactions/_form.html.erbindex aac3b1c046..c4e2808e14 100644--- a/app/views/recurring_transactions/_form.html.erb+++ b/app/views/recurring_transactions/_form.html.erb@@ -26,18 +26,20 @@required: true %><% if recurring_transaction.new_record? %>- <div class="grid grid-cols-2 gap-3">- <%= f.number_field :amount,- label: income ? t(".income_amount_label") : t(".amount_label"),- value: recurring_transaction.amount&.abs,- min: 0,- step: 0.01,- required: true %>- <%= f.date_field :first_due_on,- label: income ? t(".income_due_on_label") : t(".first_due_on_label"),- value: recurring_transaction.first_due_on,- required: true %>- </div>+ <%# The money field every other form uses, currency picker included: a+ new bill takes the currency picked here, like a transaction does. %>+ <%= f.money_field :amount,+ label: income ? t(".income_amount_label") : t(".amount_label"),+ input_class: "privacy-sensitive privacy-sensitive-interactive",+ value: recurring_transaction.amount&.abs,+ default_currency: Current.family.currency,+ step: RecurringTransaction.amount_step(recurring_transaction.currency.presence || Current.family.currency),+ min: 0,+ required: true %>+ <%= f.date_field :first_due_on,+ label: income ? t(".income_due_on_label") : t(".first_due_on_label"),+ value: recurring_transaction.first_due_on,+ required: true %><% else %><%# first_due_on seeds the schedule and does nothing once the seriesexists, so editing when a bill falls due happens in the frequency@@ -45,11 +47,15 @@<div class="space-y-2"><%# Income stores its amount negative; the field edits the magnitudeand the update path re-applies the sign. %>- <%= f.number_field :amount,+ <%# The currency shows but stays put: it shapes the schedule and the+ payments already matched to it. %>+ <%= f.money_field :amount,label: income ? t(".income_amount_label") : t(".amount_label"),+ input_class: "privacy-sensitive privacy-sensitive-interactive",value: recurring_transaction.amount&.abs,+ disable_currency: true,+ step: RecurringTransaction.amount_step(recurring_transaction.currency),min: 0,- step: 0.01,required: true %><p class="text-xs text-secondary"><%= income ? t(".income_amount_edit_hint") : t(".amount_edit_hint") %></p></div>@@ -58,7 +64,8 @@<%= f.collection_select :account_id,Current.user.accessible_accounts.visible.alphabetically,:id, :name,- { label: income ? t(".income_account_label") : t(".account_label"), include_blank: t(".account_blank") } %>+ { label: income ? t(".income_account_label") : t(".account_label"), include_blank: t(".account_blank"),+ variant: :logo, searchable: true } %><%# Which kind this is was decided by the entry point that opened thedialog, so the form only has to carry the answer. Offering it as a@@ -129,10 +136,12 @@%w[bill subscription installment other].map { |type| [ t("bills.all.types.#{type}"), type ] },{ label: t(".bill_type_label") },{ data: { frequency_fields_target: "preset", action: "change->frequency-fields#update" } } %>- <%= f.collection_select :category_id,- Current.family.categories.alphabetically,- :id, :name,- { label: t(".category_label"), include_blank: t(".category_blank") } %>+ <%= render DS::CategorySelect.new(+ form: f,+ categories: Current.family.categories.alphabetically_by_hierarchy.to_a,+ selected_id: recurring_transaction.category_id,+ blank_label: t(".category_blank")+ ) %><div data-frequency-fields-target="group" data-presets="installment" class="hidden col-span-2"><%= f.number_field :end_after_count,@@ -154,7 +163,7 @@<% end %><% end %>- <%= render DS::Disclosure.new(title: t(".more_options"), align: "left") do %>+ <%= render DS::Disclosure.new(title: t(".more_options")) do %><div class="space-y-4 pt-2"><% unless income %><div class="space-y-2">diff --git a/app/views/recurring_transactions/new.html.erb b/app/views/recurring_transactions/new.html.erbindex 974e63ed30..f622ed2f3d 100644--- a/app/views/recurring_transactions/new.html.erb+++ b/app/views/recurring_transactions/new.html.erb@@ -6,7 +6,7 @@<p class="text-sm font-medium text-primary"><%= @recurring_transaction.is_income ? t(".start_from_income_title") : t(".start_from_title") %></p>- <div class="max-h-44 overflow-y-auto rounded-lg shadow-border-xs divide-y divide-divider">+ <div class="max-h-44 overflow-y-auto rounded-lg shadow-border-xs divide-y divide-subdued"><% @candidates.each do |candidate| %><%= link_to new_recurring_transaction_path(entry_id: candidate[:entry_id], income: params[:income].presence),class: "flex items-center justify-between gap-3 px-3 py-2 hover:bg-surface-inset" do %>diff --git a/app/views/recurring_transactions/pick_entry.html.erb b/app/views/recurring_transactions/pick_entry.html.erbindex a12dc4a4b5..3cf7acae82 100644--- a/app/views/recurring_transactions/pick_entry.html.erb+++ b/app/views/recurring_transactions/pick_entry.html.erb@@ -17,7 +17,7 @@<% end %><% if @picker_entries.any? %>- <div class="max-h-80 overflow-y-auto rounded-lg shadow-border-xs divide-y divide-divider">+ <div class="max-h-80 overflow-y-auto rounded-lg shadow-border-xs divide-y divide-subdued"><% @picker_entries.each do |entry| %><%= render "recurring_transactions/picker_row", entry: entry, claimed_by: @claimed_by[entry.id] %><% end %>diff --git a/config/brakeman.ignore b/config/brakeman.ignoreindex a6bb3e36ea..bc007f8971 100644--- a/config/brakeman.ignore+++ b/config/brakeman.ignore@@ -199,13 +199,13 @@{"warning_type": "Mass Assignment","warning_code": 105,- "fingerprint": "dc0c96660c7e4fd22afb88b441ad90dda58879fbdbabfcb422ba072b1f5168ed",+ "fingerprint": "142ff7a22a406094b4cb3a6fdde4f8ec4ea404f2a6d4eaf85bbb1f413fceb527","check_name": "PermitAttributes","message": "Potentially dangerous key allowed for mass assignment","file": "app/controllers/recurring_transactions_controller.rb",- "line": 371,+ "line": 378,"link": "https://brakemanscanner.org/docs/warning_types/mass_assignment/",- "code": "params.require(:recurring_transaction).permit(:name, :amount, :account_id, :first_due_on, :frequency_preset, :frequency_interval, :frequency_interval_unit, :payment_url, :autopay, :notes, :is_income)",+ "code": "params.require(:recurring_transaction).permit(:name, :amount, :currency, :account_id, :first_due_on, :frequency_preset, :frequency_interval, :frequency_interval_unit, :payment_url, :autopay, :notes, :is_income)","render_path": null,"location": {"type": "controller",diff --git a/config/locales/views/recurring_transactions/ca.yml b/config/locales/views/recurring_transactions/ca.ymlindex 55d5c7359c..3fb2194e91 100644--- a/config/locales/views/recurring_transactions/ca.yml+++ b/config/locales/views/recurring_transactions/ca.yml@@ -127,6 +127,7 @@ ca:success_income: Ingrés afegitdue_date_required: Introdueix la propera data de venciment de la facturaamount_invalid: Introdueix l'import com a número sense format+ amount_too_precise: Fes servir 4 decimals com a màximaccount_invalid: Tria un compte al qual puguis afegir factures, o deixa-ho en blancalready_exists: Aquesta factura ja existeixedit:@@ -173,7 +174,6 @@ ca:income_amount_edit_hint: S'aplica als cobraments a partir d'ara. Els que ja han vençut mantenen l'import que tenien.cancelled_on_label: Data de cancel·laciócancelled_on_hint: Registrar la data és només per a la teva referència. Posa la factura en pausa perquè deixin d'aparèixer els propers venciments.- category_label: Categoriacategory_blank: Sense categoriafrequency_new_hint: Els detalls del dia surten de la data de venciment de dalt. Pots ajustar la periodicitat després de desar.frequency_label: Periodicitatdiff --git a/config/locales/views/recurring_transactions/en.yml b/config/locales/views/recurring_transactions/en.ymlindex 0835674a50..4abee00be8 100644--- a/config/locales/views/recurring_transactions/en.yml+++ b/config/locales/views/recurring_transactions/en.yml@@ -81,6 +81,7 @@ en:success_income: Income addeddue_date_required: "Enter the bill's next due date"amount_invalid: "Enter the amount as a plain number"+ amount_too_precise: Use at most 4 decimal placesaccount_invalid: "Pick an account you can add bills to, or leave it blank"already_exists: "This bill already exists"edit:@@ -127,7 +128,6 @@ en:income_amount_edit_hint: Applies to paydays from now on. Anything already due keeps the amount it was.cancelled_on_label: Cancelledcancelled_on_hint: Recording the date is for your own reference. Pause the bill to stop future ones appearing.- category_label: Categorycategory_blank: No categoryfrequency_new_hint: The day details come from the due date above. You can refine the schedule after saving.frequency_label: How oftendiff --git a/config/locales/views/recurring_transactions/fr.yml b/config/locales/views/recurring_transactions/fr.ymlindex 268e091ed1..e621b1805f 100644--- a/config/locales/views/recurring_transactions/fr.yml+++ b/config/locales/views/recurring_transactions/fr.yml@@ -20,6 +20,7 @@ fr:account_invalid: Choisissez un compte auquel vous pouvez ajouter des factures, ou laissez le champ videalready_exists: Cette facture existe déjàamount_invalid: Saisissez le montant sous forme de nombre simple+ amount_too_precise: Utilisez au plus 4 décimalesdue_date_required: Saisissez la prochaine date d'échéance de la facturesuccess: Facture ajoutéesuccess_income: Revenu ajouté@@ -55,7 +56,6 @@ fr:cancelled_on_hint: Noter la date ne sert qu'à votre suivi personnel. Mettez la facture en pause pour arrêter l'apparition des suivantes.cancelled_on_label: Annulée lecategory_blank: Sans catégorie- category_label: Catégoriefirst_due_on_label: Prochaine échéancefrequency_day_label: Le jourfrequency_hint: À quelle fréquence cette facture arrive à échéance. Choisissez les détails du jour pour correspondre à votre relevé.diff --git a/config/locales/views/recurring_transactions/pl.yml b/config/locales/views/recurring_transactions/pl.ymlindex c65ee0c60a..b49a17e256 100644--- a/config/locales/views/recurring_transactions/pl.yml+++ b/config/locales/views/recurring_transactions/pl.yml@@ -21,6 +21,7 @@ pl:pustealready_exists: Ten rachunek już istniejeamount_invalid: Wpisz kwotę jako zwykłą liczbę+ amount_too_precise: Użyj najwyżej 4 miejsc po przecinkudue_date_required: Wpisz następny termin płatności rachunkusuccess: Rachunek dodanysuccess_income: Przychód dodany@@ -63,7 +64,6 @@ pl:rachunek, aby przyszłe wystąpienia przestały się pojawiać.cancelled_on_label: Anulowanocategory_blank: Brak kategorii- category_label: Kategoriafirst_due_on_label: Następny terminfrequency_day_label: W dniufrequency_hint: Jak często ten rachunek jest wymagalny. Dobierz szczegóły dniadiff --git a/config/locales/views/recurring_transactions/ru.yml b/config/locales/views/recurring_transactions/ru.ymlindex 7dbe483497..e9cfb2822d 100644--- a/config/locales/views/recurring_transactions/ru.yml+++ b/config/locales/views/recurring_transactions/ru.yml@@ -127,6 +127,7 @@ ru:success_income: Доход добавленdue_date_required: Укажите следующую дату оплатыamount_invalid: Введите сумму обычным числом+ amount_too_precise: Используйте не более 4 знаков после запятойaccount_invalid: Выберите счёт, к которому можно добавлять платежи, или оставьте поле пустымalready_exists: Такой платёж уже существуетedit:@@ -175,7 +176,6 @@ ru:income_amount_edit_hint: Применяется к выплатам с этого момента. Уже наступившие выплаты сохранят прежнюю сумму.cancelled_on_label: Отмененоcancelled_on_hint: Дата записывается только для вашего сведения. Приостановите платёж, чтобы будущие не появлялись.- category_label: Категорияcategory_blank: Без категорииfrequency_new_hint: Дни берутся из даты оплаты выше. Расписание можно уточнить после сохранения.frequency_label: Периодичностьdiff --git a/config/locales/views/recurring_transactions/tr.yml b/config/locales/views/recurring_transactions/tr.ymlindex ed6d834be6..26370c136a 100644--- a/config/locales/views/recurring_transactions/tr.yml+++ b/config/locales/views/recurring_transactions/tr.yml@@ -126,6 +126,7 @@ tr:success_income: Gelir eklendidue_date_required: Faturanın bir sonraki son ödeme tarihini girinamount_invalid: Tutarı düz bir sayı olarak girin+ amount_too_precise: En fazla 4 ondalık basamak kullanınaccount_invalid: Fatura ekleyebileceğiniz bir hesap seçin veya boş bırakınalready_exists: Bu fatura zaten mevcutedit:@@ -172,7 +173,6 @@ tr:income_amount_edit_hint: Bundan sonraki maaş günlerine uygulanır. Vadesi gelmiş olanlar mevcut tutarlarını korur.cancelled_on_label: İptal tarihicancelled_on_hint: Tarihi kaydetmek yalnızca kendi bilginiz içindir. Gelecektekilerin görünmemesi için faturayı duraklatın.- category_label: Kategoricategory_blank: Kategori yokfrequency_new_hint: Gün ayrıntıları yukarıdaki son ödeme tarihinden alınır. Kaydettikten sonra zamanlamayı ayrıntılandırabilirsiniz.frequency_label: Sıklıkdiff --git a/config/locales/views/recurring_transactions/uk.yml b/config/locales/views/recurring_transactions/uk.ymlindex 4f71710c16..7fcef0ae6f 100644--- a/config/locales/views/recurring_transactions/uk.yml+++ b/config/locales/views/recurring_transactions/uk.yml@@ -120,6 +120,7 @@ uk:success_income: Дохід доданоdue_date_required: Введіть наступну дату сплатиamount_invalid: Введіть суму як звичайне число+ amount_too_precise: Використовуйте не більше 4 знаків після комиaccount_invalid: Виберіть рахунок, до якого можна додавати платежі, або залиште поле порожнімalready_exists: Такий платіж уже існуєedit:@@ -168,7 +169,6 @@ uk:income_amount_edit_hint: Застосовується до виплат відтепер. Для вже належних сума не зміниться.cancelled_on_label: Скасованоcancelled_on_hint: Дата зберігається лише для вашої довідки. Призупиніть платіж, щоб майбутні не з'являлися.- category_label: Категоріяcategory_blank: Без категоріїfrequency_new_hint: Дні беруться з дати сплати вище. Розклад можна уточнити після збереження.frequency_label: Як частоdiff --git a/test/controllers/bills_controller_test.rb b/test/controllers/bills_controller_test.rbindex 0d0ca8bf31..8b803d0f03 100644--- a/test/controllers/bills_controller_test.rb+++ b/test/controllers/bills_controller_test.rb@@ -1441,6 +1441,19 @@ class BillsControllerTest < ActionDispatch::IntegrationTestassert_match I18n.t("bills.all.subscription_price_changes"), response.bodyend+ # Bare, the filters read as loose words with a chevron and had no focus+ # ring. Each sits in the boxed field the form builder draws.+ test "the All bills filters are boxed fields like the search beside them" do+ create_bill(name: "Rent", amount: 1200)++ get bills_url(view: "all")++ assert_response :success+ %w[q[status] q[bill_type] q[sort]].each do |name|+ assert_select ".form-field select.form-field__input[name=?]", name+ end+ end+test "the rollup stays out of the way when the filter is not on subscriptions" dosub = create_bill(name: "STREAMFLIX", amount: 24.99)sub.update!(bill_type: "subscription")diff --git a/test/controllers/recurring_occurrences_controller_test.rb b/test/controllers/recurring_occurrences_controller_test.rbindex d434a6ea94..554dd0c178 100644--- a/test/controllers/recurring_occurrences_controller_test.rb+++ b/test/controllers/recurring_occurrences_controller_test.rb@@ -25,6 +25,30 @@ class RecurringOccurrencesControllerTest < ActionDispatch::IntegrationTestassert_equal 1, response.body.scan(/<turbo-frame[^>]*id="drawer"/).sizeend+ # A manual payment is typed into the same boxed money and date fields as+ # every other form, in the bill's own currency, which can't be changed here.+ test "the manual payment form uses the app's money and date fields" do+ get recurring_occurrence_url(@occurrence), headers: { "Turbo-Frame" => "drawer" }++ assert_response :success+ assert_select "form[action=?]", recurring_occurrence_allocations_path(@occurrence) do+ assert_select ".form-field[data-controller~='money-field'] input[name=amount][value=?]", "15.99"+ assert_select "input.privacy-sensitive.privacy-sensitive-interactive[name=amount]"+ assert_select "select[name=currency][disabled] option[selected][value=?]", "USD"+ assert_select ".form-field input[type=date][name=paid_on]"+ end+ end++ # A whole-unit currency steps by 1. With a 0.01 minimum as the step base,+ # every whole amount was off-step and the browser refused to submit it.+ test "the manual payment steps from its minimum in the bill's currency" do+ @occurrence.update!(currency: "JPY")++ get recurring_occurrence_url(@occurrence), headers: { "Turbo-Frame" => "drawer" }++ assert_select "input[name=amount][step='1.0'][min='1.0']"+ end+# Turbo caches the page as it was left, so a drawer still open when the user# navigated away would come back from Back as a stray dialog.# Visited directly, the dialog is the page, and Back has to restore it.diff --git a/test/controllers/recurring_transactions/smart_fills_controller_test.rb b/test/controllers/recurring_transactions/smart_fills_controller_test.rbindex 8735374e8e..b474871d61 100644--- a/test/controllers/recurring_transactions/smart_fills_controller_test.rb+++ b/test/controllers/recurring_transactions/smart_fills_controller_test.rb@@ -24,7 +24,7 @@ class RecurringTransactions::SmartFillsControllerTest < ActionDispatch::Integratassert_match I18n.t("recurring_transactions.new.smart_fill_applied"), response.bodyassert_match "Weekly gaps between charges", response.bodyassert_select "input[name=?][value=?]", "recurring_transaction[name]", "Gym Membership"- assert_select "input[name=?][value=?]", "recurring_transaction[amount]", "42.0"+ assert_select "input[name=?][value=?]", "recurring_transaction[amount]", "42.00"endtest "a provider failure keeps the plain prefill and explains" dodiff --git a/test/controllers/recurring_transactions_controller_test.rb b/test/controllers/recurring_transactions_controller_test.rbindex b8b62b0f1b..d7eecae82b 100644--- a/test/controllers/recurring_transactions_controller_test.rb+++ b/test/controllers/recurring_transactions_controller_test.rb@@ -37,6 +37,67 @@ class RecurringTransactionsControllerTest < ActionDispatch::IntegrationTestassert_match I18n.t("recurring_transactions.form.more_options"), bodyend+ # The amount is the money field every other form uses. On a new bill its+ # currency is picked there, defaulting to the family's, or the transaction's+ # when the dialog starts from one. On an existing bill it shows and stays.+ test "the add and edit forms use the app's money field and category select" do+ get new_recurring_transaction_url, headers: { "Turbo-Frame" => "modal" }++ assert_response :success+ assert_select ".form-field[data-controller~='money-field'] input[name=?]", "recurring_transaction[amount]"+ # Blurred in privacy mode, and still typeable.+ assert_select "input.privacy-sensitive.privacy-sensitive-interactive[name=?]", "recurring_transaction[amount]"+ assert_select "select[name=?]:not([disabled]) option[selected][value=?]", "recurring_transaction[currency]", @family.currency+ # The candidate list's rows are divided by a real token: divide-divider+ # matched nothing, so its rules fell back to the text colour.+ assert_no_match "divide-divider", response.body++ entry = accounts(:depository).entries.create!(date: Date.current - 20, amount: 12.5, currency: "EUR",+ name: "STREAMBOX", entryable: Transaction.new)+ get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }+ assert_select "select[name=?] option[selected][value=?]", "recurring_transaction[currency]", "EUR"+ assert_select "input[name=?][value=?]", "recurring_transaction[amount]", "12.50"++ get edit_recurring_transaction_url(@recurring_transaction), headers: { "Turbo-Frame" => "modal" }+ assert_select "select[name=?][disabled] option[selected][value=?]", "recurring_transaction[currency]", @recurring_transaction.currency+ assert_select "#category_id_trigger"+ assert_select "input[type=hidden][name=?]", "recurring_transaction[category_id]"+ end++ # Assigning the amount would already round it to the column's four places,+ # so the edit form refuses a finer one instead of saving a different figure.+ test "update refuses an amount finer than the column keeps" do+ patch recurring_transaction_url(@recurring_transaction),+ params: { recurring_transaction: { name: @recurring_transaction.display_name, amount: "15.123456" } }++ assert_response :unprocessable_entity+ assert_match I18n.t("recurring_transactions.create.amount_too_precise"), response.body+ assert_equal 15.99, @recurring_transaction.reload.amount+ end++ test "the amount steps by the currency, never finer than the column" do+ assert_in_delta 0.01, RecurringTransaction.amount_step("USD")+ assert_in_delta 1.0, RecurringTransaction.amount_step("JPY")+ assert_in_delta 0.0001, RecurringTransaction.amount_step("BTC")++ get new_recurring_transaction_url, headers: { "Turbo-Frame" => "modal" }+ assert_select "input[name=?][step=?]", "recurring_transaction[amount]", "0.01"+ end++ test "create keeps the currency picked on the form" do+ post recurring_transactions_url, params: {+ recurring_transaction: {+ name: "Streambox", amount: "12.50", currency: "EUR",+ account_id: accounts(:depository).id, first_due_on: (Date.current + 9).iso8601,+ frequency_preset: "monthly"+ }+ }++ bill = @family.recurring_transactions.find_by!(name: "Streambox")+ assert_equal "EUR", bill.currency+ assert_equal 12.5, bill.amount+ end+test "edit renders the form" doget edit_recurring_transaction_url(@recurring_transaction)@@ -815,7 +876,7 @@ class RecurringTransactionsControllerTest < ActionDispatch::IntegrationTestassert_response :success# The stored sign is bookkeeping; the form edits what the paycheck pays.- assert_select "input[name=?][value=?]", "recurring_transaction[amount]", "2000.0"+ assert_select "input[name=?][value=?]", "recurring_transaction[amount]", "2000.00"endtest "the edit form shows a bill amount as it is stored" dodiff --git a/test/models/recurring_transaction/declared_bill_test.rb b/test/models/recurring_transaction/declared_bill_test.rbindex 24882465d9..cd71e5ccb7 100644--- a/test/models/recurring_transaction/declared_bill_test.rb+++ b/test/models/recurring_transaction/declared_bill_test.rb@@ -31,6 +31,48 @@ class RecurringTransaction::DeclaredBillTest < ActiveSupport::TestCaseendend+ # The form offers the currency next to the amount, like a transaction's: a+ # USD subscription charged to a EUR card is a USD bill.+ test "a picked currency wins over the account's" do+ series = build_bill(amount: "40", currency: "EUR")++ assert series.errors.none?+ assert_equal "EUR", series.currency+ assert_equal "USD", accounts(:depository).currency+ end++ test "without a picked currency the bill takes its account's" do+ assert_equal accounts(:depository).currency, build_bill(amount: "40").currency+ assert_equal accounts(:depository).currency, build_bill(amount: "40", currency: "").currency+ end++ test "a currency the app doesn't know is ignored, not saved" do+ series = build_bill(amount: "40", currency: "XYZ")++ assert series.errors.none?+ assert_equal accounts(:depository).currency, series.currency+ end++ # The column keeps four decimal places. A finer amount would be rounded on+ # save, and one this small to zero: a bill whose cycles can never close.+ test "an amount finer than the column keeps is refused, not rounded" do+ series = build_bill(amount: "0.00000001", currency: "BTC")++ assert_includes series.errors.full_messages.to_sentence,+ I18n.t("recurring_transactions.create.amount_too_precise")+ assert build_bill(amount: "12.3456", currency: "BTC").errors.none?+ end++ # The assistant sends JSON numbers, so 15.99 + 1 arrives as+ # 16.990000000000002. That is noise past any currency's places, not a+ # precision the user meant, and it saves as 16.99 the way it always has.+ test "float noise past every currency's places is rounded, not refused" do+ series = build_bill(amount: (15.99 + 1).to_s)++ assert series.errors.none?, series.errors.full_messages.to_sentence+ assert_equal BigDecimal("16.99"), series.amount+ end+test "the same identity at the same amount reports a duplicate instead of raising" do# The amount is stamped into dedup_scope before the first insert, so the# very first identical duplicate collides and must surface as a validation@@ -54,7 +96,7 @@ class RecurringTransaction::DeclaredBillTest < ActiveSupport::TestCaseendprivate- def build_bill(amount:)+ def build_bill(amount:, **attrs)RecurringTransaction::DeclaredBill.new(family: @family,user: @user,@@ -64,7 +106,7 @@ class RecurringTransaction::DeclaredBillTest < ActiveSupport::TestCaseaccount_id: accounts(:depository).id,first_due_on: (Date.current + 10).iso8601,frequency_preset: "monthly"- }+ }.merge(attrs)).buildendenddiff --git a/test/system/declare_and_pay_bill_test.rb b/test/system/declare_and_pay_bill_test.rbindex 3a1ca8a2ea..3aa7fad467 100644--- a/test/system/declare_and_pay_bill_test.rb+++ b/test/system/declare_and_pay_bill_test.rb@@ -124,7 +124,7 @@ class DeclareAndPayBillTest < ApplicationSystemTestCaseclick_on "WATSON PROPERTY LLC"assert_field I18n.t("recurring_transactions.form.name_label"), with: "WATSON PROPERTY LLC"- assert_field I18n.t("recurring_transactions.form.amount_label"), with: "537.5"+ assert_field I18n.t("recurring_transactions.form.amount_label"), with: "537.50"click_button I18n.t("recurring_transactions.form.submit")assert_text "WATSON PROPERTY LLC"