Files
sure/test/controllers/transactions/categorizes_controller_test.rb
Mikael Møller 0870ebb56b Add Quick Categorize Wizard (#1386)
* Add Quick Categorize Wizard (iteration 1)

Adds a step-by-step wizard for bulk-categorizing uncategorized transactions
and optionally creating auto-categorization rules, reducing friction after
connecting a new bank account.

New files:
- Transaction::Grouper abstraction + ByMerchantOrName strategy (groups by
  merchant name when present, falls back to entry name; sorted by count desc)
- Transactions::CategorizesController (GET show / POST create)
- Wizard view at app/views/transactions/categorizes/show.html.erb
- Stimulus categorize_controller.js (Enter-key-to-select-first)
- Tests for grouper and controller

Modified files:
- routes.rb: resource :categorize inside namespace :transactions
- transactions_controller.rb: expose @uncategorized_count to index
- transactions/index.html.erb: Categorize (N) button in header
- family.rb: uncategorized_transaction_count query
- rules_controller.rb: return_to param support for wizard → rule editor flow
- rules/_form.html.erb, rules/new.html.erb: pass return_to through form
- i18n: categorizes show/create keys + rules.create.success

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Quick Categorize Wizard — iteration 2 polish

Six improvements from live testing:

- Breadcrumb: Home > Transactions > Categorize
- Layout: category picker + confirmation dialog above transaction list
- Inline confirmation dialog: clicking a category pill shows a <dialog>
  summarising what will happen (N transactions → category, rule if checked)
  with Confirm and Cancel buttons — no redirect to rule editor
- Direct rule creation: rule created with active: true in the controller
  instead of redirecting to the rule editor; revert return_to plumbing from
  RulesController, rules/_form, rules/new, rules/en.yml
- Individual row assignment: per-row category <select> submits via
  PATCH /transactions/categorize/assign_entry and removes the row via
  Turbo Stream (assign_entry action + route)
- Enter key guard: selectFirst only fires when exactly 1 pill is visible
  after filtering

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Quick Categorize Wizard — iteration 3 reliability fixes and UX polish

- Fix Stimulus controller not loading: remove invalid `@hotwired/turbo` named
  import (not in importmap); use global `Turbo.renderStreamMessage` instead
- Fix Enter key submitting form with wrong category when search field is
  unfocused: move keydown listener to document so it fires regardless of focus
- Prevent Enter from submitting when multiple categories are visible
- Clear search filter after bulk category assignment (pill click or Enter),
  but not after individual row dropdown assignment
- Update group transaction count and total amount live as entries are assigned
  via row dropdown or partial bulk assignment
- Add turbo frames for remaining count and group summary so they update
  without a full page reload

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Quick categorization polish

* refactoring

* Remove unused GROUPS_PER_BATCH constant, fix ERB self-closing tags

Wizard only ever uses one group at a time so limit: 1 is correct and
more honest than fetching 20 and discarding 19. ERB linter fixes are
whitespace/void-element corrections with no functional change.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Move Categorize button into ... menu on transactions index

Reduces header clutter by putting it in the overflow menu at the bottom,
where it only appears when there are uncategorized transactions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Scope categorize wizard to accessible entries only

Fixes a security issue where users with restricted account access via
account sharing could view and categorize transactions from accounts
they cannot access through normal transaction flows.

- Pass Current.accessible_entries to Transaction::Grouper so the wizard
  only displays groups from accounts the user can see
- Use Current.accessible_entries on all write paths in create and
  assign_entry, matching the pattern in TransactionCategoriesController
- Refactor Grouper to accept an entries scope instead of a family object,
  keeping authorization concerns in the controller
- Add tests verifying inaccessible entries are hidden from the wizard
  and cannot be categorized via forged POST/PATCH params

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Clamp position param to >= 0 to guard against negative offset

Prevents ArgumentError from Array#drop when a negative position is
passed via a tampered query string or form value.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Surface rule creation failure and add accessible names to entry row

- Capture Rule.create_from_grouping! return value; set flash[:alert] when
  nil so users who checked "Create Rule" know it wasn't created (e.g. a
  duplicate already exists); stream the notification for partial updates
- Add aria-label to the per-row checkbox and category select in
  _entry_row so screen readers can identify which transaction each
  control belongs to

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Localize breadcrumb labels in categorizes controller

Follows the pattern used by FamilyExportsController and ImportsController.
Adds 'transactions' and 'categorize' keys to the breadcrumbs locale file.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add error handling to categorize controller fetch calls

Check response.ok before parsing the body and add .catch handlers
so network failures and non-2xx responses are logged rather than
silently swallowed. On assignment failure the per-row select is
reset to empty so the user can retry.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Scope preview_rule to accessible entries only

Entry.uncategorized_matching now accepts an entries scope instead of a
family object, matching the same pattern used for Transaction::Grouper.
The preview_rule action passes Current.accessible_entries so rule
previews respect account sharing permissions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Scope remaining count to accessible entries

Adds Entry.uncategorized_count(entries) following the same pattern as
uncategorized_matching. Replaces all three uses of
Current.family.uncategorized_transaction_count in the categorize
controller so the remaining-count badge reflects only the transactions
the current user can actually access and categorize.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Comments got separated from their function

* Remove quick-categorize-wizard dev notes

This was a planning document used during development, not intended
for the final branch.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Recompute remaining entries from server state after writes

Adds uncategorized_entries_for helper that reloads remaining entries
from the DB with a category_id IS NULL filter after each write, so
the partial-update Turbo Stream reflects server-side state rather than
trusting the client-provided remaining_ids. This handles the case where
a concurrent request has categorized one of the remaining entries
between page render and form submit.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Rename create_from_grouping! to create_from_grouping

The method rescues RecordInvalid and returns nil, which contradicts
the bang convention. Dropping the ! correctly signals that callers
should check the return value.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Clamp offset in grouper to guard against negative values

The controller already clamps position before passing it as offset,
but clamping in the grouper itself prevents ArgumentError from
Array#drop if the grouper is ever called directly with a negative offset.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Juan José Mata <jjmata@jjmata.com>
2026-04-07 11:24:50 +02:00

269 lines
9.0 KiB
Ruby

require "test_helper"
class Transactions::CategorizesControllerTest < ActionDispatch::IntegrationTest
include EntriesTestHelper
setup do
sign_in @user = users(:family_admin)
@family = @user.family
@account = accounts(:depository)
@category = categories(:food_and_drink)
# Clear entries for isolation
@family.accounts.each { |a| a.entries.delete_all }
end
# GET /transactions/categorize
test "show redirects with notice when nothing to categorize" do
get transactions_categorize_url
assert_redirected_to transactions_url
assert_match "categorized", flash[:notice]
end
test "show renders wizard when uncategorized transactions exist" do
create_transaction(account: @account, name: "Starbucks")
get transactions_categorize_url
assert_response :success
end
test "show renders the first group at position 0" do
2.times { create_transaction(account: @account, name: "Netflix") }
3.times { create_transaction(account: @account, name: "Starbucks") }
get transactions_categorize_url(position: 0)
assert_response :success
assert_select "h2", text: "Starbucks"
end
test "show at position 1 skips first group" do
3.times { create_transaction(account: @account, name: "Starbucks") }
2.times { create_transaction(account: @account, name: "Netflix") }
get transactions_categorize_url(position: 1)
assert_response :success
assert_select "h2", text: "Netflix"
end
test "show redirects when position exceeds available groups" do
create_transaction(account: @account, name: "Starbucks")
get transactions_categorize_url(position: 99)
assert_redirected_to transactions_url
end
test "requires authentication" do
sign_out
get transactions_categorize_url
assert_redirected_to new_session_url
end
# Account sharing authorization
test "show only groups entries from accounts accessible to the user" do
accessible_account = accounts(:depository) # shared with family_member (full_control)
inaccessible_account = accounts(:investment) # not shared with family_member
create_transaction(account: accessible_account, name: "Starbucks")
create_transaction(account: inaccessible_account, name: "Starbucks")
sign_in users(:family_member)
get transactions_categorize_url(position: 0)
assert_response :success
# Only 1 entry should appear in the group — the inaccessible account's entry is hidden
assert_select "input[name='entry_ids[]']", count: 1
end
test "create does not categorize entries from inaccessible accounts" do
inaccessible_account = accounts(:investment) # not shared with family_member
entry = create_transaction(account: inaccessible_account, name: "Starbucks")
sign_in users(:family_member)
post transactions_categorize_url,
params: {
position: 0,
grouping_key: "Starbucks",
entry_ids: [ entry.id ],
all_entry_ids: [ entry.id ],
category_id: @category.id
},
headers: { "Accept" => "text/vnd.turbo-stream.html" }
assert_nil entry.transaction.reload.category
end
test "assign_entry does not categorize an entry from an inaccessible account" do
inaccessible_account = accounts(:investment) # not shared with family_member
entry = create_transaction(account: inaccessible_account, name: "Starbucks")
sign_in users(:family_member)
patch assign_entry_transactions_categorize_url, params: {
entry_id: entry.id,
category_id: @category.id,
position: 0,
all_entry_ids: [ entry.id ]
}
assert_response :not_found
assert_nil entry.transaction.reload.category
end
# GET /transactions/categorize/preview_rule
test "preview_rule returns matching entries for a filter" do
create_transaction(account: @account, name: "Amazon Prime")
create_transaction(account: @account, name: "Amazon Music")
create_transaction(account: @account, name: "Starbucks")
get preview_rule_transactions_categorize_url(filter: "Amazon"),
headers: { "Accept" => "text/vnd.turbo-stream.html" }
assert_response :success
assert_includes response.body, "Amazon Prime"
assert_includes response.body, "Amazon Music"
assert_not_includes response.body, "Starbucks"
end
test "preview_rule returns empty list for blank filter" do
create_transaction(account: @account, name: "Amazon")
get preview_rule_transactions_categorize_url(filter: ""),
headers: { "Accept" => "text/vnd.turbo-stream.html" }
assert_response :success
assert_not_includes response.body, "Amazon"
end
test "preview_rule requires authentication" do
sign_out
get preview_rule_transactions_categorize_url(filter: "Amazon")
assert_redirected_to new_session_url
end
private
def sign_out
@user.sessions.each { |s| delete session_path(s) }
end
# POST /transactions/categorize
test "create categorizes selected entries and returns redirect stream when all assigned" do
entry = create_transaction(account: @account, name: "Starbucks")
post transactions_categorize_url,
params: {
position: 0,
grouping_key: "Starbucks",
entry_ids: [ entry.id ],
all_entry_ids: [ entry.id ],
category_id: @category.id
},
headers: { "Accept" => "text/vnd.turbo-stream.html" }
assert_response :success
assert_equal @category, entry.transaction.reload.category
assert_includes response.body, "action=\"redirect\""
end
test "create removes assigned rows and replaces remaining when partial assignment" do
entry1 = create_transaction(account: @account, name: "Starbucks")
entry2 = create_transaction(account: @account, name: "Starbucks")
post transactions_categorize_url,
params: {
position: 0,
grouping_key: "Starbucks",
entry_ids: [ entry1.id ],
all_entry_ids: [ entry1.id, entry2.id ],
category_id: @category.id
},
headers: { "Accept" => "text/vnd.turbo-stream.html" }
assert_response :success
assert_equal @category, entry1.transaction.reload.category
assert_nil entry2.transaction.reload.category
# Remove stream for categorized entry
assert_includes response.body, "categorize_entry_#{entry1.id}"
# Replace stream for remaining entry (re-checked)
assert_includes response.body, "categorize_entry_#{entry2.id}"
# No redirect stream — still in the group
assert_not_includes response.body, "action=\"redirect\""
end
test "create with create_rule param creates rule with name and type conditions" do
entry = create_transaction(account: @account, name: "Netflix", amount: 15)
assert_difference "@family.rules.count", 1 do
post transactions_categorize_url,
params: {
position: 0,
grouping_key: "Netflix",
transaction_type: "expense",
entry_ids: [ entry.id ],
all_entry_ids: [ entry.id ],
category_id: @category.id,
create_rule: "1"
},
headers: { "Accept" => "text/vnd.turbo-stream.html" }
end
rule = @family.rules.find_by(name: "Netflix")
assert_not_nil rule
assert rule.active
assert rule.conditions.any? { |c| c.condition_type == "transaction_name" && c.value == "Netflix" }
assert rule.conditions.any? { |c| c.condition_type == "transaction_type" && c.value == "expense" }
end
test "create falls back to html redirect without turbo stream header" do
entry = create_transaction(account: @account, name: "Starbucks")
post transactions_categorize_url, params: {
position: 0,
grouping_key: "Starbucks",
entry_ids: [ entry.id ],
all_entry_ids: [ entry.id ],
category_id: @category.id
}
assert_redirected_to transactions_categorize_url(position: 0)
assert flash[:notice].present?
end
# PATCH /transactions/categorize/assign_entry
test "assign_entry categorizes single entry and returns remove stream" do
entry = create_transaction(account: @account, name: "Starbucks")
other = create_transaction(account: @account, name: "Starbucks")
patch assign_entry_transactions_categorize_url, params: {
entry_id: entry.id,
category_id: @category.id,
position: 0,
all_entry_ids: [ entry.id, other.id ]
}
assert_response :success
assert_equal @category, entry.transaction.reload.category
assert_includes response.body, "categorize_entry_#{entry.id}"
assert_not_includes response.body, "action=\"redirect\""
end
test "assign_entry returns redirect stream when last entry in group" do
entry = create_transaction(account: @account, name: "Starbucks")
patch assign_entry_transactions_categorize_url, params: {
entry_id: entry.id,
category_id: @category.id,
position: 0,
all_entry_ids: [ entry.id ]
}
assert_response :success
assert_includes response.body, "action=\"redirect\""
end
end