Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Let users count an investment transfer as a plain transfer (#4177)

Andrei Shkarin60ade73a1373
diff --git a/app/controllers/transfers_controller.rb b/app/controllers/transfers_controller.rb
index bd443d8c3b..a34c47b0cd 100644
--- a/app/controllers/transfers_controller.rb
+++ b/app/controllers/transfers_controller.rb
@@ -16,16 +16,16 @@ class TransfersController < ApplicationController
@categories = Current.family.categories.alphabetically_by_hierarchy
@tags = Current.family.tags.alphabetically
- # Whether the current user can hit `mark_as_recurring`: feature flag on,
- # AND they have write access to BOTH transfer endpoints. Gating the
- # view button on this avoids showing a CTA that the controller would
- # reject via `require_account_permission!` for read-only sharers.
+ # Whether the current user can hit `mark_as_recurring` (feature flag on)
+ # or switch the investment contribution: both need write access to BOTH
+ # transfer endpoints. Gating the view controls on this avoids showing a
+ # CTA that the controller would reject via `require_account_permission!`
+ # for read-only sharers.
endpoint_ids = [ @transfer.from_account&.id, @transfer.to_account&.id ].compact
writable_endpoint_count = Account.writable_by(Current.user).where(id: endpoint_ids).distinct.count
- @can_mark_as_recurring_transfer =
- !Current.family.recurring_transactions_disabled? &&
- endpoint_ids.size == 2 &&
- writable_endpoint_count == 2
+ both_endpoints_writable = endpoint_ids.size == 2 && writable_endpoint_count == 2
+ @can_mark_as_recurring_transfer = !Current.family.recurring_transactions_disabled? && both_endpoints_writable
+ @can_switch_investment_contribution = both_endpoints_writable && @transfer.investment_contribution_switchable?
end
def create
@@ -99,11 +99,18 @@ class TransfersController < ApplicationController
update_transfer_status
update_transfer_fees_and_amount
update_transfer_details
+ update_investment_contribution
end
respond_to do |format|
format.html { redirect_back_or_to transactions_url, notice: t(".success") }
- format.turbo_stream
+ format.turbo_stream do
+ # The switch moves the amount in or out of the page's expense totals,
+ # which the row replacements in update.turbo_stream would leave stale.
+ if transfer_update_params.key?(:investment_contribution)
+ stream_redirect_to(request.referer.presence || transactions_url)
+ end
+ end
end
end
@@ -286,7 +293,7 @@ class TransfersController < ApplicationController
end
def transfer_update_params
- params.require(:transfer).permit(:notes, :status, :category_id, :amount, :source_fee_amount, :destination_fee_amount)
+ params.require(:transfer).permit(:notes, :status, :category_id, :amount, :source_fee_amount, :destination_fee_amount, :investment_contribution)
end
def update_transfer_status
@@ -297,6 +304,12 @@ class TransfersController < ApplicationController
end
end
+ def update_investment_contribution
+ return unless transfer_update_params.key?(:investment_contribution)
+
+ @transfer.update_investment_contribution!(ActiveModel::Type::Boolean.new.cast(transfer_update_params[:investment_contribution]))
+ end
+
def update_transfer_details
# Confirming from the transaction list sends only the status; leave the
# category and notes alone unless the form actually submitted them.
diff --git a/app/models/assistant.rb b/app/models/assistant.rb
index b8dae18dc7..e8320c60ca 100644
--- a/app/models/assistant.rb
+++ b/app/models/assistant.rb
@@ -76,6 +76,7 @@ module Assistant
Function::CreateGoal,
Function::SetOpeningBalance,
Function::UnmatchTransfer,
+ Function::UpdateTransfer,
Function::GetTags,
Function::CreateTag,
Function::UpdateTag,
diff --git a/app/models/assistant/function/transfer_support.rb b/app/models/assistant/function/transfer_support.rb
new file mode 100644
index 0000000000..c872f7af49
--- /dev/null
+++ b/app/models/assistant/function/transfer_support.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+# Shared lookups for the transfer tools (unmatch_transfer, update_transfer):
+# a transfer is reachable only when the user can write to both of its accounts.
+module Assistant::Function::TransferSupport
+ private
+ def writable_transactions
+ family.transactions.joins(entry: :account).merge(Account.writable_by(user))
+ end
+
+ def scoped_transfers
+ ids = writable_transactions.select(:id)
+ Transfer.where(inflow_transaction_id: ids).where(outflow_transaction_id: ids)
+ end
+
+ def find_transfer(id)
+ return nil unless valid_uuid?(id)
+
+ scoped_transfers.find_by(id: id)
+ end
+
+ def find_transfer_for_transaction(id)
+ return nil unless valid_uuid?(id)
+
+ scoped_transfers.where("inflow_transaction_id = :id OR outflow_transaction_id = :id", id: id).first
+ end
+
+ # Exactly one of transaction_id or transfer_id; an error hash otherwise.
+ def lookup_transfer(params)
+ if params["transaction_id"].present? == params["transfer_id"].present?
+ return error("invalid_arguments", "Pass exactly one of transaction_id or transfer_id.")
+ end
+
+ transfer = params["transfer_id"].present? ? find_transfer(params["transfer_id"]) : find_transfer_for_transaction(params["transaction_id"])
+ return transfer if transfer
+
+ ref = params["transfer_id"].presence || params["transaction_id"]
+ error("not_found", "No transfer for '#{ref}' between accounts you can write to.")
+ end
+
+ def error(key, message)
+ { success: false, error: key, message: message }
+ end
+end
diff --git a/app/models/assistant/function/unmatch_transfer.rb b/app/models/assistant/function/unmatch_transfer.rb
index 0d0a4399de..bec9f68121 100644
--- a/app/models/assistant/function/unmatch_transfer.rb
+++ b/app/models/assistant/function/unmatch_transfer.rb
@@ -14,6 +14,8 @@
# Transfer fee transactions belong to the transfer and are deleted with it, as
# in the UI; the result lists them and the affected accounts are resynced.
class Assistant::Function::UnmatchTransfer < Assistant::Function
+ include Assistant::Function::TransferSupport
+
class << self
def name
"unmatch_transfer"
@@ -66,15 +68,8 @@ class Assistant::Function::UnmatchTransfer < Assistant::Function
end
def call(params = {})
- if params["transaction_id"].present? == params["transfer_id"].present?
- return error("invalid_arguments", "Pass exactly one of transaction_id or transfer_id.")
- end
-
- transfer = params["transfer_id"].present? ? find_transfer(params["transfer_id"]) : find_transfer_for_transaction(params["transaction_id"])
- unless transfer
- ref = params["transfer_id"].presence || params["transaction_id"]
- return error("not_found", "No transfer for '#{ref}' between accounts you can write to.")
- end
+ transfer = lookup_transfer(params)
+ return transfer if transfer.is_a?(Hash)
# Only an explicit false skips the rejection; null counts as omitted.
reject = params["reject"].nil? || ActiveModel::Type::Boolean.new.cast(params["reject"])
@@ -127,27 +122,6 @@ class Assistant::Function::UnmatchTransfer < Assistant::Function
end
private
- def writable_transactions
- family.transactions.joins(entry: :account).merge(Account.writable_by(user))
- end
-
- def scoped_transfers
- ids = writable_transactions.select(:id)
- Transfer.where(inflow_transaction_id: ids).where(outflow_transaction_id: ids)
- end
-
- def find_transfer(id)
- return nil unless valid_uuid?(id)
-
- scoped_transfers.find_by(id: id)
- end
-
- def find_transfer_for_transaction(id)
- return nil unless valid_uuid?(id)
-
- scoped_transfers.where("inflow_transaction_id = :id OR outflow_transaction_id = :id", id: id).first
- end
-
def serialize_transfer(transfer)
{
id: transfer.id,
@@ -173,8 +147,4 @@ class Assistant::Function::UnmatchTransfer < Assistant::Function
kind: transaction.kind
}
end
-
- def error(key, message)
- { success: false, error: key, message: message }
- end
end
diff --git a/app/models/assistant/function/update_transfer.rb b/app/models/assistant/function/update_transfer.rb
new file mode 100644
index 0000000000..63fa7318fe
--- /dev/null
+++ b/app/models/assistant/function/update_transfer.rb
@@ -0,0 +1,136 @@
+# frozen_string_literal: true
+
+# UpdateTransfer — changes how a confirmed transfer counts, as the transfer
+# drawer does. Today that is one switch: whether a transfer from a cash account
+# into an investment or crypto account is an investment contribution (counted
+# as spending in budgets and reports, the default) or a plain transfer (e.g.
+# a brokerage or crypto account used only to convert currency). See
+# Transfer#update_investment_contribution!, which locks the choice against
+# provider syncs.
+class Assistant::Function::UpdateTransfer < Assistant::Function
+ include Assistant::Function::TransferSupport
+
+ class << self
+ def name
+ "update_transfer"
+ end
+
+ def description
+ <<~INSTRUCTIONS
+ Changes how a confirmed transfer between two of the user's accounts
+ counts in budgets and reports.
+
+ investment_contribution: a transfer from a cash account into an
+ investment or crypto account counts as spending by default (an
+ investment contribution). Pass false to make it a plain transfer that
+ budgets and reports ignore, e.g. when the brokerage or crypto account is
+ only used to convert money into another currency; pass true to count it
+ as spending again. The choice survives
+ account syncs. Other transfers have no such switch.
+
+ Pass the id of either transaction in the transfer (get_transactions
+ marks them is_transfer), or the transfer_id. Both accounts must be
+ writable. Pass dry_run: true to see the effect first.
+ INSTRUCTIONS
+ end
+ end
+
+ def strict_mode?
+ false
+ end
+
+ def params_schema
+ build_schema(
+ properties: {
+ transaction_id: {
+ type: "string",
+ description: "ID of either transaction in the transfer, from get_transactions. Omit when passing transfer_id."
+ },
+ transfer_id: {
+ type: "string",
+ description: "Transfer ID. Omit when passing transaction_id."
+ },
+ investment_contribution: {
+ type: "boolean",
+ description: "true counts a transfer into an investment or crypto account as spending; false makes it a plain transfer."
+ },
+ dry_run: {
+ type: "boolean",
+ description: "Describe the change without making it. Defaults to false."
+ }
+ }
+ )
+ end
+
+ def call(params = {})
+ enabled = parse_boolean(params["investment_contribution"])
+ return error("invalid_arguments", "Pass investment_contribution: true or false.") if enabled.nil?
+
+ transfer = lookup_transfer(params)
+ return transfer if transfer.is_a?(Hash)
+
+ unless transfer.investment_contribution_switchable?
+ return error("not_switchable", "Only a confirmed transfer from a cash account into an investment or crypto account can be switched between an investment contribution and a plain transfer.")
+ end
+
+ if ActiveModel::Type::Boolean.new.cast(params["dry_run"])
+ return {
+ success: true,
+ dry_run: true,
+ transfer: serialize_transfer(transfer),
+ message: "Would make #{transfer.name} #{describe(enabled)}."
+ }
+ end
+
+ # Lock, then re-find within the writable scope, so write access lost since
+ # the lookup is caught.
+ updated = Transfer.uncached do
+ Transfer.transaction do
+ locked = scoped_transfers.lock.find_by(id: transfer.id)
+ next nil unless locked
+
+ locked.update_investment_contribution!(enabled) ? locked : nil
+ end
+ end
+ return error("not_found", "The transfer was unlinked, or you can no longer write to its accounts.") unless updated
+
+ { success: true, transfer: serialize_transfer(updated), message: "#{updated.name} is now #{describe(enabled)}." }
+ end
+
+ private
+ # The tool caller does not enforce params_schema, and
+ # ActiveModel::Type::Boolean reads every unrecognized string (e.g. "no")
+ # as true, which would turn on the contribution the caller meant to turn off.
+ TRUTHY_INPUTS = [ true, "true", "t", "1", 1 ].freeze
+ FALSY_INPUTS = [ false, "false", "f", "0", 0 ].freeze
+
+ def parse_boolean(value)
+ normalized = value.is_a?(String) ? value.strip.downcase : value
+ return true if TRUTHY_INPUTS.include?(normalized)
+ false if FALSY_INPUTS.include?(normalized)
+ end
+
+ def describe(enabled)
+ enabled ? "an investment contribution (counted as spending)" : "a plain transfer (not counted as spending)"
+ end
+
+ def serialize_transfer(transfer)
+ outflow = transfer.outflow_transaction.reload
+ {
+ id: transfer.id,
+ name: transfer.name,
+ status: transfer.status,
+ investment_contribution: transfer.investment_contribution?,
+ outflow: {
+ id: outflow.id,
+ account: outflow.entry.account.name,
+ kind: outflow.kind,
+ category: outflow.category&.name
+ },
+ inflow: {
+ id: transfer.inflow_transaction.id,
+ account: transfer.inflow_transaction.entry.account.name
+ }
+ }
+ end
+end
diff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rb
index f383a830be..827b71bb16 100644
--- a/app/models/family/data_exporter.rb
+++ b/app/models/family/data_exporter.rb
@@ -433,6 +433,7 @@ class Family::DataExporter
outflow_transaction_id: transfer.outflow_transaction_id,
status: transfer.status,
notes: transfer.notes,
+ investment_contribution: transfer.investment_contribution_choice,
created_at: transfer.created_at,
updated_at: transfer.updated_at
}
diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rb
index 389119e690..464bf04a1e 100644
--- a/app/models/family/data_importer.rb
+++ b/app/models/family/data_importer.rb
@@ -1047,7 +1047,11 @@ class Family::DataImporter
transfer.notes = data["notes"]
end
# Transfer kinds only apply once a transfer is confirmed (see Transfer#confirm!)
- apply_transfer_transaction_kinds!(transfer) if transfer.confirmed?
+ if transfer.confirmed?
+ apply_transfer_transaction_kinds!(transfer)
+ # Restores a user's explicit choice over the destination's default kind.
+ transfer.update_investment_contribution!(truthy?(data["investment_contribution"])) unless data["investment_contribution"].nil?
+ end
increment_summary("Transfer", transfer.previously_new_record? ? :created : :updated)
end
end
diff --git a/app/models/transfer.rb b/app/models/transfer.rb
index ddb8524c74..05ff46d566 100644
--- a/app/models/transfer.rb
+++ b/app/models/transfer.rb
@@ -107,13 +107,65 @@ class Transfer < ApplicationRecord
end
# The kind a leg carries while this transfer exists: the outflow by the
- # destination account, the inflow always funds_movement.
+ # destination account (unless the user chose whether it is an investment
+ # contribution), the inflow always funds_movement.
def kind_for_leg(transaction)
return "funds_movement" if transaction.id == inflow_transaction_id
+ return transaction.kind if investment_contribution_chosen?(transaction)
Transfer.kind_for_account(to_account, from_account: from_account)
end
+ # A transfer into an investment or crypto account counts as an investment
+ # contribution (a budgeted expense) by default. A user can make it a plain
+ # transfer instead, e.g. when a brokerage or crypto account only converts
+ # money into another currency.
+ def investment_contribution_switchable?
+ confirmed? && contribution_by_default?
+ end
+
+ def investment_contribution?
+ kind_for_leg(outflow_transaction) == "investment_contribution"
+ end
+ alias_method :investment_contribution, :investment_contribution?
+
+ # The user's explicit choice from update_investment_contribution!, or nil
+ # while the transfer follows the default for its destination account.
+ def investment_contribution_choice
+ investment_contribution? if investment_contribution_chosen?(outflow_transaction)
+ end
+
+ # Switches the outflow between investment_contribution and funds_movement
+ # and locks the kind, so provider syncs and Transfer::InvestmentKindReconciler
+ # keep the choice. The Investment Contributions category follows the switch,
+ # since a plain transfer is uncategorized (see
+ # Transaction::UNCATEGORIZED_EXCLUDED_KINDS); any other category stays.
+ #
+ # @return [Boolean] false when this transfer cannot be switched
+ def update_investment_contribution!(enabled)
+ return false unless investment_contribution_switchable?
+
+ Transfer.transaction do
+ # Lock before reading the category, so a concurrent category change is
+ # not overwritten by a value derived from a stale read.
+ outflow_transaction.lock!
+
+ outflow_attrs = { kind: enabled ? "investment_contribution" : "funds_movement" }
+ category = outflow_transaction.category
+
+ if enabled && category.nil?
+ outflow_attrs[:category] = to_account.family.investment_contributions_category
+ elsif !enabled && category && Category.all_investment_contributions_names.include?(category.name)
+ outflow_attrs[:category] = nil
+ end
+
+ outflow_transaction.update!(outflow_attrs)
+ outflow_transaction.lock_attr!(:kind)
+ end
+
+ true
+ end
+
# Based on the destination account rather than outflow_transaction.kind,
# which can be stale on rows a provider sync overwrote before
# Account::ProviderImportAdapter derived matched legs from their transfer
@@ -121,7 +173,7 @@ class Transfer < ApplicationRecord
def categorizable?
return false unless to_account
- !Transaction::UNCATEGORIZED_EXCLUDED_KINDS.include?(Transfer.kind_for_account(to_account, from_account: from_account))
+ !Transaction::UNCATEGORIZED_EXCLUDED_KINDS.include?(kind_for_leg(outflow_transaction))
end
def reject!
@@ -172,6 +224,17 @@ class Transfer < ApplicationRecord
end
private
+ def contribution_by_default?
+ to_account.present? && Transfer.kind_for_account(to_account, from_account: from_account) == "investment_contribution"
+ end
+
+ # The outflow kind update_investment_contribution! set and locked.
+ def investment_contribution_chosen?(transaction)
+ transaction.locked?(:kind) &&
+ %w[investment_contribution funds_movement].include?(transaction.kind) &&
+ contribution_by_default?
+ end
+
# Gives each surviving transaction back its standalone state. When the
# transfer goes because one leg is being deleted (dependent: :destroy on
# Transaction), that leg is skipped.
@@ -184,7 +247,11 @@ class Transfer < ApplicationRecord
begin
# A pending auto-match never changed the kind (see #confirm!), so a
# transfer kind on its transactions predates the match and stays.
- transaction.update!(kind: "standard") if transaction.transfer? && !pending?
+ if transaction.transfer? && !pending?
+ transaction.update!(kind: "standard")
+ # A kind locked by update_investment_contribution! belonged to this transfer.
+ transaction.unlock_attr!(:kind) if transaction.locked?(:kind)
+ end
# The entry survives this destroy (only the Transfer join row and
# fee transactions go away), but its idempotency_key must not: a
# later retry of the original create request looks up that key,
diff --git a/app/views/transfers/show.html.erb b/app/views/transfers/show.html.erb
index 2da9e71ba3..dbb4111066 100644
--- a/app/views/transfers/show.html.erb
+++ b/app/views/transfers/show.html.erb
@@ -81,24 +81,41 @@
</div>
<% end %>
<% dialog.with_section(title: t(".details")) do %>
- <%= styled_form_with model: @transfer,
- data: { controller: "auto-submit-form" }, class: "space-y-2" do |f| %>
+ <div class="space-y-2">
+ <%# Separate forms: the investment contribution switch reloads the page, so
+ it must not be submitted along with every category or notes edit. %>
<% if @transfer.categorizable? %>
- <%= f.collection_select :category_id, @categories, :id, :name, { label: t(".category"), include_blank: t(".uncategorized"), selected: @transfer.outflow_transaction.category&.id, variant: :badge, searchable: true }, "data-auto-submit-form-target": "auto" %>
+ <%= styled_form_with model: @transfer, data: { controller: "auto-submit-form" } do |f| %>
+ <%= f.collection_select :category_id, @categories, :id, :name, { label: t(".category"), include_blank: t(".uncategorized"), selected: @transfer.outflow_transaction.category&.id, variant: :badge, searchable: true }, "data-auto-submit-form-target": "auto" %>
+ <% end %>
<% end %>
- <%= render DS::TagSelect.new(
- form: f,
- tags: @tags,
- selected_ids: @transfer.outflow_transaction.tag_ids,
- auto_submit: true,
- update_url: tags_transfer_path(@transfer)
- ) %>
- <%= f.text_area :notes,
- label: t(".note_label"),
- placeholder: t(".note_placeholder"),
- rows: 5,
- "data-auto-submit-form-target": "auto" %>
- <% end %>
+ <% if @can_switch_investment_contribution %>
+ <%= styled_form_with model: @transfer,
+ data: { controller: "auto-submit-form" },
+ class: "flex items-center justify-between gap-4 py-1" do |f| %>
+ <div class="space-y-1">
+ <p class="text-sm text-primary"><%= t(".investment_contribution_title") %></p>
+ <p class="text-xs text-secondary"><%= t(".investment_contribution_subtitle") %></p>
+ </div>
+ <%= f.toggle :investment_contribution, data: { auto_submit_form_target: "auto" } %>
+ <% end %>
+ <% end %>
+ <%= styled_form_with model: @transfer,
+ data: { controller: "auto-submit-form" }, class: "space-y-2" do |f| %>
+ <%= render DS::TagSelect.new(
+ form: f,
+ tags: @tags,
+ selected_ids: @transfer.outflow_transaction.tag_ids,
+ auto_submit: true,
+ update_url: tags_transfer_path(@transfer)
+ ) %>
+ <%= f.text_area :notes,
+ label: t(".note_label"),
+ placeholder: t(".note_placeholder"),
+ rows: 5,
+ "data-auto-submit-form-target": "auto" %>
+ <% end %>
+ </div>
<% end %>
<% dialog.with_section(title: t(".settings")) do %>
<div class="pb-4">
diff --git a/config/locales/views/transfers/en.yml b/config/locales/views/transfers/en.yml
index b039ac3bfa..77163afb69 100644
--- a/config/locales/views/transfers/en.yml
+++ b/config/locales/views/transfers/en.yml
@@ -33,6 +33,10 @@ en:
transactions.
delete_title: Remove transfer?
details: Details
+ investment_contribution_subtitle: Count this transfer as spending in budgets and
+ reports. Turn it off when the brokerage or crypto account only converts the
+ money into another currency.
+ investment_contribution_title: Investment contribution
mark_recurring: Mark as recurring
mark_recurring_subtitle: Track this transfer as a recurring pattern in the upcoming
feed and recurring page.
diff --git a/config/locales/views/transfers/ru.yml b/config/locales/views/transfers/ru.yml
index af2e37a2ff..a2a19af89a 100644
--- a/config/locales/views/transfers/ru.yml
+++ b/config/locales/views/transfers/ru.yml
@@ -36,6 +36,10 @@ ru:
delete_title: Удалить перевод?
details: Подробности
from: Откуда
+ investment_contribution_subtitle: Учитывать этот перевод как расход в бюджете
+ и отчётах. Выключите, если брокерский или крипто-счёт служит только для
+ конвертации денег в другую валюту.
+ investment_contribution_title: Инвестиционный взнос
mark_recurring: Отметить как регулярный
mark_recurring_subtitle: Отслеживайте этот перевод как регулярный в ленте и
на странице регулярных операций.
diff --git a/docs/hosting/ai.md b/docs/hosting/ai.md
index 362f493f52..308ea668f1 100644
--- a/docs/hosting/ai.md
+++ b/docs/hosting/ai.md
@@ -1529,6 +1529,7 @@ Read and analysis:
Write:
- `update_transaction`, `update_budget`, `create_goal`
- `unmatch_transfer` - Unlink a wrongly matched transfer
+- `update_transfer` - Count a transfer into an investment account as spending or as a plain transfer
- `create_tag` / `update_tag`, `create_category` / `update_category`
Documents:
diff --git a/docs/hosting/mcp.md b/docs/hosting/mcp.md
index fa9b5681c8..9a0851cf5e 100644
--- a/docs/hosting/mcp.md
+++ b/docs/hosting/mcp.md
@@ -148,6 +148,7 @@ At the time of writing, `tools/list` includes:
| `create_goal` | Create a savings goal linked to depository accounts |
| `set_opening_balance` | Set a manual account's opening balance and the date it applies from, reporting whether the current balance changes. Supports `dry_run` |
| `unmatch_transfer` | Unlink a confirmed or pending transfer (by either transaction's id) so a wrong match can be redone; rejects the pairing for auto-match by default. Supports `dry_run` |
+| `update_transfer` | Switch a confirmed transfer into an investment or crypto account between an investment contribution (counted as spending) and a plain transfer, e.g. when a brokerage or crypto account only converts currency. Supports `dry_run` |
| `create_tag` / `update_tag` | Manage tags |
| `create_category` / `update_category` | Manage categories |
| `update_transaction` | Edit a transaction's metadata (name, notes, category, merchant, tags) |
diff --git a/test/controllers/transfers_controller_test.rb b/test/controllers/transfers_controller_test.rb
index 1c602b4301..7fed75a24b 100644
--- a/test/controllers/transfers_controller_test.rb
+++ b/test/controllers/transfers_controller_test.rb
@@ -796,6 +796,50 @@ class TransfersControllerTest < ActionDispatch::IntegrationTest
assert_response :not_found
end
+ test "show offers the investment contribution switch only for transfers into an investment account" do
+ contribution = create_confirmed_transfer(to: accounts(:investment))
+ payment = create_confirmed_transfer(to: accounts(:credit_card))
+
+ get transfer_url(contribution)
+ assert_select "input[type=checkbox][name='transfer[investment_contribution]'][checked]"
+
+ get transfer_url(payment)
+ assert_select "input[name='transfer[investment_contribution]']", count: 0
+ end
+
+ test "turning off the investment contribution makes a plain transfer and reloads the page" do
+ transfer = create_confirmed_transfer(to: accounts(:investment))
+
+ patch transfer_url(transfer),
+ params: { transfer: { investment_contribution: "0" } },
+ headers: { "Accept" => "text/vnd.turbo-stream.html", "Referer" => transactions_url }
+
+ assert_response :success
+ assert_includes response.body, %(action="redirect")
+ assert_equal "funds_movement", transfer.outflow_transaction.reload.kind
+ end
+
+ test "turning the investment contribution back on restores it" do
+ transfer = create_confirmed_transfer(to: accounts(:investment))
+ transfer.update_investment_contribution!(false)
+
+ patch transfer_url(transfer), params: { transfer: { investment_contribution: "1" } }
+
+ assert_redirected_to transactions_url
+ assert_equal "investment_contribution", transfer.outflow_transaction.reload.kind
+ end
+
+ test "switching the investment contribution requires write permission on both transfer sides" do
+ sign_in users(:family_member)
+ accounts(:investment).account_shares.create!(user: users(:family_member), permission: "read_only")
+ transfer = create_confirmed_transfer(to: accounts(:investment))
+
+ patch transfer_url(transfer), params: { transfer: { investment_contribution: "0" } }
+
+ assert_redirected_to transactions_url
+ assert_equal "investment_contribution", transfer.outflow_transaction.reload.kind
+ end
+
test "mark_as_recurring creates a recurring transfer" do
transfer = transfers(:one)
family = users(:family_admin).family
@@ -841,6 +885,13 @@ class TransfersControllerTest < ActionDispatch::IntegrationTest
end
private
+ def create_confirmed_transfer(to:)
+ outflow_entry = create_transaction(date: Date.current, account: accounts(:depository), amount: 500)
+ inflow_entry = create_transaction(date: Date.current, account: to, amount: -500)
+
+ Transfer.create!(inflow_transaction: inflow_entry.transaction, outflow_transaction: outflow_entry.transaction).tap(&:confirm!)
+ end
+
# A loan owned by family_member and not shared with family_admin
def member_loan
accounts(:loan).tap { |loan| loan.update!(owner: users(:family_member)) }
diff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rb
index 6b263c810b..2fd20d75e9 100644
--- a/test/models/account/provider_import_adapter_test.rb
+++ b/test/models/account/provider_import_adapter_test.rb
@@ -130,6 +130,36 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCase
assert_equal "loan_payment", checking_entry.transaction.reload.kind
end
+ test "re-importing a contribution the user turned into a plain transfer keeps that choice" do
+ checking_entry = @adapter.import_transaction(
+ external_id: "plaid_checking_to_broker",
+ amount: 300.00,
+ currency: "USD",
+ date: Date.current,
+ name: "To broker",
+ source: "plaid"
+ )
+ broker_entry = accounts(:investment).entries.create!(
+ name: "From checking", date: Date.current, amount: -300, currency: "USD", entryable: Transaction.new
+ )
+ transfer = Transfer.create!(inflow_transaction: broker_entry.transaction, outflow_transaction: checking_entry.transaction)
+ transfer.confirm!
+ transfer.update_investment_contribution!(false)
+
+ # A provider kind hint makes the adapter re-derive the leg from its transfer.
+ @adapter.import_transaction(
+ external_id: "plaid_checking_to_broker",
+ amount: 300.00,
+ currency: "USD",
+ date: Date.current,
+ name: "To broker",
+ source: "plaid",
+ kind: "standard"
+ )
+
+ assert_equal "funds_movement", checking_entry.transaction.reload.kind
+ end
+
test "re-importing an unconfirmed auto-matched leg does not give it a transfer kind" do
loan_entry = Account::ProviderImportAdapter.new(accounts(:loan)).import_transaction(
external_id: "plaid_loan_inflow_pending", amount: -200.00, currency: "USD",
diff --git a/test/models/assistant/function/update_transfer_test.rb b/test/models/assistant/function/update_transfer_test.rb
new file mode 100644
index 0000000000..c0dd42c2d6
--- /dev/null
+++ b/test/models/assistant/function/update_transfer_test.rb
@@ -0,0 +1,89 @@
+require "test_helper"
+
+class Assistant::Function::UpdateTransferTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @function = Assistant::Function::UpdateTransfer.new(@user)
+ @transfer = create_transfer(from_account: accounts(:depository), to_account: accounts(:investment), amount: 300)
+ @transfer.outflow_transaction.update!(kind: "investment_contribution")
+ end
+
+ test "is registered for the assistant and MCP" do
+ assert_includes Assistant.function_classes(@user), Assistant::Function::UpdateTransfer
+ end
+
+ test "turns an investment contribution into a plain transfer by either transaction" do
+ result = @function.call("transaction_id" => @transfer.inflow_transaction.id, "investment_contribution" => false)
+
+ assert result[:success]
+ assert_equal false, result[:transfer][:investment_contribution]
+ assert_equal "funds_movement", result[:transfer][:outflow][:kind]
+ assert_equal "funds_movement", @transfer.outflow_transaction.reload.kind
+ assert @transfer.outflow_transaction.locked?(:kind)
+ end
+
+ test "turns a plain transfer back into an investment contribution" do
+ assert @transfer.reload.update_investment_contribution!(false)
+
+ result = @function.call("transfer_id" => @transfer.id, "investment_contribution" => true)
+
+ assert result[:success]
+ assert_equal true, result[:transfer][:investment_contribution]
+ assert_equal "investment_contribution", @transfer.outflow_transaction.reload.kind
+ end
+
+ test "dry run describes the change without making it" do
+ result = @function.call("transfer_id" => @transfer.id, "investment_contribution" => false, "dry_run" => true)
+
+ assert result[:success]
+ assert result[:dry_run]
+ assert_equal true, result[:transfer][:investment_contribution]
+ assert_equal "investment_contribution", @transfer.outflow_transaction.reload.kind
+ end
+
+ test "refuses a transfer that cannot be an investment contribution" do
+ payment = create_transfer(from_account: accounts(:depository), to_account: accounts(:credit_card), amount: 50)
+
+ result = @function.call("transfer_id" => payment.id, "investment_contribution" => false)
+
+ assert_not result[:success]
+ assert_equal "not_switchable", result[:error]
+ end
+
+ test "requires write access to both accounts" do
+ accounts(:investment).account_shares.create!(user: users(:family_member), permission: "read_only")
+
+ result = Assistant::Function::UpdateTransfer.new(users(:family_member))
+ .call("transfer_id" => @transfer.id, "investment_contribution" => false)
+
+ assert_not result[:success]
+ assert_equal "not_found", result[:error]
+ assert_equal "investment_contribution", @transfer.outflow_transaction.reload.kind
+ end
+
+ test "reads a string false from a loose client as false" do
+ result = @function.call("transfer_id" => @transfer.id, "investment_contribution" => "false")
+
+ assert result[:success]
+ assert_equal "funds_movement", @transfer.outflow_transaction.reload.kind
+ end
+
+ test "rejects a value that is not a boolean" do
+ assert @transfer.reload.update_investment_contribution!(false)
+
+ result = @function.call("transfer_id" => @transfer.id, "investment_contribution" => "no")
+
+ assert_not result[:success]
+ assert_equal "invalid_arguments", result[:error]
+ assert_equal "funds_movement", @transfer.outflow_transaction.reload.kind
+ end
+
+ test "requires a change to make" do
+ result = @function.call("transfer_id" => @transfer.id)
+
+ assert_not result[:success]
+ assert_equal "invalid_arguments", result[:error]
+ end
+end
diff --git a/test/models/family/data_exporter_test.rb b/test/models/family/data_exporter_test.rb
index f6bcc2c03f..3a300c5bba 100644
--- a/test/models/family/data_exporter_test.rb
+++ b/test/models/family/data_exporter_test.rb
@@ -932,6 +932,21 @@ class Family::DataExporterTest < ActiveSupport::TestCase
end
end
+ test "exports a user's choice to make an investment transfer a plain transfer" do
+ brokerage = @family.accounts.create!(name: "Brokerage", accountable: Investment.new, balance: 0, currency: "USD")
+ outflow = create_transaction_entry(@account, amount: 100, date: Date.parse("2024-01-15"), name: "To brokerage")
+ inflow = create_transaction_entry(brokerage, amount: -100, date: Date.parse("2024-01-15"), name: "From checking")
+ transfer = Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable, status: "confirmed")
+ assert transfer.update_investment_contribution!(false)
+
+ Zip::File.open_buffer(@exporter.generate_export) do |zip|
+ ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
+ transfer_data = ndjson_records.find { |record| record["type"] == "Transfer" && record.dig("data", "id") == transfer.id }
+
+ assert_equal false, transfer_data["data"]["investment_contribution"]
+ end
+ end
+
test "exports transfer decisions and rejected transfers in NDJSON" do
destination_account = @family.accounts.create!(
name: "Savings Account",
@@ -967,6 +982,7 @@ class Family::DataExporterTest < ActiveSupport::TestCase
assert_equal transfer_outflow.entryable.id, transfer_data["data"]["outflow_transaction_id"]
assert_equal "confirmed", transfer_data["data"]["status"]
assert_equal "Confirmed by user", transfer_data["data"]["notes"]
+ assert_nil transfer_data["data"]["investment_contribution"]
rejected_transfer_data = ndjson_records.find { |record| record["type"] == "RejectedTransfer" && record.dig("data", "id") == rejected_transfer.id }
assert rejected_transfer_data
diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rb
index 727412ca8a..8fe9c2c7a9 100644
--- a/test/models/family/data_importer_test.rb
+++ b/test/models/family/data_importer_test.rb
@@ -1638,6 +1638,24 @@ class Family::DataImporterTest < ActiveSupport::TestCase
assert_equal "Candidate outflow", rejected_transfer.outflow_transaction.entry.name
end
+ test "restores a transfer the user made a plain transfer instead of an investment contribution" do
+ ndjson = build_ndjson([
+ { type: "Account", data: { id: "checking", name: "Checking", balance: "1000", currency: "USD", accountable_type: "Depository" } },
+ { type: "Account", data: { id: "brokerage", name: "Brokerage", balance: "2500", currency: "USD", accountable_type: "Investment" } },
+ { type: "Transaction", data: { id: "fx-outflow", account_id: "checking", date: "2024-01-15", amount: "100.00", name: "To brokerage", currency: "USD", kind: "funds_movement" } },
+ { type: "Transaction", data: { id: "fx-inflow", account_id: "brokerage", date: "2024-01-15", amount: "-100.00", name: "From checking", currency: "USD", kind: "funds_movement" } },
+ { type: "Transfer", data: { id: "transfer-1", inflow_transaction_id: "fx-inflow", outflow_transaction_id: "fx-outflow", status: "confirmed", investment_contribution: false } }
+ ])
+
+ Family::DataImporter.new(@family, ndjson).import!
+
+ outflow = Transaction.joins(:entry).find_by!(entries: { name: "To brokerage" })
+ assert_equal "funds_movement", outflow.kind
+ assert_nil outflow.category
+ assert outflow.locked?(:kind)
+ assert_equal false, outflow.transfer_as_outflow.investment_contribution_choice
+ end
+
test "imports a pending transfer without applying transfer kinds" do
ndjson = build_ndjson([
{ type: "Account", data: { id: "checking", name: "Checking", balance: "1000", currency: "USD", accountable_type: "Depository" } },
diff --git a/test/models/transfer_test.rb b/test/models/transfer_test.rb
index ac6db73ccd..55e69a3437 100644
--- a/test/models/transfer_test.rb
+++ b/test/models/transfer_test.rb
@@ -227,6 +227,73 @@ class TransferTest < ActiveSupport::TestCase
assert_equal "standard", transfer.inflow_transaction.reload.kind
end
+ test "update_investment_contribution! turns a contribution into a plain transfer and back" do
+ transfer = create_pending_transfer(from: accounts(:depository), to: accounts(:investment))
+ transfer.confirm!
+ assert transfer.investment_contribution?
+
+ assert transfer.update_investment_contribution!(false)
+
+ outflow = transfer.outflow_transaction.reload
+ assert_equal "funds_movement", outflow.kind
+ assert_nil outflow.category
+ assert outflow.locked?(:kind)
+ assert_not transfer.investment_contribution?
+ assert_not transfer.categorizable?
+
+ assert transfer.update_investment_contribution!(true)
+
+ outflow.reload
+ assert_equal "investment_contribution", outflow.kind
+ assert_equal families(:dylan_family).investment_contributions_category, outflow.category
+ assert transfer.investment_contribution?
+ assert transfer.categorizable?
+ end
+
+ test "update_investment_contribution! keeps a category the user chose" do
+ transfer = create_pending_transfer(from: accounts(:depository), to: accounts(:investment))
+ transfer.outflow_transaction.update!(category: categories(:food_and_drink))
+ transfer.confirm!
+
+ transfer.update_investment_contribution!(false)
+
+ assert_equal categories(:food_and_drink), transfer.outflow_transaction.reload.category
+ end
+
+ test "update_investment_contribution! leaves transfers that cannot be a contribution alone" do
+ payment = create_pending_transfer(from: accounts(:depository), to: accounts(:credit_card))
+ payment.confirm!
+ pending = create_pending_transfer(from: accounts(:depository), to: accounts(:investment))
+
+ assert_not payment.update_investment_contribution!(false)
+ assert_not pending.update_investment_contribution!(false)
+
+ assert_equal "cc_payment", payment.outflow_transaction.reload.kind
+ assert_not payment.outflow_transaction.locked?(:kind)
+ assert_equal "standard", pending.outflow_transaction.reload.kind
+ end
+
+ test "kind_for_leg keeps a plain transfer the user chose over a contribution" do
+ transfer = create_pending_transfer(from: accounts(:depository), to: accounts(:investment))
+ transfer.confirm!
+ transfer.update_investment_contribution!(false)
+
+ assert_equal "funds_movement", transfer.reload.kind_for_leg(transfer.outflow_transaction)
+ assert_equal "funds_movement", transfer.kind_for_leg(transfer.inflow_transaction)
+ end
+
+ test "reject! drops the contribution choice with the transfer" do
+ transfer = create_pending_transfer(from: accounts(:depository), to: accounts(:investment))
+ transfer.confirm!
+ transfer.update_investment_contribution!(false)
+
+ transfer.reject!
+
+ outflow = transfer.outflow_transaction.reload
+ assert_equal "standard", outflow.kind
+ assert_not outflow.locked?(:kind)
+ end
+
test "kind_for_account returns investment_contribution for investment accounts" do
assert_equal "investment_contribution", Transfer.kind_for_account(accounts(:investment))
end