The personal finance app for everyone (by everyone)
Ruby
feat(transactions): suggest category from past transaction names (#3069)
Anthonyf539b1c7807f
diff --git a/app/assets/tailwind/application.css b/app/assets/tailwind/application.cssindex f37855f23a..07ab1f1de3 100644--- a/app/assets/tailwind/application.css+++ b/app/assets/tailwind/application.css@@ -46,6 +46,10 @@@apply bg-container text-primary w-full;}+ .hw-combobox__input {+ @apply text-sm;+ }+.hw-combobox__main__wrapper {@apply border-0 p-0 focus:border-0 ring-0 focus:ring-0 shadow-none focus:shadow-none focus-within:shadow-none;}diff --git a/app/components/DS/select.rb b/app/components/DS/select.rbindex 3c0ca1ab57..a5b1384022 100644--- a/app/components/DS/select.rb+++ b/app/components/DS/select.rb@@ -44,7 +44,7 @@ module DSenddef selected_item- items.find { |item| item[:value] == selected_value }+ items.find { |item| !item[:value].nil? && item[:value] == selected_value }end# Returns the color for a given item (used in :badge variant)diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rbindex 5925b14812..f1e5976435 100644--- a/app/controllers/transactions_controller.rb+++ b/app/controllers/transactions_controller.rb@@ -528,6 +528,19 @@ class TransactionsController < ApplicationControllerendend+ def name_suggestions+ unknown_names = LanguagesHelper::SUPPORTED_LOCALES.map { |locale| I18n.t("transactions.unknown_name", locale: locale) }+ transactions = Current.family.transactions.merge(Account.accessible_by(Current.user)).where.not(entries: { name: unknown_names })+ query = params[:q].to_s.strip++ @suggestions = if query.length < Transaction::MIN_LENGTH_FOR_NAME_SUGGESTION+ names = recent_transaction_names.select { |name| name.downcase.include?(query.downcase) }+ transactions.name_suggestions_for_names(names)+ else+ transactions.name_suggestions_for(query)+ end+ end+privatedef uncategorized_count_cache_key"transactions_uncategorized_count/v5/#{Current.family.id}/#{Current.user.id}/" \@@ -712,7 +725,6 @@ class TransactionsController < ApplicationController@categories = Current.family.categories.alphabetically_by_hierarchy.to_a@merchants = Current.family.available_merchants_for(Current.user).alphabetically.to_a@tags = Current.family.tags.alphabetically.to_a- @recent_transaction_names = recent_transaction_namesend# Autocomplete suggestions for the name field, only queried when thediff --git a/app/javascript/controllers/category_suggestion_controller.js b/app/javascript/controllers/category_suggestion_controller.jsnew file mode 100644index 0000000000..ebfefca4e6--- /dev/null+++ b/app/javascript/controllers/category_suggestion_controller.js@@ -0,0 +1,68 @@+import { Controller } from "@hotwired/stimulus"++// Applies the category most commonly used on a past transaction when the user picks+// that transaction's name from the description autocomplete, and clears it again if a+// later-picked name has no usual category of its own. A manual category pick always+// wins over the suggestion, even if the name field changes afterward.+export default class extends Controller {+ static targets = ["categoryField", "name"]++ connect() {+ // A category already present when the controller connects (e.g. prefilled from+ // duplicating an existing transaction) is a deliberate default — treat it the same+ // as a manual pick so suggestions never clobber it.+ this.userPickedCategory = this.#hasCategorySelection()+ this.applyingSuggestion = false+ }++ syncName(event) {+ // Async combobox options can arrive after submission. The visible free-text+ // value, including an intentional blank, is authoritative for the name.+ event.formData.set("entry[name]", this.nameTarget.value)+ }++ onCategorySelected(event) {+ if (this.applyingSuggestion) return+ if (!event.target.matches('[data-category-select-target="hiddenInput"]')) return++ this.userPickedCategory = true+ }++ onNameSuggestionSelected(event) {+ // Leaving the field after typing part of a name also fires a selection for the+ // highlighted option; only a name actually picked from the list carries a category.+ const { value, display } = event.detail+ if (!value || value !== display) return++ const option = event.target.querySelector(`[role="option"][data-value="${CSS.escape(value)}"]`)+ const categoryId = option?.querySelector("[data-category-id]")?.dataset.categoryId++ // A name with no usual category (categoryId undefined) still needs to clear a category+ // that was auto-applied for a previously selected name — otherwise it stays attached to+ // the new, unrelated name. #selectCategoryOption already leaves a manual pick untouched.+ this.#selectCategoryOption(categoryId || "")+ }++ #hasCategorySelection() {+ return !!this.#categoryHiddenInput()?.value+ }++ #categoryHiddenInput() {+ return this.hasCategoryFieldTarget+ ? this.categoryFieldTarget.querySelector('[data-category-select-target="hiddenInput"]')+ : null+ }++ #selectCategoryOption(categoryId) {+ if (this.userPickedCategory || !this.hasCategoryFieldTarget) return++ const option = this.categoryFieldTarget.querySelector(+ `[data-category-select-target="option"][data-category-id="${CSS.escape(String(categoryId))}"]`+ )+ if (!option) return++ this.applyingSuggestion = true+ option.click()+ this.applyingSuggestion = false+ }+}diff --git a/app/javascript/controllers/transaction_name_preview_controller.js b/app/javascript/controllers/transaction_name_preview_controller.jsindex e5fcfa8528..9a03f9a92f 100644--- a/app/javascript/controllers/transaction_name_preview_controller.js+++ b/app/javascript/controllers/transaction_name_preview_controller.js@@ -1,29 +1,11 @@import { Controller } from "@hotwired/stimulus";-// Two related jobs for the (optional) transaction name field:-//-// 1. Live-updates its placeholder to preview what the server-side fallback-// (Entry#set_default_name) will save if the field is left blank: category,-// then merchant. Only ever touches the placeholder, never the field's-// value, so it can't clobber anything the user typed -- and since-// placeholders aren't submitted, the preview can never drift from what-// actually gets saved as long as both follow the same order. There is no-// generic fallback for "neither is set": the field's original hint text-// comes back instead, since a name is still required in that case.-//-// 2. A keyboard- and mouse-accessible suggestion dropdown for recently used-// names, filtered as the user types (an ARIA combobox: the input keeps-// focus throughout, arrow keys move an active-descendant highlight,-// Enter/click applies it). This exists instead of a native <datalist>-// because iOS Safari doesn't render datalist suggestions for text inputs-// at all -- a plain <datalist> works on desktop but is silently a no-op-// there.+// Preview the server-side fallback without changing the submitted name.export default class extends Controller {- static targets = ["name", "suggestions", "suggestionOption"];+ static targets = ["name"];connect() {if (this.hasNameTarget) this.originalPlaceholder = this.nameTarget.placeholder;- this.activeIndex = -1;}update() {@@ -57,108 +39,4 @@ export default class extends Controller {const text = container?.querySelector(nameSelector)?.textContent.trim();return text || null;}-- showSuggestions() {- this.filterSuggestions();- }-- filterSuggestions() {- if (!this.hasSuggestionsTarget) return;-- const query = this.nameTarget.value.trim().toLowerCase();- let anyVisible = false;-- this.suggestionOptionTargets.forEach((option) => {- const matches = option.dataset.name.toLowerCase().includes(query);- option.classList.toggle("hidden", !matches);- if (matches) anyVisible = true;-- // Re-filtering can hide whichever option was previously highlighted- // by arrow-key navigation -- clear that stale highlight/ARIA state- // along with resetting activeIndex below, not just the index itself.- option.classList.remove("bg-container-inset");- option.setAttribute("aria-selected", "false");- });-- this.activeIndex = -1;- this.nameTarget.removeAttribute("aria-activedescendant");- this.suggestionsTarget.classList.toggle("hidden", !anyVisible);- this.nameTarget.setAttribute("aria-expanded", anyVisible ? "true" : "false");- }-- // Hiding on a delay (rather than immediately on blur) lets the- // mousedown-based selectSuggestion below still register as a click on- // the option before it disappears.- scheduleHideSuggestions() {- if (!this.hasSuggestionsTarget) return;-- this.hideTimeout = setTimeout(() => {- this.suggestionsTarget.classList.add("hidden");- this.activeIndex = -1;- this.nameTarget.setAttribute("aria-expanded", "false");- this.nameTarget.removeAttribute("aria-activedescendant");- }, 150);- }-- // Arrow keys move a highlighted "active descendant" without moving DOM- // focus off the input (so typing keeps working); Enter applies whichever- // option is highlighted; Escape closes the list.- handleKeydown(event) {- if (!this.hasSuggestionsTarget || this.suggestionsTarget.classList.contains("hidden")) return;-- const visible = this.visibleSuggestions;- if (visible.length === 0) return;-- if (event.key === "ArrowDown") {- event.preventDefault();- this.activeIndex = (this.activeIndex + 1) % visible.length;- this.highlightActive(visible);- } else if (event.key === "ArrowUp") {- event.preventDefault();- this.activeIndex = (this.activeIndex - 1 + visible.length) % visible.length;- this.highlightActive(visible);- } else if (event.key === "Enter" && this.activeIndex >= 0) {- event.preventDefault();- this.applySuggestion(visible[this.activeIndex]);- } else if (event.key === "Escape") {- this.suggestionsTarget.classList.add("hidden");- this.activeIndex = -1;- this.nameTarget.setAttribute("aria-expanded", "false");- this.nameTarget.removeAttribute("aria-activedescendant");- }- }-- get visibleSuggestions() {- return this.suggestionOptionTargets.filter((option) => !option.classList.contains("hidden"));- }-- highlightActive(visible) {- visible.forEach((option, index) => {- const active = index === this.activeIndex;- option.classList.toggle("bg-container-inset", active);- option.setAttribute("aria-selected", active ? "true" : "false");- });-- const activeOption = visible[this.activeIndex];- if (!activeOption) return;-- activeOption.scrollIntoView({ block: "nearest" });- this.nameTarget.setAttribute("aria-activedescendant", activeOption.id);- }-- selectSuggestion(event) {- event.preventDefault();- if (this.hideTimeout) clearTimeout(this.hideTimeout);-- this.applySuggestion(event.currentTarget);- }-- applySuggestion(option) {- this.nameTarget.value = option.dataset.name;- this.suggestionsTarget.classList.add("hidden");- this.activeIndex = -1;- this.nameTarget.setAttribute("aria-expanded", "false");- this.nameTarget.removeAttribute("aria-activedescendant");- this.nameTarget.focus();- }}diff --git a/app/models/transaction.rb b/app/models/transaction.rbindex 0684885de7..e414cc9298 100644--- a/app/models/transaction.rb+++ b/app/models/transaction.rb@@ -285,6 +285,64 @@ class Transaction < ApplicationRecordendend+ # Minimum characters typed before searching past transactions for name suggestions.+ MIN_LENGTH_FOR_NAME_SUGGESTION = 3++ # Past transaction names resembling the given query, each paired with the category most+ # commonly used for that exact name. Powers the "Libellé" autocomplete in the new+ # transaction form — call on a family-scoped relation, e.g. `family.transactions.name_suggestions_for(query)`.+ def self.name_suggestions_for(query, limit: 8)+ sanitized_query = query.to_s.strip+ return [] if sanitized_query.length < MIN_LENGTH_FOR_NAME_SUGGESTION++ # distinct(false) cancels any DISTINCT inherited from the caller's scope (e.g.+ # Account.accessible_by's left_joins(:account_shares).distinct) — Postgres rejects+ # SELECT DISTINCT combined with an ORDER BY expression absent from the select list.+ # Callers such as TransactionsController#name_suggestions merge in+ # Account.accessible_by, whose left_joins(:account_shares) fans out to one row per+ # share for accounts the current user owns (the owner predicate matches regardless of+ # which share row it's paired with) — so COUNT(*) below would over-count transactions+ # on any owned account shared with multiple family members. COUNT(DISTINCT+ # transactions.id) counts each transaction once no matter how the caller's scope joins.+ # Leading-wildcard ILIKE can't use index_entries_on_lower_name (a btree on+ # lower(name), which only accelerates prefix/exact matches) and falls back+ # to a scan — same tradeoff already accepted in EntrySearch#search and+ # Entry.uncategorized_matching for the same reason. Revisit with a shared+ # pg_trgm index across all three call sites if this becomes a bottleneck.+ matching_names = with_entry+ .distinct(false)+ .where("entries.name ILIKE ?", "%#{sanitize_sql_like(sanitized_query)}%")+ .group("entries.name")+ .order(Arel.sql("COUNT(DISTINCT transactions.id) DESC"))+ .limit(limit)+ .pluck(Arel.sql("entries.name"))++ name_suggestions_for_names(matching_names)+ end++ def self.name_suggestions_for_names(matching_names)+ return [] if matching_names.empty?++ # Winning (most-used) category_id per name, in one grouped query. Rows are ordered so+ # that for each name, its highest-count category_id comes first — the `||=` below then+ # keeps only that first (winning) row per name, avoiding a query per name.+ category_id_by_name = {}+ with_entry+ .distinct(false)+ .where(entries: { name: matching_names })+ .where.not(category_id: nil)+ .group("entries.name", :category_id)+ .order(Arel.sql("entries.name ASC, COUNT(DISTINCT transactions.id) DESC"))+ .pluck(Arel.sql("entries.name"), :category_id)+ .each { |name, category_id| category_id_by_name[name] ||= category_id }++ categories_by_id = Category.where(id: category_id_by_name.values.uniq).index_by(&:id)++ matching_names.map do |name|+ Transaction::NameSuggestion.new(name: name, category: categories_by_id[category_id_by_name[name]])+ end+ end+# Overarching grouping method for all transfer-type transactionsdef transfer?TRANSFER_KINDS.include?(kind)diff --git a/app/models/transaction/name_suggestion.rb b/app/models/transaction/name_suggestion.rbnew file mode 100644index 0000000000..32f8c888c9--- /dev/null+++ b/app/models/transaction/name_suggestion.rb@@ -0,0 +1,9 @@+class Transaction::NameSuggestion+ include ActiveModel::Model++ attr_accessor :name, :category++ def to_combobox_display+ name+ end+enddiff --git a/app/views/transactions/_combobox_name_suggestion.turbo_stream.erb b/app/views/transactions/_combobox_name_suggestion.turbo_stream.erbnew file mode 100644index 0000000000..9e300cf0ee--- /dev/null+++ b/app/views/transactions/_combobox_name_suggestion.turbo_stream.erb@@ -0,0 +1,7 @@+<%# locals: (combobox_name_suggestion:, combobox_display:, combobox_value:) %>+<div class="flex items-center justify-between gap-2 w-full" data-category-id="<%= combobox_name_suggestion.category&.id %>">+ <span class="truncate text-sm text-primary"><%= combobox_name_suggestion.name %></span>+ <% if combobox_name_suggestion.category %>+ <%= render partial: "categories/badge", formats: [ :html ], locals: { category: combobox_name_suggestion.category } %>+ <% end %>+</div>diff --git a/app/views/transactions/_form.html.erb b/app/views/transactions/_form.html.erbindex 776ec0cfce..ad31ff6821 100644--- a/app/views/transactions/_form.html.erb+++ b/app/views/transactions/_form.html.erb@@ -1,7 +1,7 @@-<%# locals: (entry:, account_currencies:, manual_accounts:, categories:, merchants:, tags:, recent_transaction_names: []) %>+<%# locals: (entry:, account_currencies:, manual_accounts:, categories:, merchants:, tags:) %><% auto_generate_names = Current.family.auto_generate_transaction_names? %>-<%= styled_form_with model: entry, url: transactions_path, class: "space-y-4", data: { controller: auto_generate_names ? "transaction-form transaction-name-preview" : "transaction-form", action: "turbo:before-cache@document->transaction-form#refreshIdempotencyKey pageshow@window->transaction-form#refreshIdempotencyKeyIfPersisted", transaction_form_exchange_rate_url_value: exchange_rate_path, transaction_form_account_currencies_value: account_currencies.to_json } do |f| %>+<%= styled_form_with model: entry, url: transactions_path, class: "space-y-4", data: { controller: auto_generate_names ? "transaction-form transaction-name-preview category-suggestion" : "transaction-form category-suggestion", action: "formdata->category-suggestion#syncName hw-combobox:selection->category-suggestion#onNameSuggestionSelected turbo:before-cache@document->transaction-form#refreshIdempotencyKey pageshow@window->transaction-form#refreshIdempotencyKeyIfPersisted", transaction_form_exchange_rate_url_value: exchange_rate_path, transaction_form_account_currencies_value: account_currencies.to_json } do |f| %><% if entry.errors.any? %><%= render "shared/form_errors", model: entry %><% end %>@@ -25,38 +25,15 @@</section><section class="space-y-2">- <div class="relative">- <%= f.text_field :name, label: t(".description"),- placeholder: auto_generate_names ? t(".description_placeholder_optional") : t(".description_placeholder"),- required: !auto_generate_names,- autocomplete: "off",- role: (auto_generate_names && recent_transaction_names.present? ? "combobox" : nil),- "aria-autocomplete": (auto_generate_names && recent_transaction_names.present? ? "list" : nil),- "aria-expanded": (auto_generate_names && recent_transaction_names.present? ? "false" : nil),- "aria-controls": (auto_generate_names && recent_transaction_names.present? ? "transaction_name_suggestions" : nil),- data: {- transaction_name_preview_target: "name",- action: "input->transaction-name-preview#filterSuggestions focus->transaction-name-preview#showSuggestions blur->transaction-name-preview#scheduleHideSuggestions keydown->transaction-name-preview#handleKeydown"- } %>-- <% if auto_generate_names && recent_transaction_names.present? %>- <ul id="transaction_name_suggestions"- role="listbox"- class="absolute z-50 p-1.5 w-full min-w-48 max-h-64 overflow-auto rounded-lg shadow-lg bg-container mt-1.5 hidden"- data-transaction-name-preview-target="suggestions">- <% recent_transaction_names.each_with_index do |name, index| %>- <li id="transaction_name_suggestion_<%= index %>"- role="option"- aria-selected="false"- data-transaction-name-preview-target="suggestionOption"- data-name="<%= name %>"- data-action="mousedown->transaction-name-preview#selectSuggestion"- class="flex items-center gap-2 w-full px-3 py-1.5 text-sm rounded-lg cursor-pointer hover:bg-container-inset-hover">- <%= name %>- </li>- <% end %>- </ul>- <% end %>+ <div class="form-field combobox">+ <%= f.combobox :name,+ name_suggestions_transactions_path,+ free_text: true,+ autocomplete: :list,+ label: t(".description"),+ placeholder: auto_generate_names ? t(".description_placeholder_optional") : t(".description_placeholder"),+ required: !auto_generate_names,+ input: { data: { transaction_name_preview_target: "name", category_suggestion_target: "name" } } %></div><% if @entry.account_id %>@@ -72,15 +49,17 @@amount_data: { transaction_form_target: "amount", action: "input->transaction-form#onAmountChange" },currency_data: { transaction_form_target: "currency", action: "change->transaction-form#onCurrencyChange" } %>- <%= f.fields_for :entryable do |ef| %>- <%= render DS::CategorySelect.new(- form: ef,- categories: categories,- selected_id: ef.object.category_id,- blank_label: t(".category_prompt"),- locked: Current.family.categories_locked?- ) %>- <% end %>+ <div data-category-suggestion-target="categoryField" data-action="change->category-suggestion#onCategorySelected">+ <%= f.fields_for :entryable do |ef| %>+ <%= render DS::CategorySelect.new(+ form: ef,+ categories: categories,+ selected_id: ef.object.category_id,+ blank_label: t(".category_prompt"),+ locked: Current.family.categories_locked?+ ) %>+ <% end %>+ </div><%= f.date_field :date,label: t(".date"),diff --git a/app/views/transactions/name_suggestions.turbo_stream.erb b/app/views/transactions/name_suggestions.turbo_stream.erbnew file mode 100644index 0000000000..8d67e03c91--- /dev/null+++ b/app/views/transactions/name_suggestions.turbo_stream.erb@@ -0,0 +1,3 @@+<%= async_combobox_options @suggestions,+ value: :name,+ render_in: { partial: "transactions/combobox_name_suggestion" } %>diff --git a/app/views/transactions/new.html.erb b/app/views/transactions/new.html.erbindex 6ae791d5d8..1e13162cd2 100644--- a/app/views/transactions/new.html.erb+++ b/app/views/transactions/new.html.erb@@ -7,7 +7,6 @@manual_accounts: @manual_accounts,categories: @categories,merchants: @merchants,- tags: @tags,- recent_transaction_names: @recent_transaction_names %>+ tags: @tags %><% end %><% end %>diff --git a/config/routes.rb b/config/routes.rbindex 5bcedf4899..ed5478015d 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -571,6 +571,7 @@ Rails.application.routes.draw docollection dodelete :clear_filter+ get :name_suggestionsendmember dodiff --git a/test/components/DS/select_test.rb b/test/components/DS/select_test.rbindex f3011bc71e..4b50fa708c 100644--- a/test/components/DS/select_test.rb+++ b/test/components/DS/select_test.rb@@ -46,4 +46,36 @@ class DS::SelectTest < ViewComponent::TestCaseassert_nil blank_item[:object]assert_not select.child?(blank_item)end++ test "falls back to the placeholder, not the include_blank item's own label, when nothing is selected" do+ render_inline DS::Select.new(+ form: form_builder_for(Category.new, "category"),+ method: :parent_id,+ items: [ { value: 1, label: "Groceries" } ],+ selected: nil,+ placeholder: "Select a Category",+ include_blank: "(none)"+ )++ assert_selector "button#parent_id_trigger", text: "Select a Category"+ refute_selector "button#parent_id_trigger", text: "(none)"+ end++ test "shows the selected item's label when a real item is selected" do+ render_inline DS::Select.new(+ form: form_builder_for(Category.new, "category"),+ method: :parent_id,+ items: [ { value: 1, label: "Groceries" } ],+ selected: 1,+ placeholder: "Select a Category",+ include_blank: "(none)"+ )++ assert_selector "button#parent_id_trigger", text: "Groceries"+ end++ private+ def form_builder_for(object, name)+ StyledFormBuilder.new(name, object, vc_test_controller.view_context, {})+ endenddiff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex 9224644353..c0f7fcd37f 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -387,7 +387,7 @@ class TransactionsControllerTest < ActionDispatch::IntegrationTest)create_transaction(account: private_account, name: "Private Merchant XYZ")- get new_transaction_url+ get name_suggestions_transactions_url, as: :turbo_streamassert_response :successassert_no_match "Private Merchant XYZ", response.body@@ -399,7 +399,7 @@ class TransactionsControllerTest < ActionDispatch::IntegrationTestcreate_transaction(account: @entry.account, name: I18n.t("transactions.unknown_name", locale: :en))create_transaction(account: @entry.account, name: I18n.t("transactions.unknown_name", locale: :de))- get new_transaction_url+ get name_suggestions_transactions_url, as: :turbo_streamassert_response :successassert_no_match I18n.t("transactions.unknown_name", locale: :de), response.body@@ -420,6 +420,59 @@ class TransactionsControllerTest < ActionDispatch::IntegrationTestassert_equal 2.days.ago.to_date, @entry.reload.dateend+ test "name_suggestions returns matching past transaction names with their usual category" do+ get name_suggestions_transactions_url(q: "Starbucks"), as: :turbo_stream++ assert_response :success+ assert_match "Starbucks", response.body+ assert_match "data-category-id=\"#{categories(:food_and_drink).id}\"", response.body+ end++ test "name_suggestions starts with recent names and categories when auto naming is enabled" do+ @entry.account.family.update!(auto_generate_transaction_names: true)++ get name_suggestions_transactions_url, as: :turbo_stream++ assert_response :success+ assert_match "Starbucks", response.body+ assert_match "data-category-id=\"#{categories(:food_and_drink).id}\"", response.body++ get name_suggestions_transactions_url(q: "zz"), as: :turbo_stream+ assert_no_match "Starbucks", response.body+ end++ test "name_suggestions does not load recent names when auto naming is disabled" do+ @entry.account.family.update!(auto_generate_transaction_names: false)++ get name_suggestions_transactions_url, as: :turbo_stream++ assert_response :success+ assert_no_match "Starbucks", response.body+ end++ test "name_suggestions returns no options when no past transaction matches" do+ get name_suggestions_transactions_url(q: "no such merchant"), as: :turbo_stream++ assert_response :success+ assert_no_match "no such merchant", response.body+ end++ test "name_suggestions only considers transactions from accounts accessible to the current user" do+ # accounts(:investment) is owned by family_admin and not shared with family_member+ create_transaction(account: accounts(:investment), name: "Private Yacht Purchase", category: categories(:income))++ sign_in users(:family_member)++ get name_suggestions_transactions_url(q: "Private Yacht"), as: :turbo_stream+ assert_response :success+ assert_no_match "Private Yacht", response.body++ # depository is shared with family_member, so its transactions remain suggestible+ get name_suggestions_transactions_url(q: "Starbucks"), as: :turbo_stream+ assert_response :success+ assert_match "Starbucks", response.body+ end+test "updates with transaction details" doassert_no_difference [ "Entry.count", "Transaction.count" ] dopatch transaction_url(@entry), params: {diff --git a/test/models/transaction_test.rb b/test/models/transaction_test.rbindex 7a02237403..dcf2345c1b 100644--- a/test/models/transaction_test.rb+++ b/test/models/transaction_test.rb@@ -478,6 +478,79 @@ class TransactionTest < ActiveSupport::TestCaseassert_equal [ tags(:one).id, tags(:two).id ].sort, transaction.reload.tag_ids.sortend+ test "name_suggestions_for ranks names and each name's category by frequency" do+ family = families(:dylan_family)+ account = accounts(:depository)+ # entries(:transaction) is named "Starbucks" and its transaction (transactions(:one)) is categorized as food_and_drink++ # "Starbucks" ends up more frequent than "Star Market", and within "Starbucks",+ # food_and_drink ends up more frequent than its one-off income-categorized occurrence.+ 2.times { create_transaction(name: "Starbucks", account: account, category: categories(:food_and_drink)) }+ create_transaction(name: "Starbucks", account: account, category: categories(:income))+ create_transaction(name: "Star Market", account: account, category: categories(:income))++ suggestions = family.transactions.name_suggestions_for("star")++ assert_equal [ "Starbucks", "Star Market" ], suggestions.map(&:name)+ assert_equal categories(:food_and_drink), suggestions.first.category+ assert_equal categories(:income), suggestions.second.category+ end++ test "name_suggestions_for counts each transaction once when the caller scope joins account_shares" do+ # TransactionsController#name_suggestions calls this via+ # `family.transactions.merge(Account.accessible_by(user))`. Account.accessible_by does+ # left_joins(:account_shares), and for an account the user owns, its WHERE predicate+ # matches every joined share row regardless of which share it is — so an owned account+ # shared with multiple family members fans out to multiple rows per transaction. Without+ # counting distinct transaction ids, that inflates a name's frequency by however many+ # times its account is shared, letting a rarely-used name outrank a genuinely common one.+ family = families(:dylan_family)+ owner = users(:family_admin)+ shared_account = accounts(:depository) # owned by family_admin; already shared with family_member (fixture)+ unshared_account = accounts(:investment) # owned by family_admin; not shared with anyone++ 2.times do |i|+ extra_member = User.create!(+ family: family, email: "extra_member_#{i}@example.com", password: "password123456",+ first_name: "Extra", last_name: "Member #{i}", role: "member"+ )+ AccountShare.create!(account: shared_account, user: extra_member, permission: "read_only", include_in_finances: true)+ end+ # shared_account now has 3 account_shares rows (1 fixture + 2 created above), so its+ # accessible_by join fans out 3x — a single real transaction would inflate to a count of 3.++ create_transaction(name: "Fanout Rare", account: shared_account, category: categories(:food_and_drink))+ 2.times { create_transaction(name: "Fanout Common", account: unshared_account, category: categories(:income)) }++ suggestions = family.transactions+ .merge(Account.accessible_by(owner))+ .name_suggestions_for("Fanout")++ assert_equal [ "Fanout Common", "Fanout Rare" ], suggestions.map(&:name)+ end++ test "name_suggestions_for returns an empty array when the query is too short" do+ family = families(:dylan_family)+ assert_equal [], family.transactions.name_suggestions_for("st")+ assert_equal [], family.transactions.name_suggestions_for(" ")+ end++ test "name_suggestions_for returns an empty array when no past transaction matches" do+ family = families(:dylan_family)+ assert_equal [], family.transactions.name_suggestions_for("no such merchant")+ end++ test "name_suggestions_for caps results at 8" do+ family = families(:dylan_family)+ account = accounts(:depository)++ 9.times { |i| create_transaction(name: "Merchant #{i}", account: account) }++ suggestions = family.transactions.name_suggestions_for("Merchant")++ assert_equal 8, suggestions.size+ end+test "category_from finds categories still set by a given source" dofamily = families(:empty)account = family.accounts.create!(name: "Category from", balance: 0, currency: "USD", accountable: Depository.new)diff --git a/test/system/transaction_category_select_test.rb b/test/system/transaction_category_select_test.rbindex b9b421f082..3339bbdad4 100644--- a/test/system/transaction_category_select_test.rb+++ b/test/system/transaction_category_select_test.rb@@ -161,7 +161,7 @@ class TransactionCategorySelectTest < ApplicationSystemTestCasetest "Enter in the category search picks the match while categories are locked" do@user.family.update!(categories_locked: true)visit new_transaction_url(account_id: accounts(:depository).id)- fill_in "entry[name]", with: "Locked picker"+ fill_in "entry_name", with: "Locked picker"find("input[name='entry[amount]']").set("12.34")assert_no_difference "Entry.count" dodiff --git a/test/system/transaction_name_suggestions_test.rb b/test/system/transaction_name_suggestions_test.rbnew file mode 100644index 0000000000..f989c06a7e--- /dev/null+++ b/test/system/transaction_name_suggestions_test.rb@@ -0,0 +1,103 @@+require "application_system_test_case"++class TransactionNameSuggestionsTest < ApplicationSystemTestCase+ setup do+ @user = users(:family_admin)+ @user.family.update!(auto_sync_on_login: false, auto_generate_transaction_names: true)+ sign_in @user+ end++ test "recent and searched names share one keyboard-accessible picker with category autofill" do+ visit new_transaction_url(account_id: accounts(:depository).id)+ find("#entry_name").click+ assert_selector ".hw-combobox [role='option']", text: "Starbucks"+ assert_selector "input[role='combobox']", count: 1++ fill_in "entry_name", with: "Starb"+ assert_selector ".hw-combobox [role='option']", text: "Starbucks"+ assert_selector ".hw-combobox [role='option']", count: 1+ find("#entry_name").send_keys(:arrow_down, :enter)+ assert_field "entry_name", with: "Starbucks"+ assert_category categories(:food_and_drink)++ fill_in "entry_name", with: "My custom purchase"+ find("input[name='entry[amount]']").set("12.34")+ click_button "Add transaction"+ assert_text "Transaction created"+ entry = @user.family.entries.order(created_at: :desc).first+ assert_equal "My custom purchase", entry.name+ assert_equal categories(:food_and_drink), entry.entryable.category+ end++ test "blank names keep the live category and merchant preview and save the generated name" do+ visit new_transaction_url(account_id: accounts(:depository).id)+ select_starbucks+ fill_in "entry_name", with: ""+ choose_category categories(:food_and_drink)+ assert_selector "#entry_name[placeholder='Food & Drink']"+ assert_field "entry_name", with: ""+ assert_no_selector "#entry_name[required]"++ find("summary", text: /details/i).click+ find("[data-merchant-select-target='button']").click+ find("[data-merchant-select-target='option'][data-merchant-id='#{merchants(:amazon).id}']").click+ assert_selector "#entry_name[placeholder='Food & Drink - Amazon']"+ find("input[name='entry[amount]']").set("12.34")+ click_button "Add transaction"+ assert_text "Transaction created"+ assert_equal "Food & Drink - Amazon", @user.family.entries.order(created_at: :desc).first.name+ end++ test "manual keyboard category selection and clearing survive subsequent name suggestions" do+ visit new_transaction_url(account_id: accounts(:depository).id)+ find("[data-category-select-target='button']").click+ fill_in "Search categories", with: "Income"+ find_field("Search categories").send_keys(:enter)+ select_starbucks+ assert_category categories(:income)++ choose_category nil+ select_starbucks+ assert_category nil+ end++ test "a prefilled category is not overwritten and names remain required when auto naming is off" do+ @user.family.update!(auto_generate_transaction_names: false)+ transactions(:one).update!(category: categories(:income))+ visit new_transaction_url(duplicate_entry_id: transactions(:one).entry.id)+ assert_selector "#entry_name[required]"+ assert_category categories(:income)+ select_starbucks+ assert_category categories(:income)+ end++ test "mobile picker selects a name and category without a second suggestions menu" do+ page.current_window.resize_to(390, 844)+ visit new_transaction_url(account_id: accounts(:depository).id)+ find("#entry_name").click++ within "dialog.hw-combobox__dialog" do+ find("input[role='combobox']").set("Starb")+ find("[role='option']", text: "Starbucks").click+ end++ assert_field "entry_name", with: "Starbucks"+ assert_category categories(:food_and_drink)+ end++ private+ def select_starbucks+ fill_in "entry_name", with: "Starb"+ find(".hw-combobox [role='option']", text: "Starbucks").click+ assert_field "entry_name", with: "Starbucks"+ end++ def choose_category(category)+ find("[data-category-select-target='button']").click+ find("[data-category-select-target='option'][data-category-id='#{category&.id}']").click+ end++ def assert_category(category)+ assert_selector "[data-category-select-target='hiddenInput'][value='#{category&.id}']", visible: :all+ end+end