Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Support remaining trade activity types in API (#3297)

jaysbeekaybdd1b84b4fd8
diff --git a/app/controllers/api/v1/trades_controller.rb b/app/controllers/api/v1/trades_controller.rb
index fc26fb3e3c..43014cf45e 100644
--- a/app/controllers/api/v1/trades_controller.rb
+++ b/app/controllers/api/v1/trades_controller.rb
@@ -51,7 +51,15 @@ class Api::V1::TradesController < Api::V1::BaseController
create_params = build_create_form_params(account)
return if performed? # build_create_form_params may have rendered validation errors
- model = Trade::CreateForm.new(create_params).create
+ create_options = build_trade_create_options(create_params[:type])
+ return if performed?
+
+ model = ApplicationRecord.transaction do
+ created_model = Trade::CreateForm.new(create_params).create
+ created_trade = trade_from_created_model(created_model)
+ created_trade.update!(create_options) if created_model.persisted? && created_trade && create_options.any?
+ created_model
+ end
unless model.persisted?
errors = model.is_a?(Entry) ? model.errors.full_messages : [ "Trade could not be created" ]
@@ -68,8 +76,6 @@ class Api::V1::TradesController < Api::V1::BaseController
render template: "api/v1/transactions/show", status: :created
else
@trade = model.trade
- apply_trade_create_options!
- return if performed?
@entry = @trade.entry
render :show, status: :created
end
@@ -78,8 +84,6 @@ class Api::V1::TradesController < Api::V1::BaseController
render template: "api/v1/transfers/show", status: :created
else
@trade = model
- apply_trade_create_options!
- return if performed?
@entry = @trade.entry
render :show, status: :created
end
@@ -91,6 +95,8 @@ class Api::V1::TradesController < Api::V1::BaseController
end
def update
+ return unless valid_trade_update_semantics?
+
updatable = build_entry_params_for_update
if @entry.update(updatable.except(:nature))
@@ -198,24 +204,29 @@ class Api::V1::TradesController < Api::V1::BaseController
entry_params[:amount] = signed_qty * price.to_d
ticker = @trade.security&.ticker
entry_params[:name] = Trade.build_name(is_sell ? "sell" : "buy", signed_qty.abs, ticker) if ticker.present?
- entry_params[:entryable_attributes][:investment_activity_label] = flat[:investment_activity_label].presence || @trade.investment_activity_label.presence || (is_sell ? "Sell" : "Buy")
+ type_label = Trade::CreateForm::SECURITY_TRADE_LABELS[flat[:type].to_s.downcase]
+ entry_params[:entryable_attributes][:investment_activity_label] = flat[:investment_activity_label].presence || type_label || @trade.investment_activity_label.presence || (is_sell ? "Sell" : "Buy")
end
entry_params
end
- # True for sell: "sell" or "inflow". False for buy: "buy", "outflow", or blank. Keeps create (buy/sell) and update (type or nature) consistent.
+ # True for sell: "sell", "sweep_out", or "inflow". False for buy: "buy", "outflow", or blank. Keeps create (buy/sell) and update (type or nature) consistent.
def trade_sell_from_type_or_nature?(value)
return false if value.blank?
normalized = value.to_s.downcase.strip
- %w[sell inflow].include?(normalized)
+ %w[sell sweep_out inflow].include?(normalized)
end
def build_create_form_params(account)
type = params.dig(:trade, :type).to_s.downcase
- unless %w[buy sell dividend deposit withdrawal interest].include?(type)
- render_validation_error("Invalid type", [ "type must be 'buy', 'sell', 'dividend', 'deposit', 'withdrawal', or 'interest'" ])
+ unless Trade::CreateForm::SUPPORTED_TYPES.include?(type)
+ supported_types = Trade::CreateForm::SUPPORTED_TYPES.join(", ")
+ render_validation_error(
+ I18n.t("trades.api_errors.invalid_type"),
+ [ I18n.t("trades.api_errors.supported_types", types: supported_types) ]
+ )
return nil
end
@@ -240,7 +251,7 @@ class Api::V1::TradesController < Api::V1::BaseController
transfer_account_id: trade_params[:transfer_account_id]
}.compact
- when "interest"
+ when "interest", "fee"
unless trade_params[:date].present?
render_validation_error("Date is required", [ "date must be present" ])
return nil
@@ -253,7 +264,10 @@ class Api::V1::TradesController < Api::V1::BaseController
ticker_value = nil
manual_ticker_value = nil
- if trade_params[:ticker].present?
+ if trade_params[:security_id].present?
+ security = Security.find(trade_params[:security_id])
+ ticker_value = ticker_from_security(security)
+ elsif trade_params[:ticker].present?
ticker_value = trade_params[:ticker]
elsif trade_params[:manual_ticker].present?
manual_ticker_value = trade_params[:manual_ticker]
@@ -262,7 +276,7 @@ class Api::V1::TradesController < Api::V1::BaseController
{
account: account,
date: trade_params[:date],
- amount: parse_positive_amount!(trade_params[:amount], context: "interest"),
+ amount: parse_positive_amount!(trade_params[:amount], context: type),
currency: trade_params[:currency].presence || account.currency,
type: type,
ticker: ticker_value,
@@ -288,7 +302,7 @@ class Api::V1::TradesController < Api::V1::BaseController
if trade_params[:security_id].present?
security = Security.find(trade_params[:security_id])
- ticker_value = security.exchange_operating_mic.present? ? "#{security.ticker}|#{security.exchange_operating_mic}" : security.ticker
+ ticker_value = ticker_from_security(security)
elsif trade_params[:ticker].present?
ticker_value = trade_params[:ticker]
elsif trade_params[:manual_ticker].present?
@@ -335,7 +349,7 @@ class Api::V1::TradesController < Api::V1::BaseController
if trade_params[:security_id].present?
security = Security.find(trade_params[:security_id])
- ticker_value = security.exchange_operating_mic.present? ? "#{security.ticker}|#{security.exchange_operating_mic}" : security.ticker
+ ticker_value = ticker_from_security(security)
elsif trade_params[:ticker].present?
ticker_value = trade_params[:ticker]
elsif trade_params[:manual_ticker].present?
@@ -361,13 +375,19 @@ class Api::V1::TradesController < Api::V1::BaseController
}.compact
end
- def apply_trade_create_options!
+ def build_trade_create_options(type)
+ return {} unless Trade::CreateForm::ACTIVITY_LABELS.key?(type)
+
attrs = {}
if trade_params[:investment_activity_label].present?
label = trade_params[:investment_activity_label]
- unless Trade::ACTIVITY_LABELS.include?(label)
- render_validation_error("Invalid investment_activity_label", [ "investment_activity_label must be one of: #{Trade::ACTIVITY_LABELS.join(', ')}" ])
- return
+ expected_label = Trade::CreateForm::ACTIVITY_LABELS.fetch(type)
+ unless label == expected_label
+ render_validation_error(
+ I18n.t("trades.api_errors.invalid_activity_label"),
+ [ I18n.t("trades.api_errors.activity_label_must_match_type", label: expected_label, type: type) ]
+ )
+ return {}
end
attrs[:investment_activity_label] = label
end
@@ -375,11 +395,49 @@ class Api::V1::TradesController < Api::V1::BaseController
category = current_resource_owner.family.categories.find_by(id: trade_params[:category_id])
unless category
render_validation_error("Category not found or does not belong to your family", [ "category_id is invalid" ])
- return
+ return {}
end
attrs[:category_id] = category.id
end
- @trade.update!(attrs) if attrs.any?
+ attrs
+ end
+
+ def trade_from_created_model(model)
+ return model.trade if model.is_a?(Entry) && model.entryable_type == "Trade"
+ return model if model.is_a?(Trade)
+
+ nil
+ end
+
+ def valid_trade_update_semantics?
+ type = trade_update_params[:type].to_s.downcase
+ label = trade_update_params[:investment_activity_label]
+ return true if type.blank?
+
+ expected_label = Trade::CreateForm::SECURITY_TRADE_LABELS[type]
+ unless expected_label
+ render_validation_error(
+ I18n.t("trades.api_errors.invalid_type"),
+ [ I18n.t("trades.api_errors.supported_types", types: Trade::CreateForm::SECURITY_TRADE_LABELS.keys.join(", ")) ]
+ )
+ return false
+ end
+
+ if label.present? && label != expected_label
+ render_validation_error(
+ I18n.t("trades.api_errors.invalid_activity_label"),
+ [ I18n.t("trades.api_errors.activity_label_must_match_type", label: expected_label, type: type) ]
+ )
+ return false
+ end
+
+ true
+ end
+
+ def ticker_from_security(security)
+ return security.ticker if security.exchange_operating_mic.blank?
+
+ "#{security.ticker}|#{security.exchange_operating_mic}"
end
def render_validation_error(message, errors)
diff --git a/app/models/holding.rb b/app/models/holding.rb
index 57b5debb54..2f0f8a0cf7 100644
--- a/app/models/holding.rb
+++ b/app/models/holding.rb
@@ -290,21 +290,22 @@ class Holding < ApplicationRecord
.where(security_id: security.id)
.where("trades.qty > 0 AND entries.date <= ?", date)
- # A transfer is not a purchase: coins moved in from elsewhere were
+ # An internal movement is not a purchase: securities moved in from elsewhere were
# acquired at a price nothing here knows, so treating the day they
# arrived as their cost states a number that looks authoritative and is
# wrong — a coin bought at 30k and moved in at 60k would report no gain.
#
- # One transfer makes the whole position unknown, rather than just its own
+ # One internal movement makes the whole position unknown, rather than just its own
# row. Averaging the purchases alone and applying that to every unit is
# the same fabrication in a quieter form: buy one at 30k, receive one, and
# the position would report 30k a unit for two units it did not cost that.
- return nil if trades.where(investment_activity_label: Trade::TRANSFER_LABEL).exists?
+ return nil if trades.where(investment_activity_label: Trade::INTERNAL_MOVEMENT_LABELS).exists?
# IS DISTINCT FROM, because `!=` is NULL for an unlabelled row and would
# drop the ordinary purchases that carry no label at all.
trades = trades.where(
- "trades.investment_activity_label IS DISTINCT FROM ?", Trade::TRANSFER_LABEL
+ "trades.investment_activity_label NOT IN (?) OR trades.investment_activity_label IS NULL",
+ Trade::INTERNAL_MOVEMENT_LABELS
)
total_cost, total_qty = trades.pick(
diff --git a/app/models/holding/forward_calculator.rb b/app/models/holding/forward_calculator.rb
index fdc8e05f7a..87b368db61 100644
--- a/app/models/holding/forward_calculator.rb
+++ b/app/models/holding/forward_calculator.rb
@@ -91,9 +91,9 @@ class Holding::ForwardCalculator
security_id = trade.security_id
- # A transfer is not a purchase: it contributes no cost and it makes the
- # whole position unknowable, not just its own units.
- if trade.investment_activity_label == Trade::TRANSFER_LABEL
+ # An internal movement is not a purchase: it contributes no cost and it
+ # makes the whole position unknowable, not just its own units.
+ if trade.internal_movement?
@transferred_security_ids << security_id
next
end
diff --git a/app/models/holding/reverse_calculator.rb b/app/models/holding/reverse_calculator.rb
index 9b0bd76d0b..9289d6d27f 100644
--- a/app/models/holding/reverse_calculator.rb
+++ b/app/models/holding/reverse_calculator.rb
@@ -94,7 +94,7 @@ class Holding::ReverseCalculator
security_id = trade.security_id
- if trade.investment_activity_label == Trade::TRANSFER_LABEL
+ if trade.internal_movement?
@first_transfer_dates[security_id] ||= trade_entry.date
next
end
diff --git a/app/models/trade.rb b/app/models/trade.rb
index 8a1f06a5ad..0cce260cb1 100644
--- a/app/models/trade.rb
+++ b/app/models/trade.rb
@@ -25,15 +25,9 @@ class Trade < ApplicationRecord
# excluded, and an ambiguous one is left where the user can see it.
INTERNAL_MOVEMENT_LABELS = %w[Transfer Sweep\ In Sweep\ Out].freeze
- # Moving an asset between places you own is not an acquisition, so it must not
- # set a cost basis. Named here because Holding reads it.
- #
- # A single label rather than INTERNAL_MOVEMENT_LABELS above, though both rest
- # on ownership being preserved: this one is the label the onchain processor
- # writes, and the only one seen setting a basis it should not. Widening the
- # basis guard to the sweep labels would change which holdings lose their
- # basis, and nothing has shown a sweep landing on a security — so it stays
- # narrow until something does.
+ # Kept as the provider-facing label for direct wallet transfers. Cost-basis
+ # calculations use INTERNAL_MOVEMENT_LABELS so API-created sweeps follow the
+ # same ownership-preserving rule.
TRANSFER_LABEL = "Transfer".freeze
validates :qty, presence: true
diff --git a/app/models/trade/create_form.rb b/app/models/trade/create_form.rb
index ce4a984db4..64bc06192c 100644
--- a/app/models/trade/create_form.rb
+++ b/app/models/trade/create_form.rb
@@ -1,6 +1,24 @@
class Trade::CreateForm
include ActiveModel::Model
+ SECURITY_TRADE_LABELS = {
+ "buy" => "Buy",
+ "sell" => "Sell",
+ "sweep_in" => "Sweep In",
+ "sweep_out" => "Sweep Out",
+ "reinvestment" => "Reinvestment"
+ }.freeze
+
+ CASH_TRADE_LABELS = {
+ "dividend" => "Dividend",
+ "interest" => "Interest",
+ "fee" => "Fee"
+ }.freeze
+
+ ACTIVITY_LABELS = SECURITY_TRADE_LABELS.merge(CASH_TRADE_LABELS).freeze
+ TRANSFER_TYPES = %w[deposit withdrawal].freeze
+ SUPPORTED_TYPES = (ACTIVITY_LABELS.keys + TRANSFER_TYPES).freeze
+
attr_accessor :account, :date, :amount, :currency, :qty,
:price, :fee, :ticker, :manual_ticker, :type, :transfer_account_id
@@ -8,12 +26,14 @@ class Trade::CreateForm
# Returns the model, regardless of success or failure
def create
case type
- when "buy", "sell"
+ when *SECURITY_TRADE_LABELS.keys
create_trade
when "dividend"
create_dividend_income
when "interest"
create_interest_income
+ when "fee"
+ create_fee
when "deposit", "withdrawal"
create_transfer
end
@@ -45,11 +65,12 @@ class Trade::CreateForm
return entry
end
- signed_qty = type == "sell" ? -qty.to_d : qty.to_d
+ signed_qty = sell_side_trade? ? -qty.to_d.abs : qty.to_d.abs
signed_amount = signed_qty * price.to_d + fee.to_d
+ label = SECURITY_TRADE_LABELS.fetch(type)
trade_entry = account.entries.new(
- name: Trade.build_name(type, qty, sec.ticker),
+ name: trade_name(label, signed_qty.abs, sec.ticker),
date: date,
amount: signed_amount,
currency: currency,
@@ -59,7 +80,7 @@ class Trade::CreateForm
fee: fee.to_d,
currency: currency,
security: sec,
- investment_activity_label: type.capitalize # "buy" → "Buy", "sell" → "Sell"
+ investment_activity_label: label
)
)
@@ -81,7 +102,8 @@ class Trade::CreateForm
begin
sec = security
- create_income_trade(sec: sec, label: "Dividend", name: "Dividend: #{sec.ticker}")
+ label = CASH_TRADE_LABELS.fetch("dividend")
+ create_income_trade(sec: sec, label: label, name: "#{label}: #{sec.ticker}")
rescue => e
Rails.logger.warn("Dividend security resolution failed: #{e.class} - #{e.message}")
entry = account.entries.build(entryable: Trade.new)
@@ -93,16 +115,24 @@ class Trade::CreateForm
# Interest in an investment account is always a Trade.
# Falls back to a synthetic cash security when none is selected.
def create_interest_income
- sec = ticker_present? ? security : Security.cash_for(account)
- name = sec.cash? ? "Interest" : "Interest: #{sec.ticker}"
- create_income_trade(sec: sec, label: "Interest", name: name)
+ sec = ticker_present? ? security : Security.cash_for(account, currency: currency)
+ label = CASH_TRADE_LABELS.fetch("interest")
+ name = sec.cash? ? label : "#{label}: #{sec.ticker}"
+ create_income_trade(sec: sec, label: label, name: name)
end
- def create_income_trade(sec:, label:, name:)
+ def create_fee
+ sec = ticker_present? ? security : Security.cash_for(account, currency: currency)
+ label = CASH_TRADE_LABELS.fetch("fee")
+ name = sec.cash? ? label : "#{label}: #{sec.ticker}"
+ create_income_trade(sec: sec, label: label, name: name, amount_sign: 1)
+ end
+
+ def create_income_trade(sec:, label:, name:, amount_sign: -1)
entry = account.entries.build(
name: name,
date: date,
- amount: amount.to_d * -1,
+ amount: amount.to_d.abs * amount_sign,
currency: currency,
entryable: Trade.new(
qty: 0,
@@ -122,6 +152,16 @@ class Trade::CreateForm
entry
end
+ def sell_side_trade?
+ %w[sell sweep_out].include?(type)
+ end
+
+ def trade_name(label, quantity, ticker)
+ return Trade.build_name(type, quantity, ticker) if %w[buy sell].include?(type)
+
+ "#{label} #{quantity.to_d} shares of #{ticker}"
+ end
+
def create_transfer
if transfer_account_id.present?
from_account_id = type == "withdrawal" ? account.id : transfer_account_id
diff --git a/config/locales/views/trades/en.yml b/config/locales/views/trades/en.yml
index 5f625740d4..00200ba7e2 100644
--- a/config/locales/views/trades/en.yml
+++ b/config/locales/views/trades/en.yml
@@ -1,6 +1,11 @@
---
en:
trades:
+ api_errors:
+ activity_label_must_match_type: "investment_activity_label must be %{label} when type is %{type}"
+ invalid_activity_label: Invalid investment activity label
+ invalid_type: Invalid type
+ supported_types: "type must be one of: %{types}"
form:
account: Transfer account (optional)
account_prompt: Search account
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 1eb7d95228..e78770eada 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -7294,7 +7294,7 @@ paths:
parameters: []
responses:
'201':
- description: interest created
+ description: trade created
content:
application/json:
schema:
@@ -7312,7 +7312,7 @@ paths:
schema:
"$ref": "#/components/schemas/ErrorResponse"
'422':
- description: deposit without amount returns error
+ description: invalid trade request
content:
application/json:
schema:
@@ -7342,23 +7342,30 @@ paths:
description: Trade date (required)
qty:
type: number
- description: Quantity (required for buy/sell)
+ description: Quantity (required for buy/sell/sweep_in/sweep_out/reinvestment)
price:
type: number
- description: Price (required for buy/sell)
+ description: Price (required for buy/sell/sweep_in/sweep_out/reinvestment)
amount:
type: number
description: Amount (required for dividend, deposit, withdrawal,
- interest)
+ interest, fee)
+ fee:
+ type: number
+ description: Optional fee (buy/sell/sweep_in/sweep_out/reinvestment)
type:
type: string
enum:
- buy
- sell
+ - sweep_in
+ - sweep_out
- dividend
+ - reinvestment
+ - interest
+ - fee
- deposit
- withdrawal
- - interest
description: Trade type (required)
security_id:
type: string
@@ -7478,10 +7485,9 @@ paths:
enum:
- buy
- sell
- - dividend
- - deposit
- - withdrawal
- - interest
+ - sweep_in
+ - sweep_out
+ - reinvestment
nature:
type: string
enum:
diff --git a/spec/requests/api/v1/trades_spec.rb b/spec/requests/api/v1/trades_spec.rb
index 2f58668e86..a1a730e972 100644
--- a/spec/requests/api/v1/trades_spec.rb
+++ b/spec/requests/api/v1/trades_spec.rb
@@ -160,10 +160,21 @@ RSpec.describe 'API V1 Trades', type: :request do
properties: {
account_id: { type: :string, format: :uuid, description: 'Account ID (required)' },
date: { type: :string, format: :date, description: 'Trade date (required)' },
- qty: { type: :number, description: 'Quantity (required for buy/sell)' },
- price: { type: :number, description: 'Price (required for buy/sell)' },
- amount: { type: :number, description: 'Amount (required for dividend, deposit, withdrawal, interest)' },
- type: { type: :string, enum: %w[buy sell dividend deposit withdrawal interest], description: 'Trade type (required)' },
+ qty: { type: :number, description: 'Quantity (required for buy/sell/sweep_in/sweep_out/reinvestment)' },
+ price: { type: :number, description: 'Price (required for buy/sell/sweep_in/sweep_out/reinvestment)' },
+ amount: {
+ type: :number,
+ description: 'Amount (required for dividend, deposit, withdrawal, interest, fee)'
+ },
+ fee: {
+ type: :number,
+ description: 'Optional fee (buy/sell/sweep_in/sweep_out/reinvestment)'
+ },
+ type: {
+ type: :string,
+ enum: %w[buy sell sweep_in sweep_out dividend reinvestment interest fee deposit withdrawal],
+ description: 'Trade type (required)'
+ },
security_id: { type: :string, format: :uuid, description: 'Security ID (one of security_id, ticker, manual_ticker required)' },
ticker: { type: :string, description: 'Ticker symbol' },
manual_ticker: { type: :string, description: 'Manual ticker for offline securities' },
@@ -430,7 +441,7 @@ RSpec.describe 'API V1 Trades', type: :request do
run_test!
end
- response '201', 'interest created' do
+ response '201', 'trade created' do
schema '$ref' => '#/components/schemas/TransactionResponse'
let(:body) do
@@ -448,7 +459,7 @@ RSpec.describe 'API V1 Trades', type: :request do
run_test!
end
- response '422', 'deposit without amount returns error' do
+ response '422', 'invalid trade request' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:body) do
@@ -515,7 +526,7 @@ RSpec.describe 'API V1 Trades', type: :request do
date: { type: :string, format: :date },
qty: { type: :number },
price: { type: :number },
- type: { type: :string, enum: %w[buy sell dividend deposit withdrawal interest] },
+ type: { type: :string, enum: %w[buy sell sweep_in sweep_out reinvestment] },
nature: { type: :string, enum: %w[inflow outflow] },
name: { type: :string },
notes: { type: :string },
diff --git a/test/controllers/api/v1/trades_controller_test.rb b/test/controllers/api/v1/trades_controller_test.rb
index 89a27858f2..60d6c22507 100644
--- a/test/controllers/api/v1/trades_controller_test.rb
+++ b/test/controllers/api/v1/trades_controller_test.rb
@@ -99,6 +99,90 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
assert_equal "Sell", body["investment_activity_label"]
end
+ test "create sweep in trade returns 201" do
+ security = Security.create!(ticker: "SWIN", name: "Sweep In Security", country_code: "US")
+
+ post "/api/v1/trades",
+ params: { trade: {
+ account_id: @investment_account.id,
+ type: "sweep_in",
+ date: Date.current,
+ qty: 10,
+ price: 1.00,
+ currency: "USD",
+ security_id: security.id
+ } },
+ headers: api_headers(read_write_api_key)
+
+ assert_response :created
+ body = JSON.parse(response.body)
+ assert_equal "Sweep In", body["investment_activity_label"]
+ assert_equal 10, body["qty"].to_i
+ end
+
+ test "create sweep out trade returns 201" do
+ security = Security.create!(ticker: "SWOUT", name: "Sweep Out Security", country_code: "US")
+
+ post "/api/v1/trades",
+ params: { trade: {
+ account_id: @investment_account.id,
+ type: "sweep_out",
+ date: Date.current,
+ qty: 10,
+ price: 1.00,
+ currency: "USD",
+ security_id: security.id
+ } },
+ headers: api_headers(read_write_api_key)
+
+ assert_response :created
+ body = JSON.parse(response.body)
+ assert_equal "Sweep Out", body["investment_activity_label"]
+ assert_equal(-10, body["qty"].to_i)
+ end
+
+ test "create reinvestment trade returns 201" do
+ security = Security.create!(ticker: "REINV", name: "Reinvestment Security", country_code: "US")
+
+ post "/api/v1/trades",
+ params: { trade: {
+ account_id: @investment_account.id,
+ type: "reinvestment",
+ date: Date.current,
+ qty: 2,
+ price: 12.34,
+ currency: "USD",
+ security_id: security.id
+ } },
+ headers: api_headers(read_write_api_key)
+
+ assert_response :created
+ body = JSON.parse(response.body)
+ assert_equal "Reinvestment", body["investment_activity_label"]
+ assert_equal 2, body["qty"].to_i
+ end
+
+ test "create fee trade returns 201" do
+ security = Security.create!(ticker: "FEESEC", name: "Fee Security", country_code: "US")
+
+ post "/api/v1/trades",
+ params: { trade: {
+ account_id: @investment_account.id,
+ type: "fee",
+ date: Date.current,
+ amount: 0.68,
+ currency: "USD",
+ security_id: security.id
+ } },
+ headers: api_headers(read_write_api_key)
+
+ assert_response :created
+ body = JSON.parse(response.body)
+ assert_equal "Fee", body["investment_activity_label"]
+ assert_equal 0, body["qty"].to_d
+ assert_in_delta 0.68, Trade.find(body["id"]).entry.amount.to_f, 0.001
+ end
+
test "invalid type returns 422" do
post "/api/v1/trades",
params: { trade: {
@@ -111,6 +195,47 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
assert_response :unprocessable_entity
end
+ test "rejects a type-label mismatch without persisting a trade" do
+ security = Security.create!(ticker: "MISMATCH", name: "Mismatch Security", country_code: "US")
+
+ assert_no_difference [ "Entry.count", "Trade.count" ] do
+ post "/api/v1/trades",
+ params: { trade: {
+ account_id: @investment_account.id,
+ type: "sweep_out",
+ investment_activity_label: "Buy",
+ date: Date.current,
+ qty: 10,
+ price: 1,
+ security_id: security.id
+ } },
+ headers: api_headers(read_write_api_key)
+ end
+
+ assert_response :unprocessable_entity
+ end
+
+ test "rejects an inaccessible category without persisting a trade" do
+ security = Security.create!(ticker: "BADCAT", name: "Bad Category Security", country_code: "US")
+ other_category = families(:empty).categories.create!(name: "Other family category", color: "#123456", lucide_icon: "circle")
+
+ assert_no_difference [ "Entry.count", "Trade.count" ] do
+ post "/api/v1/trades",
+ params: { trade: {
+ account_id: @investment_account.id,
+ type: "buy",
+ date: Date.current,
+ qty: 10,
+ price: 1,
+ security_id: security.id,
+ category_id: other_category.id
+ } },
+ headers: api_headers(read_write_api_key)
+ end
+
+ assert_response :unprocessable_entity
+ end
+
test "create deposit returns 201" do
post "/api/v1/trades",
params: { trade: {
@@ -502,6 +627,40 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
assert_equal "Updated notes", response_data["notes"]
end
+ test "updates a security trade to sweep out with matching sign and label" do
+ security = Security.create!(ticker: "UPDSWEEP", name: "Update Sweep Security", country_code: "US")
+ post "/api/v1/trades",
+ params: { trade: {
+ account_id: @investment_account.id,
+ type: "buy",
+ date: Date.current,
+ qty: 5,
+ price: 100,
+ security_id: security.id
+ } },
+ headers: api_headers(read_write_api_key)
+ trade_id = JSON.parse(response.body).fetch("id")
+
+ patch api_v1_trade_url(trade_id),
+ params: { trade: { type: "sweep_out", qty: 4 } },
+ headers: api_headers(read_write_api_key)
+
+ assert_response :success
+ body = JSON.parse(response.body)
+ assert_equal(-4, body["qty"].to_d)
+ assert_equal "Sweep Out", body["investment_activity_label"]
+ end
+
+ test "rejects unsupported cash trade types on update" do
+ trade = @investment_account.trades.first
+
+ patch api_v1_trade_url(trade.id),
+ params: { trade: { type: "fee", qty: 1 } },
+ headers: api_headers(read_write_api_key)
+
+ assert_response :unprocessable_entity
+ end
+
test "should reject update with read-only API key" do
security = Security.create!(ticker: "UPDRO", name: "Update RO Security", country_code: "US")
post "/api/v1/trades",
diff --git a/test/models/holding/materializer_test.rb b/test/models/holding/materializer_test.rb
index d6c34eb20f..890d0ba562 100644
--- a/test/models/holding/materializer_test.rb
+++ b/test/models/holding/materializer_test.rb
@@ -42,6 +42,19 @@ class Holding::MaterializerTest < ActiveSupport::TestCase
assert_nil latest_holding.avg_cost
end
+ test "a sweep in clears a cost basis this app had worked out" do
+ create_trade(@aapl, account: @account, qty: 1, price: 200, date: Date.current)
+ Holding::Materializer.new(@account, strategy: :forward).materialize_holdings
+ assert_equal 200, latest_holding.cost_basis.to_d
+
+ @account.trades.each { |trade| trade.update!(investment_activity_label: "Sweep In") }
+ Holding::Materializer.new(@account, strategy: :forward).materialize_holdings
+
+ assert_nil latest_holding.cost_basis
+ assert_nil latest_holding.cost_basis_source
+ assert_nil latest_holding.avg_cost
+ end
+
# A row carrying a figure with no `cost_basis_source` was invisible to
# `load_existing_holdings_map`, so the clearing above saw no existing holding
# and left the stale basis standing — the rows least able to justify the
diff --git a/test/models/holding_test.rb b/test/models/holding_test.rb
index 353bf0ffd2..78c9b5037a 100644
--- a/test/models/holding_test.rb
+++ b/test/models/holding_test.rb
@@ -458,12 +458,15 @@ class HoldingTest < ActiveSupport::TestCase
# A coin bought elsewhere at one price and moved in at another was never
# bought here, so counting the day it arrived as its cost reports a gain of
# zero on a position that may have doubled.
- test "a transfer does not set the cost basis" do
+ test "an internal movement does not set the cost basis" do
holding = holdings(:one)
- holding.account.trades.each { |t| t.update!(investment_activity_label: Trade::TRANSFER_LABEL) }
- assert_nil holding.avg_cost,
- "a transferred position has no cost basis this app can know"
+ Trade::INTERNAL_MOVEMENT_LABELS.each do |label|
+ holding.account.trades.each { |trade| trade.update!(investment_activity_label: label) }
+
+ assert_nil holding.avg_cost,
+ "a position moved by #{label} has no cost basis this app can know"
+ end
end
# `!=` is NULL for an unlabelled row, so a naive exclusion drops the ordinary