The personal finance app for everyone (by everyone)
Ruby
Respect account share permissions in bulk edit and categorize (#4192)
GFRe211acf5d418
diff --git a/app/controllers/transactions/bulk_updates_controller.rb b/app/controllers/transactions/bulk_updates_controller.rbindex e90e47cd37..5711d88f7d 100644--- a/app/controllers/transactions/bulk_updates_controller.rb+++ b/app/controllers/transactions/bulk_updates_controller.rb@@ -4,26 +4,65 @@ class Transactions::BulkUpdatesController < ApplicationControllerdef create# Skip split parents from bulk update - update children instead- updated = Current.family- .entries- .excluding_split_parents- .where(id: bulk_update_params[:entry_ids])- .includes(:entryable)- .bulk_update!(bulk_update_params, update_tags: tags_provided?)+ scoped_params = family_scoped_bulk_update_params+ selected = Current.annotatable_entries+ .excluding_split_parents+ .where(id: bulk_update_params[:entry_ids])++ # Owners and full_control shares may change every field; read_write shares+ # may only annotate (notes, category, merchant, tags), as on a single entry.+ # Read-only and unshared accounts are left out entirely.+ rows = selected.pluck(:id, Account.writable_by_sql(Current.user))+ full_ids = rows.select(&:last).map(&:first).uniq+ annotate_ids = rows.map(&:first).uniq - full_ids++ updated = Entry.transaction do+ bulk_update_entries(full_ids, scoped_params) ++ bulk_update_entries(annotate_ids, scoped_params.slice(*AccountShare::ANNOTATE_ENTRY_ATTRIBUTES, *AccountShare::ANNOTATE_TRANSACTION_ATTRIBUTES))+ endredirect_back_or_to transactions_path, notice: "#{updated} transactions updated"endprivate+ def bulk_update_entries(entry_ids, attributes)+ return 0 if entry_ids.empty?++ Current.family.entries.where(id: entry_ids).includes(:entryable)+ .bulk_update!(attributes, update_tags: attributes.key?(:tag_ids))+ end+def bulk_update_paramsparams.require(:bulk_update).permit(:date, :notes, :name, :category_id, :merchant_id, entry_ids: [], tag_ids: [])end- # Check if tag_ids was explicitly provided in the request.- # This distinguishes between "user wants to update tags" vs "user didn't touch tags field".- def tags_provided?- bulk_update = params[:bulk_update]- bulk_update.respond_to?(:key?) && bulk_update.key?(:tag_ids)+ # Resolve category, merchant and tag IDs through the current family so IDs+ # belonging to another family are dropped instead of being attached.+ def family_scoped_bulk_update_params+ scoped = bulk_update_params.to_h.symbolize_keys++ if scoped[:category_id].present?+ scoped[:category_id] = Current.family.categories.where(id: scoped[:category_id]).pick(:id)+ end++ if scoped[:merchant_id].present?+ scoped[:merchant_id] = Current.family.available_merchants_for(Current.user).where(id: scoped[:merchant_id]).pick(:id)+ end++ if scoped.key?(:tag_ids)+ tag_ids = Array.wrap(scoped[:tag_ids]).reject(&:blank?)+ resolved = tag_ids.any? ? Current.family.tags.where(id: tag_ids).pluck(:id) : []++ # Tags were requested but none belong to this family: leave the entries'+ # tags alone instead of wiping them. An explicit empty list still clears.+ if tag_ids.any? && resolved.empty?+ scoped.delete(:tag_ids)+ else+ scoped[:tag_ids] = resolved+ end+ end++ scopedendenddiff --git a/app/controllers/transactions/categorizes_controller.rb b/app/controllers/transactions/categorizes_controller.rbindex f6b3c4049e..a2cc42ace4 100644--- a/app/controllers/transactions/categorizes_controller.rb+++ b/app/controllers/transactions/categorizes_controller.rb@@ -7,7 +7,7 @@ class Transactions::CategorizesController < ApplicationController]@position = [ params[:position].to_i, 0 ].maxgroups = Transaction::Grouper.strategy.call(- Current.accessible_entries,+ Current.annotatable_entries,limit: 1,offset: @position)@@ -28,10 +28,10 @@ class Transactions::CategorizesController < ApplicationControllerremaining_ids = all_entry_ids - entry_idscategory = Current.family.categories.find(params[:category_id])- entries = Current.accessible_entries.excluding_split_parents.where(id: entry_ids)+ entries = Current.annotatable_entries.excluding_split_parents.where(id: entry_ids)count = entries.bulk_update!({ category_id: category.id })- if params[:create_rule] == "1"+ if params[:create_rule] == "1" && (count.positive? || entry_ids.empty?)rule = Rule.create_from_grouping(Current.family,params[:grouping_key],@@ -75,7 +75,7 @@ class Transactions::CategorizesController < ApplicationControllerdef preview_rulefilter = params[:filter].to_s.striptransaction_type = params[:transaction_type].presence- entries = filter.present? ? Entry.uncategorized_matching(Current.accessible_entries, filter, transaction_type) : []+ entries = filter.present? ? Entry.uncategorized_matching(Current.annotatable_entries, filter, transaction_type) : []@categories = Current.family.categories.includes(:parent).alphabeticallyrender turbo_stream: [@@ -92,13 +92,13 @@ class Transactions::CategorizesController < ApplicationControllerenddef assign_entry- entry = Current.accessible_entries.excluding_split_parents.find(params[:entry_id])+ entry = Current.annotatable_entries.excluding_split_parents.find(params[:entry_id])category = Current.family.categories.find(params[:category_id])position = params[:position].to_iall_entry_ids = Array.wrap(params[:all_entry_ids]).reject(&:blank?)remaining_ids = all_entry_ids - [ entry.id.to_s ]- Current.accessible_entries.where(id: entry.id).bulk_update!({ category_id: category.id })+ Current.annotatable_entries.where(id: entry.id).bulk_update!({ category_id: category.id })remaining_entries = uncategorized_entries_for(remaining_ids)remaining_ids = remaining_entries.map { |e| e.id.to_s }@@ -120,12 +120,12 @@ class Transactions::CategorizesController < ApplicationControllerprivatedef uncategorized_count- Current.accessible_entries.uncategorized_transactions.count+ Current.annotatable_entries.uncategorized_transactions.countenddef uncategorized_entries_for(ids)return [] if ids.blank?- Current.accessible_entries+ Current.annotatable_entries.excluding_split_parents.where(id: ids).uncategorized_transactionsdiff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rbindex 397b574a52..3487845b94 100644--- a/app/controllers/transactions_controller.rb+++ b/app/controllers/transactions_controller.rb@@ -76,8 +76,10 @@ class TransactionsController < ApplicationControllerSet.newend+ # Counts what the categorize wizard can act on, so read-only shares don't+ # keep the "Categorize" menu item visible.@uncategorized_count = Rails.cache.fetch(uncategorized_count_cache_key) do- Current.accessible_entries.uncategorized_transactions.count+ Current.annotatable_entries.uncategorized_transactions.countend# Load projected recurring transactions for next 10 days. Only the IDs are@@ -532,7 +534,7 @@ class TransactionsController < ApplicationController# active status (AccountsController#toggle_active) doesn't touch `entries`# or `AccountShare`, so it wouldn't otherwise bust this cache.def uncategorized_count_cache_key- "transactions_uncategorized_count/v4/#{Current.family.id}/#{Current.user.id}/" \+ "transactions_uncategorized_count/v5/#{Current.family.id}/#{Current.user.id}/" \"#{Current.family.entries_version}/#{Current.family.accounts_status_version}/#{Current.account_share_version}"end@@ -714,9 +716,9 @@ class TransactionsController < ApplicationControllerentry_paramswhen :read_write# Annotate only: category, tags, merchant, notes- ep = entry_params.slice(:notes)+ ep = entry_params.slice(*AccountShare::ANNOTATE_ENTRY_ATTRIBUTES)if entry_params[:entryable_attributes].present?- ep[:entryable_attributes] = entry_params[:entryable_attributes].slice(:id, :category_id, :merchant_id, :tag_ids)+ ep[:entryable_attributes] = entry_params[:entryable_attributes].slice(:id, *AccountShare::ANNOTATE_TRANSACTION_ATTRIBUTES)endepelsediff --git a/app/models/account.rb b/app/models/account.rbindex d80e08c20e..9e081a980c 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -94,12 +94,20 @@ class Account < ApplicationRecord}# Accounts a user can write to (owned or shared with full_control)+ WRITABLE_BY_CONDITION = "accounts.owner_id = :uid OR (account_shares.user_id = :uid AND account_shares.permission = 'full_control')".freeze+scope :writable_by, ->(user) {left_joins(:account_shares)- .where("accounts.owner_id = :uid OR (account_shares.user_id = :uid AND account_shares.permission = 'full_control')", uid: user.id)+ .where(WRITABLE_BY_CONDITION, uid: user.id).distinct}+ # SQL boolean for "user may write to this account", for selecting next to+ # rows already joined with account_shares (e.g. through annotatable_by).+ def self.writable_by_sql(user)+ Arel.sql("(#{sanitize_sql([ WRITABLE_BY_CONDITION, uid: user.id ])})")+ end+# Accounts a user can annotate (category, tags, notes, merchant): owned,# or shared with full_control or read_writescope :annotatable_by, ->(user) {diff --git a/app/models/account_share.rb b/app/models/account_share.rbindex e4fdca42ff..d20a4ea63f 100644--- a/app/models/account_share.rb+++ b/app/models/account_share.rb@@ -6,6 +6,11 @@ class AccountShare < ApplicationRecord# Share tiers that may annotate (category, tags, notes, merchant); owners# always can. Single source for the per-account check and bulk scopes.ANNOTATE_PERMISSIONS = %w[full_control read_write].freeze+ # Fields those annotate-only tiers may change: notes on the entry, and+ # category, merchant and tags on its transaction. Single-entry edits and+ # bulk edits both filter through these lists.+ ANNOTATE_ENTRY_ATTRIBUTES = %i[notes].freeze+ ANNOTATE_TRANSACTION_ATTRIBUTES = %i[category_id merchant_id tag_ids].freezevalidates :permission, inclusion: { in: PERMISSIONS }validates :user_id, uniqueness: { scope: :account_id }diff --git a/app/models/current.rb b/app/models/current.rbindex ffb08f3e7e..c2f18edbfa 100644--- a/app/models/current.rb+++ b/app/models/current.rb@@ -33,6 +33,13 @@ class Current < ActiveSupport::CurrentAttributesfamily.entries.joins(:account).merge(Account.accessible_by(user))end+ # Entries the user may annotate (notes, category, merchant, tags): owned+ # accounts and shares with full_control or read_write, not read_only.+ def annotatable_entries+ return family&.entries unless user+ family.entries.joins(:account).merge(Account.annotatable_by(user))+ end+# Used for invalidating caches whose results depend on the current user's# account-share access (e.g. the transactions index's uncategorized count# and projected recurring list, which are scoped to accessible accounts).diff --git a/app/models/entry.rb b/app/models/entry.rbindex 25593fe97b..e3429da253 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -530,6 +530,12 @@ class Entry < ApplicationRecord# Bulk update entries with the given parameters.#+ # No authorization happens here: callers must scope the relation to entries+ # the user may change (e.g. Current.annotatable_entries, Account.writable_by)+ # and pass only the fields that permission allows+ # (AccountShare::ANNOTATE_* for annotate-only shares), and must resolve+ # category, merchant and tag IDs through the family.+ ## Tags are handled separately from other entryable attributes because they use# a join table (taggings) rather than a direct column. This means:# - category_id: nil means "no category" (column value)diff --git a/test/controllers/transactions/bulk_updates_controller_test.rb b/test/controllers/transactions/bulk_updates_controller_test.rbindex 8e34ba2fc5..8e2b975a0f 100644--- a/test/controllers/transactions/bulk_updates_controller_test.rb+++ b/test/controllers/transactions/bulk_updates_controller_test.rb@@ -1,6 +1,8 @@require "test_helper"class Transactions::BulkUpdatesControllerTest < ActionDispatch::IntegrationTest+ include EntriesTestHelper+setup dosign_in @user = users(:family_admin)end@@ -136,4 +138,135 @@ class Transactions::BulkUpdatesControllerTest < ActionDispatch::IntegrationTesttransaction_entry.reloadassert_equal [ new_tag.id ], transaction_entry.transaction.tag_idsend++ test "bulk update ignores category, merchant and tag ids from another family" do+ other_family = families(:empty)+ foreign_category = other_family.categories.create!(name: "Foreign category")+ foreign_merchant = FamilyMerchant.create!(family: other_family, name: "Foreign merchant")+ foreign_tag = other_family.tags.create!(name: "Foreign tag")++ transaction_entry = @user.family.entries.transactions.first+ transaction_entry.transaction.update!(category: categories(:food_and_drink), merchant: merchants(:netflix))+ transaction_entry.transaction.tags = [ tags(:one) ]+ transaction_entry.transaction.save!++ post transactions_bulk_update_url, params: {+ bulk_update: {+ entry_ids: [ transaction_entry.id ],+ category_id: foreign_category.id,+ merchant_id: foreign_merchant.id,+ tag_ids: [ foreign_tag.id, tags(:two).id ]+ }+ }++ assert_redirected_to transactions_url++ transaction = transaction_entry.reload.transaction+ assert_equal categories(:food_and_drink), transaction.category+ assert_equal merchants(:netflix), transaction.merchant+ assert_equal [ tags(:two).id ], transaction.tag_ids+ assert_empty foreign_tag.taggings+ end++ test "bulk update keeps existing tags when every requested tag belongs to another family" do+ foreign_tag = families(:empty).tags.create!(name: "Foreign tag")+ transaction_entry = @user.family.entries.transactions.first+ transaction_entry.transaction.tags = [ tags(:one) ]+ transaction_entry.transaction.save!++ post transactions_bulk_update_url, params: {+ bulk_update: { entry_ids: [ transaction_entry.id ], tag_ids: [ foreign_tag.id ] }+ }++ assert_equal [ tags(:one).id ], transaction_entry.reload.transaction.tag_ids+ end++ test "bulk update lets a read_write share annotate but not change date or name" do+ account = accounts(:credit_card)+ account.account_shares.find_by!(user: users(:family_member)).update!(permission: "read_write")+ entry = create_transaction(account: account, name: "Original name", date: Date.new(2026, 1, 5))++ sign_in users(:family_member)+ post transactions_bulk_update_url, params: {+ bulk_update: {+ entry_ids: [ entry.id ],+ name: "Renamed", date: "2026-02-10", notes: "annotated", category_id: categories(:food_and_drink).id+ }+ }++ entry.reload+ assert_equal "Original name", entry.name+ assert_equal Date.new(2026, 1, 5), entry.date+ assert_equal "annotated", entry.notes+ assert_equal categories(:food_and_drink), entry.transaction.category+ end++ test "bulk update skips entries from accounts the user can only read" do+ read_only_account = accounts(:credit_card) # shared read_only with family_member+ entry = create_transaction(account: read_only_account, name: "Starbucks")+ original_category = entry.transaction.category++ sign_in users(:family_member)++ post transactions_bulk_update_url, params: {+ bulk_update: {+ entry_ids: [ entry.id ],+ category_id: categories(:food_and_drink).id,+ notes: "Changed by a read-only member"+ }+ }++ assert_redirected_to transactions_url+ assert_equal "0 transactions updated", flash[:notice]+ assert_equal original_category, entry.reload.transaction.category+ assert_nil entry.notes+ end++ test "bulk update skips entries from accounts not shared with the user" do+ entry = create_transaction(account: accounts(:other_asset), name: "Private entry")++ sign_in users(:family_member)+ post transactions_bulk_update_url, params: {+ bulk_update: { entry_ids: [ entry.id ], name: "Renamed", notes: "Changed by another member" }+ }++ assert_equal "0 transactions updated", flash[:notice]+ entry.reload+ assert_equal "Private entry", entry.name+ assert_nil entry.notes+ end++ test "bulk update lets a full_control share change date and name" do+ entry = create_transaction(account: accounts(:depository), name: "Original name", date: Date.new(2026, 1, 5))++ sign_in users(:family_member)+ post transactions_bulk_update_url, params: {+ bulk_update: { entry_ids: [ entry.id ], name: "Renamed", date: "2026-02-10" }+ }++ assert_equal "1 transactions updated", flash[:notice]+ entry.reload+ assert_equal "Renamed", entry.name+ assert_equal Date.new(2026, 2, 10), entry.date+ end++ test "bulk update applies each share's rights within one mixed selection" do+ accounts(:credit_card).account_shares.find_by!(user: users(:family_member)).update!(permission: "read_write")+ full_entry = create_transaction(account: accounts(:depository), name: "Full", date: Date.new(2026, 1, 5))+ annotate_entry = create_transaction(account: accounts(:credit_card), name: "Annotate", date: Date.new(2026, 1, 5))+ private_entry = create_transaction(account: accounts(:other_asset), name: "Private", date: Date.new(2026, 1, 5))++ sign_in users(:family_member)+ post transactions_bulk_update_url, params: {+ bulk_update: {+ entry_ids: [ full_entry.id, annotate_entry.id, private_entry.id ],+ name: "Renamed", notes: "bulk note"+ }+ }++ assert_equal "2 transactions updated", flash[:notice]+ assert_equal [ "Renamed", "bulk note" ], [ full_entry.reload.name, full_entry.notes ]+ assert_equal [ "Annotate", "bulk note" ], [ annotate_entry.reload.name, annotate_entry.notes ]+ assert_equal [ "Private", nil ], [ private_entry.reload.name, private_entry.notes ]+ endenddiff --git a/test/controllers/transactions/categorizes_controller_test.rb b/test/controllers/transactions/categorizes_controller_test.rbindex 1bd141f77e..1f7069c14a 100644--- a/test/controllers/transactions/categorizes_controller_test.rb+++ b/test/controllers/transactions/categorizes_controller_test.rb@@ -161,6 +161,93 @@ class Transactions::CategorizesControllerTest < ActionDispatch::IntegrationTestassert_nil entry.transaction.reload.categoryend+ test "create does not categorize entries from read-only shared accounts" do+ read_only_account = accounts(:credit_card) # shared read_only with family_member+ entry = create_transaction(account: read_only_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 "create does not create a rule when no entry could be categorized" do+ read_only_account = accounts(:credit_card) # shared read_only with family_member+ entry = create_transaction(account: read_only_account, name: "Starbucks")++ sign_in users(:family_member)+ assert_no_difference "Rule.count" do+ post transactions_categorize_url,+ params: {+ position: 0,+ grouping_key: "Starbucks",+ entry_ids: [ entry.id ],+ all_entry_ids: [ entry.id ],+ category_id: @category.id,+ create_rule: "1"+ },+ headers: { "Accept" => "text/vnd.turbo-stream.html" }+ end+ end++ test "create categorizes entries from read_write shared accounts" do+ read_write_account = accounts(:credit_card)+ read_write_account.account_shares.find_by!(user: users(:family_member)).update!(permission: "read_write")+ entry = create_transaction(account: read_write_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_equal @category, entry.transaction.reload.category+ end++ test "assign_entry does not categorize an entry from a read-only shared account" do+ read_only_account = accounts(:credit_card) # shared read_only with family_member+ entry = create_transaction(account: read_only_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++ test "show and preview_rule skip entries from read-only shared accounts" do+ read_only_account = accounts(:credit_card) # shared read_only with family_member+ entry = create_transaction(account: read_only_account, name: "ReadOnlyShop")++ sign_in users(:family_member)++ get transactions_categorize_url+ assert_not_includes response.body, entry.id++ get preview_rule_transactions_categorize_url(filter: "ReadOnlyShop"),+ headers: { "Accept" => "text/vnd.turbo-stream.html" }+ assert_response :success+ assert_not_includes response.body, entry.id+ end+# GET /transactions/categorize/preview_ruletest "preview_rule returns matching entries for a filter" dodiff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex be5fbcdbbe..cdfbf33615 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -1563,6 +1563,31 @@ endRails.cache = original_cacheend+ test "index uncategorized_count leaves out read-only shared accounts" do+ sign_in users(:family_member)+ get transactions_url+ count_before = rendered_uncategorized_count++ accounts(:credit_card).entries.create!( # shared read_only with family_member+ name: "Uncategorized on read-only share",+ amount: 42,+ currency: "USD",+ date: Date.current,+ entryable: Transaction.new+ )+ accounts(:depository).entries.create!( # shared full_control with family_member+ name: "Uncategorized on full-control share",+ amount: 42,+ currency: "USD",+ date: Date.current,+ entryable: Transaction.new+ )++ get transactions_url+ assert_equal count_before + 1, rendered_uncategorized_count,+ "the categorize count should only include entries the member can categorize"+ end+test "index projected_recurring cache is invalidated when account-share access is revoked" dooriginal_cache = Rails.cacheRails.cache = ActiveSupport::Cache::MemoryStore.new