Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Resolve a goal's transfer pledge from deposits booked in the app (#4381)

jaysbeekaye9003c29b633
diff --git a/app/controllers/transfer_matches_controller.rb b/app/controllers/transfer_matches_controller.rb
index 952d7e967b..d3032b9ede 100644
--- a/app/controllers/transfer_matches_controller.rb
+++ b/app/controllers/transfer_matches_controller.rb
@@ -22,6 +22,13 @@ class TransferMatchesController < ApplicationController
@transfer.sync_account_later
+ # A new counterpart for an outflow is a deposit booked on the target
+ # account, which can resolve its transfer pledge. Matching two existing
+ # entries books nothing new.
+ if transfer_match_params[:method] == "new" && @entry.amount.positive?
+ GoalPledge::Reconciler.run_after_commit(@transfer.inflow_transaction.entry)
+ end
+
redirect_back_or_to transactions_path, notice: t(".success")
end
diff --git a/app/models/account.rb b/app/models/account.rb
index fed971e5fb..f52f189e39 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -711,6 +711,12 @@ class Account < ApplicationRecord
manual?
end
+ # Only an account linked to a goal can hold a goal pledge, so callers use
+ # this to skip pledge reconciliation for every other account.
+ def linked_to_goal?
+ goal_accounts.exists?
+ end
+
# True when the account has no live sync provider attached. Mirrors the
# `Account.manual` scope so per-instance checks don't drift from the query.
def manual?
diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rb
index 29e3d4a20b..ccb4479d0a 100644
--- a/app/models/account/provider_import_adapter.rb
+++ b/app/models/account/provider_import_adapter.rb
@@ -748,6 +748,15 @@ class Account::ProviderImportAdapter
)
entry.save!
+
+ # Coins arriving in a wallet are its deposits (GoalPledge.deposit_trade?).
+ # After commit, because a wallet writes the trade inside its own
+ # transaction. A re-imported trade is skipped by the reconciler once
+ # stamped.
+ if GoalPledge.deposit_trade?(entry) && account_linked_to_any_goal?
+ GoalPledge::Reconciler.run_after_commit(entry)
+ end
+
entry
end
end
@@ -1156,7 +1165,7 @@ class Account::ProviderImportAdapter
def account_linked_to_any_goal?
return @account_linked_to_any_goal if defined?(@account_linked_to_any_goal)
- @account_linked_to_any_goal = account.goal_accounts.exists?
+ @account_linked_to_any_goal = account.linked_to_goal?
end
# Writes provider-owned metadata onto the transaction.
diff --git a/app/models/goal_pledge.rb b/app/models/goal_pledge.rb
index 02e432ae25..b2047117f8 100644
--- a/app/models/goal_pledge.rb
+++ b/app/models/goal_pledge.rb
@@ -59,12 +59,15 @@ class GoalPledge < ApplicationRecord
return false unless entry.account_id == account_id
is_valuation = entry.entryable.is_a?(Valuation)
+ is_trade = entry.entryable.is_a?(Trade)
if is_valuation
# Never match a valuation delta on an investment or crypto account: it may
# be a market move, not a deposit, and would false-match.
return false if account&.balance_type == :investment
return false if valuation_delta.nil? || valuation_delta.to_d <= 0
+ elsif is_trade
+ return false unless kind_transfer? && self.class.deposit_trade?(entry)
elsif kind_transfer? && !entry.amount.to_d.negative?
return false
end
@@ -73,8 +76,16 @@ class GoalPledge < ApplicationRecord
latest = [ created_at.to_date + MATCH_DATE_TOLERANCE_DAYS.days, expires_at.to_date ].max
return false unless entry.date >= earliest && entry.date <= latest
- native_amount = (is_valuation ? valuation_delta.to_d : entry.amount.to_d).abs
- txn_amount = goal.convert_money!(Money.new(native_amount, entry.currency.presence || account.currency), date: entry.date).amount
+ native_money = if is_valuation
+ Money.new(valuation_delta.to_d.abs, entry.currency.presence || account.currency)
+ elsif is_trade
+ # A deposit trade carries no cash amount; what arrived is the coins, at
+ # the trade's price.
+ Money.new((entry.trade.qty * entry.trade.price).abs, entry.trade.currency)
+ else
+ Money.new(entry.amount.to_d.abs, entry.currency.presence || account.currency)
+ end
+ txn_amount = goal.convert_money!(native_money, date: entry.date).amount
pledge_amount = amount.to_d
diff_abs = (txn_amount - pledge_amount).abs
@@ -105,6 +116,40 @@ class GoalPledge < ApplicationRecord
end
end
+ # Coins arriving in a crypto account: a self-custody wallet books them as a
+ # transfer-in trade with no cash side, so that trade is the account's
+ # deposit. A buy only swaps cash already in the account for coins, and a
+ # transfer-in on an investment account moves securities, so neither counts.
+ def self.deposit_trade?(entry)
+ trade = entry.entryable
+ return false unless trade.is_a?(Trade)
+ return false unless entry.account&.accountable_type == "Crypto"
+
+ trade.investment_activity_label == Trade::TRANSFER_LABEL && trade.qty.to_d.positive?
+ end
+
+ # Trade-backed match: the trade is stamped like a transaction, since a
+ # wallet re-imports every movement on each sync and the same trade must not
+ # pay a second pledge. There is no transaction to link.
+ def resolve_with_trade!(trade)
+ with_lock do
+ raise NotOpenError, "Pledge no longer open" unless status_open?
+
+ trade.with_lock do
+ pledge_id_in_extra = trade.extra.dig("goal", "pledge_id")
+ if pledge_id_in_extra.present? && pledge_id_in_extra != id
+ raise AlreadyClaimedError, "Trade ##{trade.id} already claimed by pledge ##{pledge_id_in_extra}"
+ end
+
+ extra = trade.extra || {}
+ extra["goal"] = (extra["goal"] || {}).merge("pledge_id" => id)
+ trade.update!(extra: extra)
+
+ update!(status: "matched")
+ end
+ end
+ end
+
# Valuation-backed match: no transaction to stamp, just flip the pledge.
def resolve_with_valuation!
with_lock do
diff --git a/app/models/goal_pledge/reconciler.rb b/app/models/goal_pledge/reconciler.rb
index 81de43746e..8a992a4bd2 100644
--- a/app/models/goal_pledge/reconciler.rb
+++ b/app/models/goal_pledge/reconciler.rb
@@ -10,6 +10,15 @@ class GoalPledge::Reconciler
@valuation_delta = valuation_delta
end
+ # For an entry booked in the app, where the caller may already hold a
+ # transaction (the API wraps trade creation in one). Waits for every open
+ # transaction to commit, so a rolled-back entry never resolves a pledge
+ # and a database error rescued in #run can't leave the caller's
+ # transaction aborted. Runs at once when no transaction is open.
+ def self.run_after_commit(entry)
+ ActiveRecord.after_all_transactions_commit { new(entry).run }
+ end
+
def run
return unless eligible_entry?
return if already_stamped?
@@ -27,6 +36,8 @@ class GoalPledge::Reconciler
begin
if entry.entryable.is_a?(Transaction)
pledge.resolve_with!(entry.transaction)
+ elsif entry.entryable.is_a?(Trade)
+ pledge.resolve_with_trade!(entry.trade)
elsif entry.entryable.is_a?(Valuation)
pledge.resolve_with_valuation!
end
@@ -56,13 +67,13 @@ class GoalPledge::Reconciler
return false if entry.account_id.blank?
return false if entry.excluded?
- entry.entryable.is_a?(Transaction) || entry.entryable.is_a?(Valuation)
+ entry.entryable.is_a?(Transaction) || entry.entryable.is_a?(Valuation) || GoalPledge.deposit_trade?(entry)
end
def already_stamped?
- return false unless entry.entryable.is_a?(Transaction)
+ return false if entry.entryable.is_a?(Valuation)
- entry.transaction.extra.dig("goal", "pledge_id").present?
+ entry.entryable.extra.dig("goal", "pledge_id").present?
end
def expected_kind
diff --git a/app/models/rule/action_executor/set_as_transfer_or_payment.rb b/app/models/rule/action_executor/set_as_transfer_or_payment.rb
index b2ac72d204..d5f8529d36 100644
--- a/app/models/rule/action_executor/set_as_transfer_or_payment.rb
+++ b/app/models/rule/action_executor/set_as_transfer_or_payment.rb
@@ -19,6 +19,8 @@ class Rule::ActionExecutor::SetAsTransferOrPayment < Rule::ActionExecutor
target_account = family.accounts.find_by_id(value)
return 0 unless target_account
scope = transaction_scope.with_entry
+ # Checked once per run, not per transaction.
+ reconcile_pledges = target_account.linked_to_goal?
count_modified_resources(scope) do |txn|
entry = txn.entry
@@ -30,6 +32,8 @@ class Rule::ActionExecutor::SetAsTransferOrPayment < Rule::ActionExecutor
end
transfer.sync_account_later
+ # An outflow's new counterpart is a deposit on the target account.
+ GoalPledge::Reconciler.run_after_commit(transfer.inflow_transaction.entry) if reconcile_pledges && entry.amount.positive?
end
end
end
diff --git a/app/models/trade/create_form.rb b/app/models/trade/create_form.rb
index 64bc06192c..9dad48f7f2 100644
--- a/app/models/trade/create_form.rb
+++ b/app/models/trade/create_form.rb
@@ -194,6 +194,7 @@ class Trade::CreateForm
if entry.save
entry.lock_saved_attributes!
account.sync_later
+ GoalPledge::Reconciler.run_after_commit(entry) if signed_amount.negative?
end
entry
diff --git a/app/models/transfer/creator.rb b/app/models/transfer/creator.rb
index 6b203756e2..4fefe48c23 100644
--- a/app/models/transfer/creator.rb
+++ b/app/models/transfer/creator.rb
@@ -65,6 +65,11 @@ class Transfer::Creator
transfer.sync_account_later
+ # After commit, including a caller's own transaction, so a reconcile
+ # error can never roll back the transfer. Only the inflow can resolve a
+ # transfer pledge.
+ GoalPledge::Reconciler.run_after_commit(transfer.inflow_transaction.entry)
+
transfer
rescue ActiveRecord::RecordNotUnique
# Concurrent-request backstop: two near-simultaneous submissions both
diff --git a/docs/llm-guides/goals.md b/docs/llm-guides/goals.md
index 6d21b2d168..ca2d593628 100644
--- a/docs/llm-guides/goals.md
+++ b/docs/llm-guides/goals.md
@@ -28,6 +28,13 @@ Account::ProviderImportAdapter#import_transaction
Account::ReconciliationManager#reconcile
→ GoalPledge::Reconciler.new(prepared_valuation).run (manual_save path)
+In-app transfer deposits (transfer-kind path, after the caller's transaction
+commits, via GoalPledge::Reconciler.run_after_commit):
+Transfer::Creator#create → inflow leg
+TransferMatchesController#create → inflow leg
+Rule::ActionExecutor::SetAsTransferOrPayment → inflow leg (goal-linked accounts only)
+Trade::CreateForm (unlinked cash deposit) → the deposit entry
+
SweepExpiredGoalPledgesJob (cron, every 15 minutes)
→ GoalPledge.open_and_expired_now.find_each(&:expire!)
```
@@ -38,7 +45,7 @@ Model layer:
- `app/models/goal.rb` — balance, pace, status, projection, color map.
- `app/models/goal_pledge.rb` — pledge, match policy, lifecycle.
-- `app/models/goal_pledge/reconciler.rb` — entry-to-pledge resolver, called from the import adapters.
+- `app/models/goal_pledge/reconciler.rb` — entry-to-pledge resolver, called from the import adapters and, through `run_after_commit`, from in-app transfer deposits.
- `app/models/account.rb` — `#manual?` instance method (mirrors the `Account.manual` scope) drives pledge kind detection.
- `app/models/family.rb` — `#savings_inflow_velocity` powers the KPI strip.
diff --git a/test/controllers/trades_controller_test.rb b/test/controllers/trades_controller_test.rb
index fbbb3056be..7cb4bed243 100644
--- a/test/controllers/trades_controller_test.rb
+++ b/test/controllers/trades_controller_test.rb
@@ -2,6 +2,7 @@ require "test_helper"
class TradesControllerTest < ActionDispatch::IntegrationTest
include EntryableResourceInterfaceTest
+ include GoalPledgeTestHelper
setup do
sign_in @user = users(:family_admin)
@@ -536,6 +537,32 @@ class TradesControllerTest < ActionDispatch::IntegrationTest
assert @entry.protected_from_sync?, "Entry should be protected from sync"
end
+
+ # we-promise/sure#4226: a deposit with no "from" account books a standalone
+ # inflow on the investment account, which must resolve its pledge.
+ test "an unlinked deposit resolves the account's open transfer pledge" do
+ investment = accounts(:investment)
+ pledge = open_transfer_pledge(investment, amount: 250)
+
+ post trades_url(account_id: investment.id), params: {
+ model: { type: "deposit", date: Date.current, amount: 250, currency: "USD" }
+ }
+
+ entry = investment.entries.order(:created_at).last
+ assert_equal entry.transaction.id, pledge.reload.matched_transaction_id
+ end
+
+ test "an unlinked withdrawal leaves the pledge open" do
+ investment = accounts(:investment)
+ pledge = open_transfer_pledge(investment, amount: 250)
+
+ post trades_url(account_id: investment.id), params: {
+ model: { type: "withdrawal", date: Date.current, amount: 250, currency: "USD" }
+ }
+
+ assert_equal "open", pledge.reload.status
+ end
+
private
# family_member gets the investment account with full control; fixtures
# already share depository with full control and credit_card read-only,
diff --git a/test/controllers/transfer_matches_controller_test.rb b/test/controllers/transfer_matches_controller_test.rb
index bcc6a3a531..1859010f6b 100644
--- a/test/controllers/transfer_matches_controller_test.rb
+++ b/test/controllers/transfer_matches_controller_test.rb
@@ -2,6 +2,7 @@ require "test_helper"
class TransferMatchesControllerTest < ActionDispatch::IntegrationTest
include EntriesTestHelper
+ include GoalPledgeTestHelper
setup do
sign_in @user = users(:family_admin)
@@ -144,6 +145,32 @@ class TransferMatchesControllerTest < ActionDispatch::IntegrationTest
assert_equal category, outflow_txn.category
end
+ # we-promise/sure#4226: marking a synced bank outflow as a transfer to a
+ # manual account creates the deposit there, which must resolve its pledge.
+ test "matching an outflow to a new inflow on a pledged account resolves the pledge" do
+ investment = accounts(:investment)
+ pledge = open_transfer_pledge(investment, amount: 120)
+ outflow = create_transaction(amount: 120, account: accounts(:depository), name: "To brokerage")
+
+ post transaction_transfer_match_path(outflow), params: {
+ transfer_match: { method: "new", target_account_id: investment.id }
+ }
+
+ transfer = Transfer.find_by!(outflow_transaction_id: outflow.transaction.id)
+ assert_equal transfer.inflow_transaction.id, pledge.reload.matched_transaction_id
+ end
+
+ test "matching an inflow to a new outflow leaves the inflow account's pledge open" do
+ pledge = goal_pledges(:open_transfer)
+ inflow = create_transaction(amount: -200, account: pledge.account, name: "From brokerage")
+
+ post transaction_transfer_match_path(inflow), params: {
+ transfer_match: { method: "new", target_account_id: accounts(:investment).id }
+ }
+
+ assert_equal "open", pledge.reload.status
+ end
+
test "new shows the transaction being matched with its account logo" do
Setting.stubs(:brand_fetch_client_id).returns("test-client")
accounts(:credit_card).update!(institution_domain: "example-card.com")
diff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rb
index 70ff72f748..46900f70fc 100644
--- a/test/models/account/provider_import_adapter_test.rb
+++ b/test/models/account/provider_import_adapter_test.rb
@@ -661,6 +661,35 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCase
assert_equal "security is required", exception.message
end
+ test "an imported coin transfer into a goal-linked crypto account resolves its transfer pledge" do
+ crypto = accounts(:crypto)
+ goal = goals(:vacation_italy)
+ goal.goal_accounts.find_or_create_by!(account: crypto)
+ pledge = GoalPledge.create!(goal: goal, account: crypto, amount: 200, currency: "USD", kind: "transfer",
+ status: "open", expires_at: 7.days.from_now)
+ btc = Security.find_or_create_by!(ticker: "CRYPTO:BTC") { |s| s.name = "Bitcoin" }
+
+ entry = Account::ProviderImportAdapter.new(crypto).import_trade(
+ security: btc, quantity: BigDecimal("0.004"), price: 50_000, amount: 0, currency: "USD",
+ date: Date.current, external_id: "onchain-in-1", source: "onchain_wallet", activity_label: Trade::TRANSFER_LABEL
+ )
+
+ assert_equal "matched", pledge.reload.status
+ assert_equal pledge.id, entry.trade.reload.extra.dig("goal", "pledge_id")
+ end
+
+ test "an imported coin transfer on a crypto account linked to no goal runs no reconcile" do
+ crypto = accounts(:crypto)
+ GoalAccount.where(account: crypto).delete_all
+ btc = Security.find_or_create_by!(ticker: "CRYPTO:BTC") { |s| s.name = "Bitcoin" }
+ GoalPledge::Reconciler.any_instance.expects(:run).never
+
+ Account::ProviderImportAdapter.new(crypto).import_trade(
+ security: btc, quantity: BigDecimal("0.004"), price: 50_000, amount: 0, currency: "USD",
+ date: Date.current, external_id: "onchain-in-2", source: "onchain_wallet", activity_label: Trade::TRANSFER_LABEL
+ )
+ end
+
test "imports trade with all parameters" do
investment_account = accounts(:investment)
adapter = Account::ProviderImportAdapter.new(investment_account)
diff --git a/test/models/account_test.rb b/test/models/account_test.rb
index 9529f6de99..bce1d63abf 100644
--- a/test/models/account_test.rb
+++ b/test/models/account_test.rb
@@ -1325,6 +1325,16 @@ class AccountTest < ActiveSupport::TestCase
assert_includes Account.annotatable_by(member).pluck(:id), accounts(:credit_card).id, "read_write share"
end
+ test "linked_to_goal? is true only for an account linked to a goal" do
+ account = @family.accounts.create!(name: "Goal savings", balance: 0, currency: "USD", accountable: Depository.new)
+
+ assert_not account.linked_to_goal?
+
+ goals(:vacation_italy).goal_accounts.create!(account: account)
+
+ assert account.linked_to_goal?
+ end
+
test "institution_domain is normalized to a bare host" do
{
"https://www.tbank.ru/" => "tbank.ru",
diff --git a/test/models/goal_pledge/reconciler_test.rb b/test/models/goal_pledge/reconciler_test.rb
index e84064b79d..6e188f9321 100644
--- a/test/models/goal_pledge/reconciler_test.rb
+++ b/test/models/goal_pledge/reconciler_test.rb
@@ -1,6 +1,8 @@
require "test_helper"
class GoalPledge::ReconcilerTest < ActiveSupport::TestCase
+ include GoalPledgeTestHelper
+
setup do
@pledge = goal_pledges(:open_transfer)
@account = @pledge.account
@@ -102,7 +104,97 @@ class GoalPledge::ReconcilerTest < ActiveSupport::TestCase
assert_not manual_pledge.reload.status_matched?
end
+
+ # A buy moves money within an investment account, so it is not a deposit
+ # and never resolves a transfer pledge.
+ test "an imported buy on a goal-linked investment account leaves its transfer pledge open" do
+ investment = accounts(:investment)
+ pledge = open_transfer_pledge(investment, amount: 200)
+ trade = investment.entries.create!(
+ name: "Buy", date: Date.current, amount: -200, currency: "USD",
+ entryable: Trade.new(qty: 1, price: 200, security: securities(:aapl), currency: "USD", investment_activity_label: "Buy")
+ )
+
+ GoalPledge::Reconciler.new(trade).run
+
+ assert_equal "open", pledge.reload.status
+ end
+
+ # A self-custody wallet books coins arriving at its address as a transfer-in
+ # trade with no cash side, so that trade is the deposit a transfer pledge
+ # waits for.
+ test "coins transferred into a goal-linked crypto account resolve its transfer pledge" do
+ crypto = accounts(:crypto)
+ pledge = open_transfer_pledge(crypto, amount: 200)
+ entry = create_coin_transfer(crypto, qty: BigDecimal("0.004"), price: 50_000)
+
+ GoalPledge::Reconciler.new(entry).run
+
+ assert_equal "matched", pledge.reload.status
+ assert_nil pledge.matched_transaction_id
+ assert_equal pledge.id, entry.trade.reload.extra.dig("goal", "pledge_id")
+ end
+
+ # Every wallet sync re-imports every movement, so the trade that paid one
+ # pledge must not pay the next one as well.
+ test "a coin transfer that resolved one pledge does not resolve another" do
+ crypto = accounts(:crypto)
+ first = open_transfer_pledge(crypto, amount: 200)
+ entry = create_coin_transfer(crypto, qty: BigDecimal("0.004"), price: 50_000)
+ GoalPledge::Reconciler.new(entry).run
+ assert_equal "matched", first.reload.status, "precondition"
+
+ second = GoalPledge.create!(goal: first.goal, account: crypto, amount: 200, currency: "USD", kind: "transfer",
+ status: "open", expires_at: 7.days.from_now)
+ GoalPledge::Reconciler.new(entry).run
+
+ assert_equal "open", second.reload.status
+ assert_equal first.id, entry.trade.reload.extra.dig("goal", "pledge_id")
+ end
+
+ test "coins transferred out of a crypto account leave its transfer pledge open" do
+ crypto = accounts(:crypto)
+ pledge = open_transfer_pledge(crypto, amount: 200)
+ entry = create_coin_transfer(crypto, qty: BigDecimal("-0.004"), price: 50_000)
+
+ GoalPledge::Reconciler.new(entry).run
+
+ assert_equal "open", pledge.reload.status
+ end
+
+ # An exchange buy swaps cash already in the account for coins: no money
+ # arrives, whatever the trade is worth.
+ test "a buy on a crypto account leaves its transfer pledge open" do
+ crypto = accounts(:crypto)
+ pledge = open_transfer_pledge(crypto, amount: 200)
+ entry = create_coin_transfer(crypto, qty: BigDecimal("0.004"), price: 50_000, label: "Buy", amount: 200)
+
+ GoalPledge::Reconciler.new(entry).run
+
+ assert_equal "open", pledge.reload.status
+ end
+
+ # Deposits into an investment account arrive as cash transactions, which
+ # already resolve pledges; a transfer-in trade there moves securities.
+ test "a transfer-in trade on an investment account leaves its transfer pledge open" do
+ investment = accounts(:investment)
+ pledge = open_transfer_pledge(investment, amount: 200)
+ entry = create_coin_transfer(investment, qty: 1, price: 200, security: securities(:aapl))
+
+ GoalPledge::Reconciler.new(entry).run
+
+ assert_equal "open", pledge.reload.status
+ end
+
private
+ def create_coin_transfer(account, qty:, price:, label: Trade::TRANSFER_LABEL, amount: 0, security: nil)
+ security ||= Security.find_or_create_by!(ticker: "CRYPTO:BTC") { |s| s.name = "Bitcoin" }
+ account.entries.create!(
+ name: "Transfer", date: Date.current, amount: amount, currency: "USD",
+ entryable: Trade.new(qty: qty, price: price, security: security, currency: "USD", investment_activity_label: label)
+ )
+ end
+
def create_transaction_entry(amount:, date:, account: @account, excluded: false)
Entry.create!(
account: account,
diff --git a/test/models/rule/action_test.rb b/test/models/rule/action_test.rb
index 5db15929bb..0fc07aa017 100644
--- a/test/models/rule/action_test.rb
+++ b/test/models/rule/action_test.rb
@@ -2,6 +2,7 @@ require "test_helper"
class Rule::ActionTest < ActiveSupport::TestCase
include EntriesTestHelper
+ include GoalPledgeTestHelper
setup do
@family = families(:dylan_family)
@@ -419,6 +420,28 @@ class Rule::ActionTest < ActiveSupport::TestCase
assert_nil @txn1.reload.investment_activity_label
end
+ test "set as transfer into a pledged account resolves the pledge" do
+ investment = accounts(:investment)
+ pledge = open_transfer_pledge(investment, amount: 100)
+
+ Rule::Action.new(rule: @transaction_rule, action_type: "set_as_transfer_or_payment", value: investment.id)
+ .apply(Transaction.where(id: @txn1.id))
+
+ transfer = Transfer.find_by!(outflow_transaction_id: @txn1.id)
+ assert_equal transfer.inflow_transaction.id, pledge.reload.matched_transaction_id
+ end
+
+ # The goal check is made once per run, not once per transaction.
+ test "set as transfer into an account with no goal reads no pledges" do
+ target = @family.accounts.create!(name: "No goal", balance: 0, currency: "USD", accountable: Depository.new)
+
+ assert_queries_match(/FROM "goal_pledges"/, count: 0) do
+ Rule::Action.new(rule: @transaction_rule, action_type: "set_as_transfer_or_payment", value: target.id)
+ .apply(Transaction.where(id: [ @txn1.id, @txn3.id ]))
+ end
+ assert_equal 2, Transfer.where(outflow_transaction_id: [ @txn1.id, @txn3.id ]).count
+ end
+
# The executor's key is derived from its class name, so a rename would leave
# the constant pointing at an action type nothing executes.
test "the email action type is the email executor's key" do
diff --git a/test/models/trade/create_form_test.rb b/test/models/trade/create_form_test.rb
new file mode 100644
index 0000000000..f8f097a739
--- /dev/null
+++ b/test/models/trade/create_form_test.rb
@@ -0,0 +1,23 @@
+require "test_helper"
+
+class Trade::CreateFormTest < ActiveSupport::TestCase
+ include GoalPledgeTestHelper
+
+ setup do
+ @account = accounts(:investment)
+ end
+
+ # The API runs the form inside its own transaction, so a pledge must wait
+ # for that to commit rather than resolve inside it.
+ test "an unlinked deposit resolves its pledge only once the caller's transaction commits" do
+ pledge = open_transfer_pledge(@account, amount: 250)
+
+ ApplicationRecord.transaction do
+ Trade::CreateForm.new(account: @account, type: "deposit", date: Date.current, amount: 250, currency: "USD").create
+
+ assert_equal "open", pledge.reload.status
+ end
+
+ assert_equal "matched", pledge.reload.status
+ end
+end
diff --git a/test/models/transfer/creator_test.rb b/test/models/transfer/creator_test.rb
index 493d95b043..06ebcff391 100644
--- a/test/models/transfer/creator_test.rb
+++ b/test/models/transfer/creator_test.rb
@@ -2,6 +2,7 @@ require "test_helper"
class Transfer::CreatorTest < ActiveSupport::TestCase
include ActiveJob::TestHelper
+ include GoalPledgeTestHelper
setup do
@family = families(:dylan_family)
@@ -372,4 +373,96 @@ class Transfer::CreatorTest < ActiveSupport::TestCase
assert_equal [ tag.id ], transfer.outflow_transaction.tag_ids
assert_equal [ tag.id ], transfer.inflow_transaction.tag_ids
end
+
+ # we-promise/sure#4226: a transfer pledge resolved only from provider
+ # imports, so a deposit booked in the app never matched it.
+ test "a transfer into an account with an open transfer pledge resolves it" do
+ pledge = goal_pledges(:open_transfer)
+ source = @family.accounts.create!(name: "Savings source", balance: 1000, currency: "USD", accountable: Depository.new)
+
+ transfer = Transfer::Creator.new(
+ family: @family, source_account_id: source.id, destination_account_id: pledge.account_id,
+ date: Date.current, amount: 200
+ ).create
+
+ pledge.reload
+ assert_equal "matched", pledge.status
+ assert_equal transfer.inflow_transaction.id, pledge.matched_transaction_id
+ assert_equal pledge.id, transfer.inflow_transaction.reload.extra.dig("goal", "pledge_id")
+ end
+
+ test "a transfer into a goal-linked investment account resolves its pledge" do
+ pledge = open_transfer_pledge(@destination_account, amount: 150)
+
+ transfer = Transfer::Creator.new(
+ family: @family, source_account_id: @source_account.id, destination_account_id: @destination_account.id,
+ date: Date.current, amount: 150
+ ).create
+
+ assert_equal transfer.inflow_transaction.id, pledge.reload.matched_transaction_id
+ end
+
+ test "a transfer out of the pledged account does not resolve it" do
+ pledge = goal_pledges(:open_transfer)
+
+ transfer = Transfer::Creator.new(
+ family: @family, source_account_id: pledge.account_id, destination_account_id: @destination_account.id,
+ date: Date.current, amount: 200
+ ).create
+
+ assert_equal "open", pledge.reload.status
+ assert_nil transfer.outflow_transaction.reload.extra.dig("goal", "pledge_id")
+ end
+
+ # The API wraps trade creation, and so this, in its own transaction. The
+ # pledge must wait for that to commit: resolving it inside would let a
+ # rescued database error in the reconciler abort the caller's transaction.
+ test "pledge reconciliation waits for the caller's transaction to commit" do
+ pledge = goal_pledges(:open_transfer)
+ source = @family.accounts.create!(name: "Savings source", balance: 1000, currency: "USD", accountable: Depository.new)
+
+ ApplicationRecord.transaction do
+ Transfer::Creator.new(
+ family: @family, source_account_id: source.id, destination_account_id: pledge.account_id,
+ date: Date.current, amount: 200
+ ).create
+
+ assert_equal "open", pledge.reload.status
+ end
+
+ assert_equal "matched", pledge.reload.status
+ end
+
+ test "a rolled-back caller transaction leaves the pledge open" do
+ pledge = goal_pledges(:open_transfer)
+ source = @family.accounts.create!(name: "Savings source", balance: 1000, currency: "USD", accountable: Depository.new)
+
+ ApplicationRecord.transaction do
+ Transfer::Creator.new(
+ family: @family, source_account_id: source.id, destination_account_id: pledge.account_id,
+ date: Date.current, amount: 200
+ ).create
+ raise ActiveRecord::Rollback
+ end
+
+ assert_equal "open", pledge.reload.status
+ assert_nil pledge.matched_transaction_id
+ end
+
+ test "a reconcile failure does not undo the transfer" do
+ pledge = goal_pledges(:open_transfer)
+ source = @family.accounts.create!(name: "Savings source", balance: 1000, currency: "USD", accountable: Depository.new)
+ GoalPledge.any_instance.stubs(:resolve_with!).raises(StandardError, "boom")
+
+ transfer = nil
+ assert_difference "Transfer.count", 1 do
+ transfer = Transfer::Creator.new(
+ family: @family, source_account_id: source.id, destination_account_id: pledge.account_id,
+ date: Date.current, amount: 200
+ ).create
+ end
+
+ assert transfer.persisted?
+ assert_equal "open", pledge.reload.status
+ end
end
diff --git a/test/support/goal_pledge_test_helper.rb b/test/support/goal_pledge_test_helper.rb
new file mode 100644
index 0000000000..d34e5d3864
--- /dev/null
+++ b/test/support/goal_pledge_test_helper.rb
@@ -0,0 +1,8 @@
+module GoalPledgeTestHelper
+ # An open transfer pledge on an account linked to a goal.
+ def open_transfer_pledge(account, amount:, goal: goals(:vacation_italy))
+ goal.goal_accounts.find_or_create_by!(account: account)
+ GoalPledge.create!(goal: goal, account: account, amount: amount, currency: "USD", kind: "transfer",
+ status: "open", expires_at: 7.days.from_now)
+ end
+end