Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Allow transaction-to-trade conversion for crypto exchange accounts (#3936)

Orange🍊7339805c5be5
diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rb
index 57bb87131b..3103ecdd3d 100644
--- a/app/controllers/transactions_controller.rb
+++ b/app/controllers/transactions_controller.rb
@@ -329,13 +329,14 @@ class TransactionsController < ApplicationController
redirect_back_or_to transactions_path
end
+ # Offer transaction conversion only for account types that can own trades.
def convert_to_trade
@transaction = accessible_transactions.includes(entry: :account).find(params[:id])
@entry = @transaction.entry
return unless require_account_permission!(@entry.account)
- unless @entry.account.investment?
+ unless @entry.account.supports_trades?
flash[:alert] = t("transactions.convert_to_trade.errors.not_investment_account")
redirect_back_or_to transactions_path
return
@@ -344,6 +345,7 @@ class TransactionsController < ApplicationController
render :convert_to_trade
end
+ # Lock and recheck the source entry before creating a trade and excluding the transaction.
def create_trade_from_transaction
@transaction = accessible_transactions.includes(entry: :account).find(params[:id])
@entry = @transaction.entry
@@ -351,7 +353,7 @@ class TransactionsController < ApplicationController
return unless require_account_permission!(@entry.account)
# Pre-transaction validations
- unless @entry.account.investment?
+ unless @entry.account.supports_trades?
flash[:alert] = t("transactions.convert_to_trade.errors.not_investment_account")
redirect_back_or_to transactions_path
return
@@ -367,15 +369,25 @@ class TransactionsController < ApplicationController
security = resolve_security_for_conversion
return if performed? # Early exit if redirect already happened
- # Validate and calculate qty/price before transaction
- qty, price = calculate_qty_and_price
- return if performed? # Early exit if redirect already happened
-
activity_label = params[:investment_activity_label].presence
- # Infer sell from amount sign: negative amount = money coming in = sell
- is_sell = activity_label == "Sell" || (activity_label.blank? && @entry.amount < 0)
-
+ # Serialize replacements on the source, including requests already in flight.
ActiveRecord::Base.transaction do
+ # Entry#transaction is its delegated transaction record, so use an
+ # explicit DB transaction rather than ActiveRecord's instance with_lock.
+ @entry.lock!
+ if @entry.excluded?
+ flash[:alert] = t("transactions.convert_to_trade.errors.already_converted")
+ redirect_back_or_to transactions_path
+ next
+ end
+
+ # Infer missing values from the locked source amount, including edits
+ # committed while the security was being resolved.
+ qty, price = calculate_qty_and_price
+ next if performed?
+
+ # Infer sell from the refreshed source: negative amount means money in.
+ is_sell = activity_label == "Sell" || (activity_label.blank? && @entry.amount < 0)
# For trades: positive qty = buy (money out), negative qty = sell (money in)
signed_qty = is_sell ? -qty : qty
trade_amount = qty * price
@@ -413,6 +425,8 @@ class TransactionsController < ApplicationController
@entry.update!(excluded: true)
end
+ return if performed?
+
flash[:notice] = t("transactions.convert_to_trade.success")
redirect_to account_path(@entry.account), status: :see_other
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved => e
@@ -760,6 +774,7 @@ class TransactionsController < ApplicationController
# Helper methods for convert_to_trade
+ # Resolve the allowed ticker/provider before locking the source, avoiding network calls under its lock.
def resolve_security_for_conversion
user_country = Current.family.country
@@ -828,6 +843,7 @@ class TransactionsController < ApplicationController
end
end
+ # Validate submitted trade values and infer a missing value from the locked amount.
def calculate_qty_and_price
amount = @entry.amount.abs
qty = params[:qty].present? ? params[:qty].to_d.abs : nil
diff --git a/app/views/transactions/show.html.erb b/app/views/transactions/show.html.erb
index dd848b9cb9..6fe28c5fb4 100644
--- a/app/views/transactions/show.html.erb
+++ b/app/views/transactions/show.html.erb
@@ -379,8 +379,8 @@
) %>
</div>
<% end %>
- <!-- Convert to Trade (Investment Accounts Only, not already converted) -->
- <% if @entry.account.investment? && @entry.entryable.is_a?(Transaction) && [email protected]? %>
+ <!-- Convert to Trade (trade-capable accounts, not already converted) -->
+ <% if @entry.account.supports_trades? && @entry.entryable.is_a?(Transaction) && [email protected]? %>
<div class="flex items-center justify-between gap-2 p-3">
<div class="text-sm space-y-1">
<h4 class="text-primary"><%= t(".convert_to_trade_title") %></h4>
diff --git a/test/controllers/transactions_trade_conversion_test.rb b/test/controllers/transactions_trade_conversion_test.rb
new file mode 100644
index 0000000000..f29ee68b9c
--- /dev/null
+++ b/test/controllers/transactions_trade_conversion_test.rb
@@ -0,0 +1,190 @@
+require "test_helper"
+
+class TransactionsTradeConversionTest < ActionDispatch::IntegrationTest
+ include EntriesTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @account = accounts(:crypto)
+ @account.crypto.update!(subtype: "exchange")
+ @entry = create_transaction(account: @account, amount: 100)
+ sign_in @user
+ end
+
+ test "trade-capable accounts return the conversion modal" do
+ [ @account, accounts(:investment) ].each do |account|
+ entry = create_transaction(account: account)
+
+ get convert_to_trade_transaction_url(entry.transaction),
+ params: { activity_label: "Buy" }, headers: { "Turbo-Frame" => "modal" }
+
+ assert_response :success
+ assert_select "turbo-frame#modal"
+ assert_select "form[action=?]", create_trade_from_transaction_transaction_path(entry.transaction)
+ end
+ end
+
+ test "conversion action follows the account's trade capability" do
+ [ @account, accounts(:investment), accounts(:depository) ].each do |account|
+ entry = create_transaction(account: account)
+
+ get transaction_url(entry), headers: { "Turbo-Frame" => "drawer" }
+
+ assert_response :success
+ assert_select "form[action=?]", convert_to_trade_transaction_path(entry.transaction),
+ count: account.supports_trades? ? 1 : 0
+ end
+
+ @account.crypto.update!(subtype: "wallet")
+ get transaction_url(@entry), headers: { "Turbo-Frame" => "drawer" }
+ assert_response :success
+ assert_select "form[action=?]", convert_to_trade_transaction_path(@entry.transaction), count: 0
+ end
+
+ %w[Buy Sell].each do |label|
+ test "converts a synced crypto exchange transaction to a #{label.downcase}" do
+ @entry.update!(external_id: "provider-transaction", amount: label == "Buy" ? 100 : -100)
+
+ assert_difference "Trade.count", 1 do
+ post create_trade_from_transaction_transaction_url(@entry.transaction), params: {
+ security_id: securities(:aapl).id, qty: 2, price: 50, investment_activity_label: label
+ }
+ assert_nil flash[:alert], flash[:alert]
+ end
+
+ assert_redirected_to account_path(@account)
+ trade_entry = @account.entries.where(entryable_type: "Trade").order(:created_at).last
+ assert_equal label, trade_entry.trade.investment_activity_label
+ assert_equal label == "Buy" ? 2 : -2, trade_entry.trade.qty
+ assert_equal label == "Buy" ? 100 : -100, trade_entry.amount
+ assert_equal @entry.date, trade_entry.date
+ assert_equal @entry.currency, trade_entry.currency
+ assert trade_entry.user_modified?
+ assert @entry.reload.excluded?
+ assert_equal "provider-transaction", @entry.external_id
+ end
+ end
+
+ test "wallets and bank accounts cannot open or submit the conversion" do
+ @account.crypto.update!(subtype: "wallet")
+
+ [ @account, accounts(:depository) ].each do |account|
+ entry = create_transaction(account: account)
+ get convert_to_trade_transaction_url(entry.transaction), headers: { "Turbo-Frame" => "modal" }
+ assert_redirected_to transactions_path
+
+ assert_no_difference "Trade.count" do
+ post create_trade_from_transaction_transaction_url(entry.transaction), params: {
+ security_id: securities(:aapl).id, qty: 2, price: 50, investment_activity_label: "Buy"
+ }
+ end
+ assert_redirected_to transactions_path
+ assert_not entry.reload.excluded?
+ end
+ end
+
+ test "an excluded transaction cannot produce another trade" do
+ @entry.update!(excluded: true)
+
+ assert_no_difference "Trade.count" do
+ post create_trade_from_transaction_transaction_url(@entry.transaction), params: {
+ security_id: securities(:aapl).id, qty: 2, price: 50, investment_activity_label: "Buy"
+ }
+ end
+ assert_redirected_to transactions_path
+ assert @entry.reload.excluded?
+ end
+
+ test "invalid trade quantities leave the original transaction unchanged" do
+ assert_no_difference "Trade.count" do
+ post create_trade_from_transaction_transaction_url(@entry.transaction), params: {
+ security_id: securities(:aapl).id, qty: 0, price: 50, investment_activity_label: "Buy"
+ }
+ end
+ assert_redirected_to transactions_path
+ assert_not @entry.reload.excluded?
+ end
+
+ test "a conversion completed during security lookup cannot be repeated" do
+ [ @account, accounts(:investment) ].each do |account|
+ entry = create_transaction(account: account)
+ security = securities(:aapl)
+ Security.expects(:find_by).with do |attributes|
+ if attributes == { id: security.id }
+ Entry.where(id: entry.id).update_all(excluded: true)
+ true
+ end
+ end.returns(security)
+
+ assert_no_difference "Trade.count" do
+ post create_trade_from_transaction_transaction_url(entry.transaction), params: {
+ security_id: security.id, qty: 2, price: 50, investment_activity_label: "Buy"
+ }
+ end
+ assert_redirected_to transactions_path
+ assert_equal I18n.t("transactions.convert_to_trade.errors.already_converted"), flash[:alert]
+ end
+ end
+
+ test "inferred conversion values use an amount edited before the source lock" do
+ [ @account, accounts(:investment) ].each do |account|
+ [ { qty: 2 }, { price: 50 } ].each do |trade_params|
+ entry = create_transaction(account: account, amount: 100)
+ security = securities(:aapl)
+ Security.expects(:find_by).with do |attributes|
+ if attributes == { id: security.id }
+ Entry.where(id: entry.id).update_all(amount: -200)
+ true
+ end
+ end.returns(security)
+
+ assert_difference "Trade.count", 1 do
+ post create_trade_from_transaction_transaction_url(entry.transaction),
+ params: trade_params.merge(security_id: security.id)
+ end
+ assert_nil flash[:alert]
+ assert_redirected_to account_path(account)
+ trade_entry = account.entries.where(entryable_type: "Trade").order(:created_at).last
+ assert_equal(-200, trade_entry.amount)
+ assert_equal "Sell", trade_entry.trade.investment_activity_label
+ assert_equal trade_params[:qty] ? -2 : -4, trade_entry.trade.qty
+ assert_equal trade_params[:qty] ? 100 : 50, trade_entry.trade.price
+ assert entry.reload.excluded?
+ end
+ end
+ end
+
+ test "annotation-only and read-only shares cannot convert" do
+ member = users(:family_member)
+ share = @account.account_shares.create!(user: member, permission: "read_write")
+ sign_in member
+
+ %w[read_write read_only].each do |permission|
+ share.update!(permission: permission)
+ get convert_to_trade_transaction_url(@entry.transaction), headers: { "Turbo-Frame" => "modal" }
+ assert_response :redirect
+
+ assert_no_difference "Trade.count" do
+ post create_trade_from_transaction_transaction_url(@entry.transaction), params: {
+ security_id: securities(:aapl).id, qty: 2, price: 50, investment_activity_label: "Buy"
+ }
+ end
+ assert_response :redirect
+ assert_not @entry.reload.excluded?
+ end
+ end
+
+ test "another family cannot convert the transaction" do
+ sign_in users(:empty)
+
+ get convert_to_trade_transaction_url(@entry.transaction), headers: { "Turbo-Frame" => "modal" }
+ assert_response :not_found
+
+ assert_no_difference "Trade.count" do
+ post create_trade_from_transaction_transaction_url(@entry.transaction), params: {
+ security_id: securities(:aapl).id, qty: 2, price: 50, investment_activity_label: "Buy"
+ }
+ end
+ assert_not @entry.reload.excluded?
+ end
+end
diff --git a/test/system/crypto_trade_conversion_test.rb b/test/system/crypto_trade_conversion_test.rb
new file mode 100644
index 0000000000..6d9733dcb1
--- /dev/null
+++ b/test/system/crypto_trade_conversion_test.rb
@@ -0,0 +1,29 @@
+require "application_system_test_case"
+
+class CryptoTradeConversionTest < ApplicationSystemTestCase
+ setup do
+ @account = accounts(:crypto)
+ @account.crypto.update!(subtype: "exchange")
+ @entry = @account.entries.create!(
+ name: "Crypto purchase", date: Date.current, amount: 100, currency: "USD",
+ external_id: "synced-crypto-purchase", entryable: Transaction.new
+ )
+ sign_in users(:family_admin)
+ end
+
+ test "buy activity on a crypto exchange opens the conversion modal" do
+ visit account_url(@account, tab: "activity")
+
+ within "##{dom_id(@entry)}" do
+ find("[data-activity-label-quick-edit-target='badge']").click
+ find("[data-label='Buy']").click
+ end
+
+ within "turbo-frame#modal" do
+ assert_selector "form[action='#{create_trade_from_transaction_transaction_path(@entry.transaction)}']"
+ assert_selector "select#investment_activity_label option[value='Buy'][selected]", visible: false
+ page.save_screenshot(Rails.root.join("tmp/screenshots/crypto-trade-conversion.png"))
+ end
+ assert_no_text "Content missing"
+ end
+end