The personal finance app for everyone (by everyone)
Ruby
Fix N+1 queries on categories index by batching lookups and removing … (#2163)
William Wei Mingb613d107bed3
diff --git a/.github/workflows/preview-cleanup.yml b/.github/workflows/preview-cleanup.ymlindex 2df3d98d9a..6ad6c6b5bf 100644--- a/.github/workflows/preview-cleanup.yml+++ b/.github/workflows/preview-cleanup.yml@@ -88,7 +88,7 @@ jobs:cleanup-expired:name: Cleanup expired previews- if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'+ if: github.repository == 'we-promise/sure' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')runs-on: ubuntu-latesttimeout-minutes: 15diff --git a/app/components/DS/disclosure.html.erb b/app/components/DS/disclosure.html.erbindex 8cd25bcfc1..007b09ac98 100644--- a/app/components/DS/disclosure.html.erb+++ b/app/components/DS/disclosure.html.erb@@ -1,7 +1,7 @@<%= tag.details class: details_classes, open: open, **details_opts do %>- <%= tag.summary class: summary_classes do %>+ <%= tag.summary class: summary_classes, aria: summary_aria_attrs do %><% if summary_content? %>- <% if variant == :default %>+ <% if variant.in?(%i[default bare]) %><%# `:default` summary is already `flex justify-between`, socaller-provided sibling divs get distributed directly.Wrapping would collapse them into a single flex child and@@ -33,7 +33,11 @@<% end %><% end %>- <%= tag.div class: body_class.presence do %>+ <% if variant == :bare %><%= content %>+ <% else %>+ <%= tag.div class: body_class.presence do %>+ <%= content %>+ <% end %><% end %><% end %>diff --git a/app/components/DS/disclosure.rb b/app/components/DS/disclosure.rbindex bff18f3323..ea1c9ec08e 100644--- a/app/components/DS/disclosure.rb+++ b/app/components/DS/disclosure.rb@@ -1,9 +1,9 @@class DS::Disclosure < DesignSystemComponentrenders_one :summary_content- VARIANTS = %i[default card card_inset inline].freeze+ VARIANTS = %i[default card card_inset inline bare].freeze- attr_reader :title, :align, :open, :variant, :summary_class_override, :body_class, :opts+ attr_reader :title, :align, :open, :variant, :summary_class_override, :summary_aria_label, :body_class, :opts# `:default` — bg-surface summary, no chrome on the `<details>`. Use# for inline expanders that sit inside a parent card (the summary@@ -25,20 +25,25 @@ class DS::Disclosure < DesignSystemComponent# the summary text (and optional chevron) via the `summary_content`# slot.#+ # `:bare` — like `:default` on the `<details>` element (`group` only),+ # but content is yielded without the in-flow body wrapper. Use for+ # popovers anchored with absolute/fixed positioning inside the panel+ # (e.g. goal/category color-icon pickers).+ ## In card / inline variants, callers should pass their own# `summary_content` slot; the built-in title rendering assumes the# `:default` shape.- # `body_class:` styles the wrapper around the disclosure body. Defaults- # to `mt-2` (the standard gap below the summary). Pass `nil`/`""` to drop- # it — e.g. when the body is an absolutely-positioned popover whose- # wrapper would otherwise add ~8px of normal-flow margin and shove- # siblings down on open (see `goals/_color_picker`).- def initialize(title: nil, align: "right", open: false, variant: :default, summary_class: nil, body_class: "mt-2", **opts)+ #+ # `body_class:` styles the wrapper around the disclosure body (ignored for+ # `:bare`, which renders no wrapper). Defaults to `mt-2` (the standard gap+ # below the summary). Pass `nil`/`""` to drop it on non-bare variants.+ def initialize(title: nil, align: "right", open: false, variant: :default, summary_class: nil, summary_aria_label: nil, body_class: "mt-2", **opts)@title = title@align = align.to_sym@open = open@variant = variant&.to_sym@summary_class_override = summary_class+ @summary_aria_label = summary_aria_label@body_class = body_class@opts = opts@@ -71,18 +76,21 @@ class DS::Disclosure < DesignSystemComponentcase variantwhen :card, :card_inset# Card variants: no bg on summary — the parent details *is* the- # surface. Keep cursor + focus-visible ring + flex baseline.- # Ring token matches `settings/provider_card.html.erb` (the- # established focus pattern on container cards).+ # surface. Keep cursor + focus ring + flex baseline."list-none cursor-pointer focus-ring rounded-xl"when :inline# Inline variant: no surface, no padding — the summary reads as# plain text-link copy. Caller markup (text + optional chevron)- # provides the visual. Keep cursor + focus-visible ring + matching- # alpha-black-300 token used by the card variants for consistency.+ # provides the visual."list-none cursor-pointer focus-ring rounded-sm"+ when :bare+ "list-none cursor-pointer focus-ring"else"px-3 py-2 rounded-xl cursor-pointer flex items-center justify-between bg-surface focus-ring min-h-11"endend++ def summary_aria_attrs+ summary_aria_label.present? ? { label: summary_aria_label } : {}+ endenddiff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex 161015e760..2f1a1cbaa8 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -6,7 +6,10 @@ class CategoriesController < ApplicationControllerdef index@categories = Current.family.categories.alphabetically_by_hierarchy.to_a@category_groups = Category::Group.for(@categories)- @category_ids_with_transactions = category_ids_with_transactions(@categories)+ @category_ids_with_transactions = Category.ids_with_transactions(+ family: Current.family,+ category_ids: @categories.map(&:id)+ )render layout: "settings"end@@ -125,17 +128,6 @@ class CategoriesController < ApplicationControllerparams.permit(:target_id, source_ids: [])end- def category_ids_with_transactions(categories)- category_ids = categories.map(&:id)- return {} if category_ids.empty?-- Current.family.transactions- .where(category_id: category_ids)- .distinct- .pluck(:category_id)- .index_with(true)- end-def record_error_message(error)record = error.respond_to?(:record) ? error.record : nilrecord&.errors&.full_messages&.to_sentence.presence || error.messagediff --git a/app/javascript/controllers/color_icon_picker_controller.js b/app/javascript/controllers/color_icon_picker_controller.jsindex a208ba969f..59e321d63f 100644--- a/app/javascript/controllers/color_icon_picker_controller.js+++ b/app/javascript/controllers/color_icon_picker_controller.js@@ -152,10 +152,10 @@ export default class extends Controller {"Poor contrast, choose darker color or auto-adjust.",);- this.validationMessageTarget.classList.remove("hidden");+ this.showFlex(this.validationMessageTarget);} else {this.colorInputTarget.setCustomValidity("");- this.validationMessageTarget.classList.add("hidden");+ this.hideFlex(this.validationMessageTarget);}}@@ -226,7 +226,7 @@ export default class extends Controller {showPaletteSection() {this.initPicker();this.colorsSectionTarget.classList.add("hidden");- this.paletteSectionTarget.classList.remove("hidden");+ this.showFlex(this.paletteSectionTarget);this.pickerSectionTarget.classList.remove("hidden");this.updatePopupPosition();this.picker.show();@@ -234,7 +234,7 @@ export default class extends Controller {showColorsSection() {this.colorsSectionTarget.classList.remove("hidden");- this.paletteSectionTarget.classList.add("hidden");+ this.hideFlex(this.paletteSectionTarget);this.pickerSectionTarget.classList.add("hidden");this.updatePopupPosition()if (this.picker) {@@ -256,6 +256,16 @@ export default class extends Controller {}};+ showFlex(element) {+ element.classList.remove("hidden");+ element.classList.add("flex");+ }++ hideFlex(element) {+ element.classList.add("hidden");+ element.classList.remove("flex");+ }+updatePopupPosition() {const popup = this.popupTarget;popup.style.top = "";diff --git a/app/models/category.rb b/app/models/category.rbindex fdc25dd0a9..7bad10cd51 100644--- a/app/models/category.rb+++ b/app/models/category.rb@@ -137,6 +137,17 @@ class Category < ApplicationRecordendclass << self+ def ids_with_transactions(family:, category_ids:)+ category_ids = Array(category_ids).compact+ return {} if category_ids.empty?++ family.transactions+ .where(category_id: category_ids)+ .distinct+ .pluck(:category_id)+ .index_with(true)+ end+def suggested_icon(name)name_down = name.to_s.downcase@@ -284,9 +295,7 @@ class Category < ApplicationRecordenddef inherit_color_from_parent- if subcategory?- self.color = parent.color- end+ self.color = parent.color if subcategory? && parentenddef replace_and_destroy!(replacement)@@ -297,15 +306,22 @@ class Category < ApplicationRecordenddef parent?- subcategories.any?+ if association(:subcategories).loaded?+ subcategories.any?+ else+ subcategories.exists?+ endenddef subcategory?- parent.present?+ parent_id.present? && parent.present?enddef name_with_parent- subcategory? ? "#{parent.name} > #{name}" : name+ return name unless subcategory?++ parent_name = parent&.name+ parent_name.present? ? "#{parent_name} > #{name}" : nameenddef display_name@@ -333,7 +349,7 @@ class Category < ApplicationRecordprivatedef category_level_limit- if (subcategory? && parent.subcategory?) || (parent? && subcategory?)+ if (subcategory? && parent&.subcategory?) || (parent? && subcategory?)errors.add(:parent, "can't have more than 2 levels of subcategories")endenddiff --git a/app/views/categories/_category.html.erb b/app/views/categories/_category.html.erbindex 1fbea37dc2..e110bfd722 100644--- a/app/views/categories/_category.html.erb+++ b/app/views/categories/_category.html.erb@@ -1,10 +1,8 @@-<%# locals: (category:, subcategories: nil, has_transactions: nil) %>-<% subcategories ||= category.subcategories.to_a %>-<% has_transactions = category.transactions.exists? if has_transactions.nil? %>+<%# locals: (category:, subcategories: [], has_transactions: false) %>-<div id="<%= dom_id(category) %>" class="flex items-center gap-3 px-4 pb-4 <%= "pt-4" unless category.subcategory? %> <%= "pb-4" unless subcategories.any? %> bg-container">+<div id="<%= dom_id(category) %>" class="flex items-center gap-3 px-4 pb-4 <%= "pt-4" unless category.parent_id.present? %> bg-container"><div class="flex min-w-0 flex-1 items-center gap-2.5" data-testid="category-content">- <% if category.subcategory? %>+ <% if category.parent_id.present? %><span style="color: <%= category.color %>"><%= icon "corner-down-right", size: "sm", color: "current", class: "ml-2" %></span>diff --git a/app/views/categories/_category_list_group.html.erb b/app/views/categories/_category_list_group.html.erbindex c498cb48a6..7ef2152f1e 100644--- a/app/views/categories/_category_list_group.html.erb+++ b/app/views/categories/_category_list_group.html.erb@@ -1,5 +1,12 @@-<%# locals: (title:, categories:, category_groups: nil, category_ids_with_transactions: nil) %>+<%# locals: (title:, categories:, family: nil, category_groups: nil, category_ids_with_transactions: nil) %><% category_groups ||= Category::Group.for(categories) %>+<% if category_ids_with_transactions.nil? %>+ <% category_ids_with_transactions = if categories.any? && family+ Category.ids_with_transactions(family: family, category_ids: categories.map(&:id))+ else+ {}+ end %>+<% end %><div class="rounded-xl bg-container-inset space-y-1 p-1"><div class="flex items-center gap-1.5 px-4 py-2 text-xs font-medium text-secondary uppercase">@@ -14,13 +21,13 @@<%= render "categories/category",category: group.category,subcategories: group.subcategories,- has_transactions: category_ids_with_transactions&.key?(group.category.id) %>+ has_transactions: category_ids_with_transactions.key?(group.category.id) %><% group.subcategories.each do |subcategory| %><%= render "categories/category",category: subcategory,subcategories: [],- has_transactions: category_ids_with_transactions&.key?(subcategory.id) %>+ has_transactions: category_ids_with_transactions.key?(subcategory.id) %><% end %><% unless idx == category_groups.count - 1 %>diff --git a/app/views/categories/_form.html.erb b/app/views/categories/_form.html.erbindex a462849030..b974d191d5 100644--- a/app/views/categories/_form.html.erb+++ b/app/views/categories/_form.html.erb@@ -7,6 +7,8 @@<%= render partial: "color_avatar", locals: { category: category } %><%= render DS::Disclosure.new(+ variant: :bare,+ summary_aria_label: t(".trigger_label"),summary_class: "cursor-pointer absolute -bottom-2 -right-2 flex justify-center items-center bg-surface-inset hover:bg-surface-inset-hover border-2 w-7 h-7 border-subdued rounded-full text-secondary",data: {color_icon_picker_target: "details",@@ -32,13 +34,13 @@<div class="w-6 h-6 rounded-full cursor-pointer peer-checked:ring-2 peer-checked:ring-offset-2 peer-checked:ring-blue-500" data-color-icon-picker-target="pickerBtn" style="background: conic-gradient(red,orange,yellow,lime,green,teal,cyan,blue,indigo,purple,magenta,pink,red)"></div></label></div>- <div class="flex gap-2 items-center hidden flex-col" data-color-icon-picker-target="paletteSection">+ <div class="hidden flex-col gap-2" data-color-icon-picker-target="paletteSection"><div class="flex gap-2 items-center w-full"><div class="w-6 h-6 p-4 rounded-full cursor-pointer" style="background-color: <%= category.color %>" data-color-icon-picker-target="colorPreview"></div><%= f.text_field :color, data: { color_icon_picker_target: "colorInput" }, inline: true, pattern: "^#[0-9A-Fa-f]{6}$" %><%= icon "palette", size: "2xl", data: { action: "click->color-icon-picker#toggleSections" } %></div>- <div data-color-icon-picker-target="validationMessage" class="hidden self-start flex gap-1 items-center text-xs text-destructive ">+ <div data-color-icon-picker-target="validationMessage" class="hidden self-start gap-1 items-center text-xs text-destructive"><span><%= t(".poor_contrast") %></span><button type="button" class="underline cursor-pointer" data-action="color-icon-picker#autoAdjust"><%= t(".auto_adjust") %></button></div>diff --git a/app/views/categories/index.html.erb b/app/views/categories/index.html.erbindex f5b13df1cf..e9dc57d16e 100644--- a/app/views/categories/index.html.erb+++ b/app/views/categories/index.html.erb@@ -31,6 +31,7 @@<%= render "categories/category_list_group",title: t(".categories"),categories: @categories,+ family: Current.family,category_groups: @category_groups,category_ids_with_transactions: @category_ids_with_transactions %></div>diff --git a/app/views/category/dropdowns/_row.html.erb b/app/views/category/dropdowns/_row.html.erbindex e7e3e2f6f1..8f133c14be 100644--- a/app/views/category/dropdowns/_row.html.erb+++ b/app/views/category/dropdowns/_row.html.erb@@ -24,7 +24,7 @@<% if is_selected %><%= icon("check") %><% end %></span>- <% if category.subcategory? %>+ <% if category.parent_id.present? %><%= icon("corner-down-right", size: "sm") %><% end %>diff --git a/app/views/goals/_color_picker.html.erb b/app/views/goals/_color_picker.html.erbindex 7840913943..e178db443e 100644--- a/app/views/goals/_color_picker.html.erb+++ b/app/views/goals/_color_picker.html.erb@@ -14,18 +14,15 @@<% end %></span>- <%# `body_class: nil` drops DS::Disclosure's default `mt-2` body wrapper:- the body here is an absolutely-positioned popover, so that wrapper's- normal-flow margin would otherwise push the form down ~8px on open. %><%= render DS::Disclosure.new(- body_class: nil,- summary_class: "list-none cursor-pointer absolute -bottom-1 -right-1 flex justify-center items-center bg-surface-inset hover:bg-surface-inset-hover border-2 w-6 h-6 border-subdued rounded-full text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-alpha-black-300",+ variant: :bare,+ summary_aria_label: t("goals.color_picker.trigger_label"),+ summary_class: "list-none cursor-pointer absolute -bottom-1 -right-1 flex justify-center items-center bg-surface-inset hover:bg-surface-inset-hover border-2 w-6 h-6 border-subdued rounded-full text-secondary",data: {color_icon_picker_target: "details",action: "mousedown->color-icon-picker#handleOutsideClick"- }) do |disclosure| %>- <% disclosure.with_summary_content do %>- <span class="sr-only"><%= t("goals.color_picker.trigger_label") %></span>+ }) do |d| %>+ <% d.with_summary_content do %><%= icon("pen", size: "xs") %><% end %>@@ -46,13 +43,13 @@<div class="w-6 h-6 rounded-full cursor-pointer peer-checked:ring-2 peer-checked:ring-offset-2 peer-checked:ring-alpha-black-500" data-color-icon-picker-target="pickerBtn" style="background: conic-gradient(red,orange,yellow,lime,green,teal,cyan,blue,indigo,purple,magenta,pink,red)"></div></label></div>- <div class="flex gap-2 items-center hidden flex-col" data-color-icon-picker-target="paletteSection">+ <div class="hidden flex-col gap-2" data-color-icon-picker-target="paletteSection"><div class="flex gap-2 items-center w-full"><div class="w-6 h-6 p-4 rounded-full cursor-pointer" style="background-color: <%= form.object.color %>" data-color-icon-picker-target="colorPreview"></div><%= form.text_field :color, data: { color_icon_picker_target: "colorInput" }, inline: true, pattern: "^#[0-9A-Fa-f]{6}$" %><%= icon "palette", size: "2xl", data: { action: "click->color-icon-picker#toggleSections" } %></div>- <div data-color-icon-picker-target="validationMessage" class="hidden self-start flex gap-1 items-center text-xs text-destructive">+ <div data-color-icon-picker-target="validationMessage" class="hidden self-start gap-1 items-center text-xs text-destructive"><span><%= t("goals.color_picker.poor_contrast") %></span><button type="button" class="underline cursor-pointer" data-action="color-icon-picker#autoAdjust"><%= t("goals.color_picker.auto_adjust") %></button></div>diff --git a/config/locales/views/categories/ca.yml b/config/locales/views/categories/ca.ymlindex f57ac01e7c..275c6b6b79 100644--- a/config/locales/views/categories/ca.yml+++ b/config/locales/views/categories/ca.yml@@ -15,6 +15,7 @@ ca:edit:edit: Edita la categoriaform:+ trigger_label: Tria color i iconacolor: Coloricon: Iconaname_label: Nomdiff --git a/config/locales/views/categories/en.yml b/config/locales/views/categories/en.ymlindex 18ae3170ed..7f985e4183 100644--- a/config/locales/views/categories/en.yml+++ b/config/locales/views/categories/en.yml@@ -17,6 +17,7 @@ en:name_label: Nameunassigned: "(unassigned)"parent_category_label: "Parent category (optional)"+ trigger_label: Choose color and iconcolor: Coloricon: Iconauto_adjust: auto-adjust.diff --git a/config/locales/views/categories/fr.yml b/config/locales/views/categories/fr.ymlindex 336c45b6fd..398a25405e 100644--- a/config/locales/views/categories/fr.yml+++ b/config/locales/views/categories/fr.yml@@ -16,6 +16,7 @@ fr:edit: Éditer la catégorieform:auto_adjust: réglage automatique.+ trigger_label: Choisir la couleur et l'icônecolor: Couleuricon: Icônename_label: Nomdiff --git a/config/locales/views/categories/hu.yml b/config/locales/views/categories/hu.ymlindex a10c00072f..1410c25fd7 100644--- a/config/locales/views/categories/hu.yml+++ b/config/locales/views/categories/hu.yml@@ -17,6 +17,7 @@ hu:name_label: Névunassigned: "(nincs hozzárendelve)"parent_category_label: "Szülőkategória (nem kötelező)"+ trigger_label: Szín és ikon választásacolor: Színicon: Ikonpoor_contrast: "Gyenge kontraszt, válassz sötétebb színt vagy"diff --git a/config/locales/views/categories/it.yml b/config/locales/views/categories/it.ymlindex 2818832190..d91281cc9a 100644--- a/config/locales/views/categories/it.yml+++ b/config/locales/views/categories/it.yml@@ -17,6 +17,7 @@ it:name_label: Nomeunassigned: "(non assegnata)"parent_category_label: "Categoria genitore (opzionale)"+ trigger_label: Scegli colore e iconacolor: Coloreicon: Iconaauto_adjust: adattamento automatico.diff --git a/config/locales/views/categories/ru.yml b/config/locales/views/categories/ru.ymlindex 6ee56a8860..d8e381f591 100644--- a/config/locales/views/categories/ru.yml+++ b/config/locales/views/categories/ru.yml@@ -16,6 +16,7 @@ ru:edit: Редактировать категориюform:auto_adjust: авто-настройка.+ trigger_label: Выбрать цвет и иконкуcolor: Цветicon: Иконкаname_label: Названиеdiff --git a/config/locales/views/categories/vi.yml b/config/locales/views/categories/vi.ymlindex 596f848d88..63439dcbcf 100644--- a/config/locales/views/categories/vi.yml+++ b/config/locales/views/categories/vi.yml@@ -17,6 +17,7 @@ vi:name_label: Tênunassigned: "(chưa gán)"parent_category_label: "Danh mục cha (tùy chọn)"+ trigger_label: Chọn màu và biểu tượngcolor: Màu sắcicon: Biểu tượngauto_adjust: tự động điều chỉnh.diff --git a/config/locales/views/categories/zh-CN.yml b/config/locales/views/categories/zh-CN.ymlindex 0e323090ec..26a7decb5b 100644--- a/config/locales/views/categories/zh-CN.yml+++ b/config/locales/views/categories/zh-CN.yml@@ -17,6 +17,7 @@ zh-CN:name_label: 名称unassigned: (未分配)parent_category_label: 父分类(可选)+ trigger_label: 选择颜色和图标color: 颜色icon: 图标auto_adjust: 自动调整。diff --git a/test/components/DS/disclosure_test.rb b/test/components/DS/disclosure_test.rbindex b8154a49f2..583c7f9d26 100644--- a/test/components/DS/disclosure_test.rb+++ b/test/components/DS/disclosure_test.rb@@ -1,6 +1,17 @@require "test_helper"class DS::DisclosureTest < ViewComponent::TestCase+ test "bare variant yields panel content without mt-2 wrapper" do+ render_inline(DS::Disclosure.new(variant: :bare, summary_class: "cursor-pointer")) do |disclosure|+ disclosure.with_summary_content { "Toggle" }+ "Panel"+ end++ assert page.has_css?("details.group")+ assert page.has_text?("Panel")+ assert_no_match(/<div class="mt-2">/, rendered_content)+ end+test "body wrapper defaults to an mt-2 margin" dorender_inline(DS::Disclosure.new(title: "More", open: true)) { "body text" }diff --git a/test/components/previews/disclosure_component_preview.rb b/test/components/previews/disclosure_component_preview.rbindex 51b9a8a004..77f85b0b87 100644--- a/test/components/previews/disclosure_component_preview.rb+++ b/test/components/previews/disclosure_component_preview.rb@@ -10,4 +10,15 @@ class DisclosureComponentPreview < ViewComponent::Previewcontent_tag(:p, "Sample disclosure content", class: "text-sm")endend++ # @display container_classes max-w-[400px]+ def bare+ render DS::Disclosure.new(variant: :bare, open: true, summary_class: "cursor-pointer") do |disclosure|+ disclosure.with_summary_content do+ content_tag(:span, "Edit", class: "text-sm")+ end++ content_tag(:p, "Absolutely positioned panels should use the bare variant.", class: "text-sm absolute mt-2")+ end+ endenddiff --git a/test/models/category_test.rb b/test/models/category_test.rbindex 0f993bb203..a12b9790aa 100644--- a/test/models/category_test.rb+++ b/test/models/category_test.rb@@ -43,6 +43,20 @@ class CategoryTest < ActiveSupport::TestCaseassert_equal subcategory, transaction.reload.categoryend+ test "invalid parent_id does not raise during validation" do+ category = Category.new(+ name: "Orphan Subcategory",+ color: "#000000",+ lucide_icon: "folder",+ family: @family,+ parent_id: SecureRandom.uuid+ )++ assert_nothing_raised { category.valid? }+ assert_not category.subcategory?+ assert_nil category.parent+ end+test "subcategory can only be one level deep" docategory = categories(:subcategory)@@ -127,4 +141,22 @@ class CategoryTest < ActiveSupport::TestCaseassert_includes category.errors[:color], "is invalid"endend++ test "ids_with_transactions returns a lookup hash for categorized transactions" do+ category = categories(:food_and_drink)+ transaction = Transaction.create!(category: category)+ Entry.create!(+ account: accounts(:depository),+ entryable: transaction,+ name: "Lookup transaction",+ date: Date.current,+ amount: 10,+ currency: "USD"+ )++ lookup = Category.ids_with_transactions(family: @family, category_ids: [ category.id, 0 ])++ assert lookup.key?(category.id)+ assert_not lookup.key?(0)+ endenddiff --git a/test/system/accounts_test.rb b/test/system/accounts_test.rbindex 87c544de48..5bb7740eb1 100644--- a/test/system/accounts_test.rb+++ b/test/system/accounts_test.rb@@ -173,20 +173,20 @@ class AccountsTest < ApplicationSystemTestCaseassert_equal notes, created_account[:notes]visit account_url(created_account)-- open_account_edit_dialog+ # Let the initial page (and any immediate Turbo morph) settle before+ # opening the edit dialog — same race as open_account_edit_dialog.+ assert_selector "h2", text: account_nameupdated_institution_name = "[system test] Updated Institution"updated_institution_domain = "updated.example.com"updated_notes = "Updated notes for #{accountable_type}"- fill_in "Account name", with: "Updated account name"- find("summary", text: "Additional details").click- fill_in "Institution name", with: updated_institution_name- fill_in "Institution domain", with: updated_institution_domain- fill_in "Notes", with: updated_notes- click_button "Update Account"- assert_selector "h2", text: "Updated account name"+ update_account_details(+ name: "Updated account name",+ institution_name: updated_institution_name,+ institution_domain: updated_institution_domain,+ notes: updated_notes+ )created_account.reloadassert_equal updated_institution_name, created_account[:institution_name]@@ -194,6 +194,34 @@ class AccountsTest < ApplicationSystemTestCaseassert_equal updated_notes, created_account[:notes]end+ # Fill + submit the account edit dialog, retrying when a Turbo morph+ # detaches nodes mid-interaction (Chrome: "Node with given id does not+ # belong to the document"). Mirrors open_account_edit_dialog.+ def update_account_details(name:, institution_name:, institution_domain:, notes:)+ 3.times do+ begin+ open_account_edit_dialog unless has_field?("Account name", wait: 0)++ fill_in "Account name", with: name+ unless has_field?("Institution name", wait: 0)+ find("summary", text: "Additional details").click+ end+ fill_in "Institution name", with: institution_name+ fill_in "Institution domain", with: institution_domain+ fill_in "Notes", with: notes+ click_button "Update Account"++ return if has_selector?("h2", text: name, wait: 2)+ rescue Selenium::WebDriver::Error::WebDriverError => e+ raise unless e.message.match?(+ /does not belong to the document|stale element reference/i,+ )+ end+ end++ assert_selector "h2", text: name+ end+def humanized_accountable(accountable_type)Accountable.from_type(accountable_type).singular_display_nameenddiff --git a/test/system/transactions_form_exchange_rate_test.rb b/test/system/transactions_form_exchange_rate_test.rbindex 4e611e881d..d521c5a720 100644--- a/test/system/transactions_form_exchange_rate_test.rb+++ b/test/system/transactions_form_exchange_rate_test.rb@@ -68,10 +68,8 @@ class TransactionsFormExchangeRateTest < ApplicationSystemTestCase# Wait for exchange rate container to become visibleassert_selector "[data-transaction-form-target='exchangeRateContainer']", visible: true- # Exchange rate field should be populated- exchange_rate_field = find("[data-transaction-form-target='exchangeRateField']")- assert_not_empty exchange_rate_field.value- assert_equal "1.27", exchange_rate_field.value+ # Exchange rate is fetched asynchronously — wait for the field value.+ assert_equal "1.27", wait_for_exchange_rate_value("1.27")endtest "exchange rate field is empty when rate not found" do@@ -100,18 +98,17 @@ class TransactionsFormExchangeRateTest < ApplicationSystemTestCase# Change to EURfind("select[data-money-field-target='currency']").find("option[value='EUR']").select_option- # Wait for EUR rate to load+ # Wait for EUR rate to load (async fetch)assert_selector "[data-transaction-form-target='exchangeRateContainer']", visible: true- first_rate = find("[data-transaction-form-target='exchangeRateField']").value- assert_equal "1.10", first_rate+ first_rate = wait_for_exchange_rate_value("1.10")# Change to GBPfind("select[data-money-field-target='currency']").find("option[value='GBP']").select_option- # Wait for GBP rate to be updated+ # Wait for the field to flip from EUR→GBP; reading immediately is flaky+ # because the previous value stays until the fetch completes.assert_selector "[data-transaction-form-target='exchangeRateContainer']", visible: true- second_rate = find("[data-transaction-form-target='exchangeRateField']").value- assert_equal "1.27", second_rate+ second_rate = wait_for_exchange_rate_value("1.27")# Rates should be differentassert_not_equal first_rate, second_rate@@ -135,6 +132,7 @@ class TransactionsFormExchangeRateTest < ApplicationSystemTestCase# Exchange rate shown (both USD and EUR exist, they differ)assert_selector "[data-transaction-form-target='exchangeRateContainer']", visible: true+ wait_for_exchange_rate_value("1.10")# Switch to EUR accountselect_ds("Account", eur_account)@@ -143,4 +141,11 @@ class TransactionsFormExchangeRateTest < ApplicationSystemTestCase# Exchange rate UI should hideassert_selector "[data-transaction-form-target='exchangeRateContainer']", visible: falseend++ private+ # JS sets the input's value property after an async fetch. Waiting on the+ # HTML value= attribute is unreliable, so filter the node by .value.+ def wait_for_exchange_rate_value(expected)+ find("[data-transaction-form-target='exchangeRateField']") { |node| node.value == expected }.value+ endenddiff --git a/test/views/categories/category_list_group_view_test.rb b/test/views/categories/category_list_group_view_test.rbindex 62d5a90017..7305ece0e3 100644--- a/test/views/categories/category_list_group_view_test.rb+++ b/test/views/categories/category_list_group_view_test.rb@@ -1,7 +1,7 @@require "test_helper"class CategoryListGroupViewTest < ActionView::TestCase- test "falls back to transaction existence checks when no lookup is provided" do+ test "loads transaction lookup in one query when no lookup is provided" docategory = categories(:food_and_drink)transaction = Transaction.create!(category: category)Entry.create!(@@ -15,10 +15,20 @@ class CategoryListGroupViewTest < ActionView::TestCasehtml = render(partial: "categories/category_list_group", locals: {title: "Categories",- categories: [ category ]+ categories: [ category ],+ family: category.family})assert_includes html, new_category_deletion_path(category)assert_not_includes html, "data-turbo-method=\"delete\""end++ test "renders with empty categories when no transaction lookup is provided" do+ assert_nothing_raised do+ render(partial: "categories/category_list_group", locals: {+ title: "Categories",+ categories: []+ })+ end+ endend