Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Apply nature, type and price on API transaction and trade updates (#5415)

David Gilaa4b7432f465
diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rb
index 0bb2301082..11c824498c 100644
--- a/app/controllers/api/v1/base_controller.rb
+++ b/app/controllers/api/v1/base_controller.rb
@@ -316,6 +316,15 @@ class Api::V1::BaseController < ApplicationController
nil
end
+ # A finite decimal, or nil for anything else. String#to_d would read "abc"
+ # as 0 and "12abc" as 12. exception: false does not cover a NUL byte.
+ def parse_decimal(raw)
+ value = BigDecimal(raw.to_s.strip, exception: false)
+ value if value&.finite?
+ rescue ArgumentError
+ nil
+ end
+
def parse_date_param(key)
Date.iso8601(params[key].to_s)
rescue ArgumentError
diff --git a/app/controllers/api/v1/splits_controller.rb b/app/controllers/api/v1/splits_controller.rb
index c8a4ec05a0..c27fafc496 100644
--- a/app/controllers/api/v1/splits_controller.rb
+++ b/app/controllers/api/v1/splits_controller.rb
@@ -196,9 +196,14 @@ class Api::V1::SplitsController < Api::V1::BaseController
# Round before the range check: 999999999999999.99995 is under the
# limit as sent and at it once rounded.
- amount = BigDecimal(s[:amount].to_s)
- amount = amount.round(AMOUNT_SCALE) if amount.finite?
- unless amount.finite? && amount.abs < AMOUNT_LIMIT
+ amount = parse_decimal(s[:amount])
+ if amount.nil?
+ render_unprocessable("each split requires a numeric amount")
+ return nil
+ end
+
+ amount = amount.round(AMOUNT_SCALE)
+ unless amount.abs < AMOUNT_LIMIT
render_unprocessable("split amount is out of range")
return nil
end
@@ -214,9 +219,6 @@ class Api::V1::SplitsController < Api::V1::BaseController
**split_references.scope(**references)
}
end
- rescue ArgumentError, TypeError
- render_unprocessable("each split requires a numeric amount")
- nil
end
# Transaction's belongs_to :category and :merchant are unscoped, so a known UUID from another
diff --git a/app/controllers/api/v1/trades_controller.rb b/app/controllers/api/v1/trades_controller.rb
index 77cee2f498..da50404815 100644
--- a/app/controllers/api/v1/trades_controller.rb
+++ b/app/controllers/api/v1/trades_controller.rb
@@ -3,6 +3,8 @@
class Api::V1::TradesController < Api::V1::BaseController
include Pagy::Backend
+ UPDATE_NATURES = %w[inflow outflow].freeze
+
before_action :ensure_read_scope, only: [ :index, :show ]
before_action :ensure_write_scope, only: [ :create, :update, :destroy ]
before_action :set_trade, only: [ :show, :update, :destroy ]
@@ -99,6 +101,7 @@ class Api::V1::TradesController < Api::V1::BaseController
return unless valid_trade_update_semantics?
updatable = build_entry_params_for_update
+ return if performed? # build_entry_params_for_update may have rendered validation errors
# The edit and its follow-up writes commit together, as in
# TransactionsController#update: if one fails, a retry still finds the
@@ -215,22 +218,23 @@ class Api::V1::TradesController < Api::V1::BaseController
}.compact_blank
}.compact
- original_qty = flat[:qty]
- original_price = flat[:price]
- type_or_nature = flat[:type].presence || flat[:nature]
-
- if original_qty.present? || original_price.present?
- qty = original_qty.present? ? original_qty : @trade.qty.abs
- price = original_price.present? ? original_price : @trade.price
- is_sell = type_or_nature.present? ? trade_sell_from_type_or_nature?(type_or_nature) : @trade.qty.negative?
- signed_qty = is_sell ? -qty.to_d.abs : qty.to_d.abs
- entry_params[:entryable_attributes][:qty] = signed_qty
- 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?
- 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
+ type_or_nature = flat[:type].presence || flat[:nature].presence
+ return entry_params unless flat.key?(:qty) || flat.key?(:price) || type_or_nature
+
+ # Any of qty, price, type or nature rewrites the trade as create builds
+ # it, taking what the request leaves out from the stored trade. A qty or
+ # price sent blank is invalid, not left out.
+ qty, price = parse_qty_and_price!(flat.fetch(:qty) { @trade.qty.abs }, flat.fetch(:price) { @trade.price })
+ return if performed?
+
+ is_sell = type_or_nature ? trade_sell_from_type_or_nature?(type_or_nature) : @trade.qty.negative?
+ signed_qty = is_sell ? -qty : qty
+ entry_params[:entryable_attributes].merge!(qty: signed_qty, price: price)
+ entry_params[:amount] = signed_qty * price + @trade.fee
+ ticker = @trade.security&.ticker
+ entry_params[:name] = Trade.build_name(is_sell ? "sell" : "buy", qty, ticker) if ticker.present?
+ 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.label_for_side(sell: is_sell)
entry_params
end
@@ -336,25 +340,18 @@ class Api::V1::TradesController < Api::V1::BaseController
return nil
end
- qty_raw = trade_params[:qty].to_s.strip
- price_raw = trade_params[:price].to_s.strip
- return render_validation_error("Quantity and price are required", [ "qty and price must be present and positive" ]) if qty_raw.blank? || price_raw.blank?
+ qty, price = parse_qty_and_price!(trade_params[:qty], trade_params[:price])
+ return if performed?
- qty = qty_raw.to_d
- price = price_raw.to_d
- if qty <= 0 || price <= 0
- # Non-numeric input (e.g. "abc") becomes 0 with to_d; give a clearer message than "must be present"
- non_numeric = (qty.zero? && qty_raw !~ /\A0(\.0*)?\z/) || (price.zero? && price_raw !~ /\A0(\.0*)?\z/)
- return render_validation_error("Quantity and price must be valid numbers", [ "qty and price must be valid positive numbers" ]) if non_numeric
- return render_validation_error("Quantity and price are required", [ "qty and price must be present and positive" ])
- end
+ fee = parse_fee!(trade_params[:fee])
+ return if performed?
{
account: account,
date: trade_params[:date],
qty: qty,
price: price,
- fee: trade_params[:fee].to_d,
+ fee: fee,
currency: trade_params[:currency].presence || account.currency,
type: trade_params[:type].to_s.downcase,
ticker: ticker_value,
@@ -426,6 +423,12 @@ class Api::V1::TradesController < Api::V1::BaseController
end
def valid_trade_update_semantics?
+ nature = trade_update_params[:nature]
+ if nature.present? && UPDATE_NATURES.exclude?(nature.to_s.downcase)
+ render_validation_error("Invalid nature", [ "nature must be one of: #{UPDATE_NATURES.join(", ")}" ])
+ return false
+ end
+
type = trade_update_params[:type].to_s.downcase
label = trade_update_params[:investment_activity_label]
return true if type.blank?
@@ -490,15 +493,38 @@ class Api::V1::TradesController < Api::V1::BaseController
end
def parse_positive_amount!(raw, context:)
- value_raw = raw.to_s.strip
- return render_validation_error("Amount is required", [ "amount must be present for #{context}" ]) if value_raw.blank?
+ return render_validation_error("Amount is required", [ "amount must be present for #{context}" ]) if raw.to_s.strip.blank?
- value = value_raw.to_d
- non_numeric = value.zero? && value_raw !~ /\A0(\.0*)?\z/
- return render_validation_error("Amount must be a valid number", [ "amount must be a valid positive number" ]) if non_numeric || value <= 0
+ value = parse_decimal(raw)
+ return render_validation_error("Amount must be a valid number", [ "amount must be a valid positive number" ]) if value.nil? || value <= 0
value
- end
+ end
+
+ # Positive quantity and price, or nothing after rendering a 422.
+ def parse_qty_and_price!(qty_raw, price_raw)
+ if qty_raw.to_s.strip.blank? || price_raw.to_s.strip.blank?
+ return render_validation_error("Quantity and price are required", [ "qty and price must be present and positive" ])
+ end
+
+ values = [ qty_raw, price_raw ].map { |raw| parse_decimal(raw) }
+ if values.any?(&:nil?)
+ return render_validation_error("Quantity and price must be valid numbers", [ "qty and price must be valid positive numbers" ])
+ end
+ return render_validation_error("Quantity and price are required", [ "qty and price must be present and positive" ]) unless values.all?(&:positive?)
+
+ values
+ end
+
+ # A non-negative fee, zero when absent, or nothing after rendering a 422.
+ def parse_fee!(raw)
+ return 0 if raw.to_s.strip.blank?
+
+ fee = parse_decimal(raw)
+ return render_validation_error("Fee must be a valid number", [ "fee must be a valid non-negative number" ]) if fee.nil? || fee.negative?
+
+ fee
+ end
def safe_page_param
page = params[:page].to_i
diff --git a/app/controllers/api/v1/transactions_controller.rb b/app/controllers/api/v1/transactions_controller.rb
index fb189aa1e3..73c7e22412 100644
--- a/app/controllers/api/v1/transactions_controller.rb
+++ b/app/controllers/api/v1/transactions_controller.rb
@@ -4,6 +4,9 @@ class Api::V1::TransactionsController < Api::V1::BaseController
include Pagy::Backend
include Api::V1::TransactionLookup
+ NATURES = %w[income expense inflow outflow].freeze
+ INVALID_NATURE_MESSAGE = "nature must be one of: #{NATURES.join(", ")}".freeze
+
# Ensure proper scope authorization for read vs write access
before_action :ensure_read_scope, only: [ :index, :show ]
before_action :ensure_write_scope, only: [ :create, :update, :destroy ]
@@ -100,6 +103,7 @@ class Api::V1::TransactionsController < Api::V1::BaseController
return render_existing_idempotent_entry(existing_entry)
end
+ return render_validation_error(INVALID_NATURE_MESSAGE) if invalid_nature?
return render_validation_error("tag_ids must be an array of tag ids") if malformed_tag_ids?
return render_validation_error("Unknown tag id") if unknown_tag_ids?
return render_validation_error("Unknown category id") if unknown_category_id?
@@ -151,6 +155,12 @@ class Api::V1::TransactionsController < Api::V1::BaseController
return
end
+ return render_validation_error(INVALID_NATURE_MESSAGE) if invalid_nature?
+ # The web UI hides amount and nature on a transfer: one leg alone cannot
+ # change them without breaking Transfer#transfer_has_opposite_amounts.
+ if @entry.transaction.transfer && transfer_amount_changed?
+ return render_validation_error("A transfer's amount and nature cannot be changed through one of its transactions")
+ end
return render_validation_error("tag_ids must be an array of tag ids") if malformed_tag_ids?
return render_validation_error("Unknown tag id") if tags_provided? && unknown_tag_ids?
return render_validation_error("Unknown category id") if unknown_category_id?
@@ -402,9 +412,11 @@ class Api::V1::TransactionsController < Api::V1::BaseController
}.compact_blank
}
- # Only update amount if provided
+ # A nature without an amount applies to the stored amount.
if transaction_params[:amount].present?
entry_params[:amount] = calculate_signed_amount
+ elsif transaction_params[:nature].present?
+ entry_params[:amount] = calculate_signed_amount(@entry.amount)
end
entry_params.compact
@@ -528,11 +540,20 @@ class Api::V1::TransactionsController < Api::V1::BaseController
render :show, status: :ok
end
- def calculate_signed_amount
- amount = transaction_params[:amount].to_f
+ def invalid_nature?
+ nature = transaction_params[:nature]
+ nature.present? && NATURES.exclude?(nature.to_s.downcase)
+ end
+
+ def transfer_amount_changed?
+ amount = entry_params_for_update[:amount]
+ amount.present? && amount.to_d != @entry.amount
+ end
+
+ def calculate_signed_amount(amount = transaction_params[:amount].to_f)
nature = transaction_params[:nature]
- case nature&.downcase
+ case nature.to_s.downcase
when "income", "inflow"
-amount.abs # Income is negative
when "expense", "outflow"
diff --git a/app/models/trade.rb b/app/models/trade.rb
index 5f7b4155f0..e2a61032ef 100644
--- a/app/models/trade.rb
+++ b/app/models/trade.rb
@@ -28,6 +28,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
+ # The labels that only say which side of the trade it is.
+ SIDE_LABELS = Trade::CreateForm::SECURITY_TRADE_LABELS.values_at("buy", "sell").freeze
+
# 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.
@@ -58,6 +61,7 @@ class Trade < ApplicationRecord
validate :exchange_rate_must_be_valid
validate :lot_source_entry_must_be_a_lot_choice, if: -> { lot_source_entry_id_changed? && lot_source_entry_id }
+ before_validation :drop_lot_source_entry, if: -> { lot_source_entry_id && !lot_source_entry_id_changed? && qty && !disposal? }
# Trade types for categorization
def buy?
@@ -68,6 +72,11 @@ class Trade < ApplicationRecord
qty.negative?
end
+ # A sale that can name the lot it sold from.
+ def disposal?
+ sell? && !internal_movement?
+ end
+
# A negative quantity that left for another account you own. It looks exactly
# like a sale — same sign, same shape — and only the label tells them apart.
def internal_movement?
@@ -84,7 +93,7 @@ class Trade < ApplicationRecord
# holds is always among them, so an edit keeps it, and is replayed only
# while it names a lot that is still open; a new choice must be open by then.
def lot_choices
- return Entry.none unless sell? && !internal_movement? && entry&.account&.cost_basis_fifo?
+ return Entry.none unless disposal? && entry&.account&.cost_basis_fifo?
acquisitions = entry.account.entries
.where(entryable_type: "Trade", entryable_id: Trade.where(security_id: security_id).where("qty > 0").select(:id))
@@ -257,6 +266,15 @@ class Trade < ApplicationRecord
true
end
+
+ # The label for this trade once it is on the given side: Buy and Sell
+ # follow the side, any other activity (Sweep In, Reinvestment...) is kept.
+ def label_for_side(sell:)
+ return investment_activity_label if investment_activity_label.present? && SIDE_LABELS.exclude?(investment_activity_label)
+
+ Trade::CreateForm::SECURITY_TRADE_LABELS[sell ? "sell" : "buy"]
+ end
+
private
# Acquisitions whose lot is now empty and was emptied before this sale:
@@ -306,6 +324,13 @@ class Trade < ApplicationRecord
end
end
+ # Only a disposal names a lot: an edit that turns it into a buy or an
+ # internal movement lets the stored lot go. A lot named in the same edit
+ # is left for lot_source_entry_must_be_a_lot_choice to refuse.
+ def drop_lot_source_entry
+ self.lot_source_entry_id = nil
+ end
+
def lot_source_entry_must_be_a_lot_choice
errors.add(:lot_source_entry, :invalid) unless lot_choices.exists?(id: lot_source_entry_id)
end
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 3008ed19c1..dc577a5234 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -10460,6 +10460,7 @@ paths:
interest, fee)
fee:
type: number
+ minimum: 0
description: Optional fee (buy/sell/sweep_in/sweep_out/reinvestment)
type:
type: string
@@ -10571,6 +10572,13 @@ paths:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
+ '422':
+ description: qty or price is not a positive number, or nature is not inflow
+ or outflow
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
requestBody:
content:
application/json:
@@ -10585,8 +10593,13 @@ paths:
format: date
qty:
type: number
+ description: Positive quantity. Sending qty, price, type or
+ nature recomputes the entry amount as signed qty * price +
+ fee, where qty is negative on a sell; what the request leaves
+ out is taken from the trade.
price:
type: number
+ description: Positive price per unit
type:
type: string
enum:
@@ -10595,11 +10608,13 @@ paths:
- sweep_in
- sweep_out
- reinvestment
+ description: Side of the trade; takes precedence over nature
nature:
type: string
enum:
- inflow
- outflow
+ description: inflow is a sell, outflow a buy
name:
type: string
notes:
@@ -10918,8 +10933,9 @@ paths:
schema:
"$ref": "#/components/schemas/ErrorResponse"
'422':
- description: validation error - malformed tag_ids, or a tag, category or
- merchant id the family cannot use
+ description: validation error - unknown nature, an amount or nature change
+ on a transfer, malformed tag_ids, or a tag, category or merchant id the
+ family cannot use
content:
application/json:
schema:
@@ -10961,6 +10977,8 @@ paths:
- expense
- inflow
- outflow
+ description: Sign of the amount. Without amount, applies to
+ the stored amount.
tag_ids:
type: array
items:
diff --git a/spec/requests/api/v1/trades_spec.rb b/spec/requests/api/v1/trades_spec.rb
index 7074702680..1ec10b9f85 100644
--- a/spec/requests/api/v1/trades_spec.rb
+++ b/spec/requests/api/v1/trades_spec.rb
@@ -203,6 +203,7 @@ RSpec.describe 'API V1 Trades', type: :request do
},
fee: {
type: :number,
+ minimum: 0,
description: 'Optional fee (buy/sell/sweep_in/sweep_out/reinvestment)'
},
type: {
@@ -599,10 +600,10 @@ RSpec.describe 'API V1 Trades', type: :request do
type: :object,
properties: {
date: { type: :string, format: :date },
- qty: { type: :number },
- price: { type: :number },
- type: { type: :string, enum: %w[buy sell sweep_in sweep_out reinvestment] },
- nature: { type: :string, enum: %w[inflow outflow] },
+ qty: { type: :number, description: 'Positive quantity. Sending qty, price, type or nature recomputes the entry amount as signed qty * price + fee, where qty is negative on a sell; what the request leaves out is taken from the trade.' },
+ price: { type: :number, description: 'Positive price per unit' },
+ type: { type: :string, enum: %w[buy sell sweep_in sweep_out reinvestment], description: 'Side of the trade; takes precedence over nature' },
+ nature: { type: :string, enum: %w[inflow outflow], description: 'inflow is a sell, outflow a buy' },
name: { type: :string },
notes: { type: :string },
currency: { type: :string },
@@ -673,6 +674,15 @@ RSpec.describe 'API V1 Trades', type: :request do
run_test!
end
+
+ response '422', 'qty or price is not a positive number, or nature is not inflow or outflow' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ let(:id) { trade.id }
+ let(:body) { { trade: { price: 'abc' } } }
+
+ run_test!
+ end
end
delete 'Delete trade' do
diff --git a/spec/requests/api/v1/transactions_spec.rb b/spec/requests/api/v1/transactions_spec.rb
index 89aa310de1..0c9f88a94f 100644
--- a/spec/requests/api/v1/transactions_spec.rb
+++ b/spec/requests/api/v1/transactions_spec.rb
@@ -337,7 +337,7 @@ RSpec.describe 'API V1 Transactions', type: :request do
currency: { type: :string, description: 'Currency code' },
category_id: { type: :string, format: :uuid },
merchant_id: { type: :string, format: :uuid },
- nature: { type: :string, enum: %w[income expense inflow outflow] },
+ nature: { type: :string, enum: %w[income expense inflow outflow], description: 'Sign of the amount. Without amount, applies to the stored amount.' },
tag_ids: {
type: :array,
items: { type: :string, format: :uuid },
@@ -380,7 +380,7 @@ RSpec.describe 'API V1 Transactions', type: :request do
run_test!
end
- response '422', 'validation error - malformed tag_ids, or a tag, category or merchant id the family cannot use' do
+ response '422', 'validation error - unknown nature, an amount or nature change on a transfer, malformed tag_ids, or a tag, category or merchant id the family cannot use' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:body) { { transaction: { tag_ids: [ SecureRandom.uuid ] } } }
diff --git a/test/controllers/api/v1/splits_controller_test.rb b/test/controllers/api/v1/splits_controller_test.rb
index 6658886f21..19eb6607a1 100644
--- a/test/controllers/api/v1/splits_controller_test.rb
+++ b/test/controllers/api/v1/splits_controller_test.rb
@@ -86,11 +86,15 @@ class Api::V1::SplitsControllerTest < ActionDispatch::IntegrationTest
assert_response :unprocessable_entity
end
- test "returns 422 when an amount is not numeric" do
- params = { split: { splits: [ { name: "Bad", amount: "not-a-number" } ] } }
+ test "returns 422 when an amount is not a finite number" do
+ [ "not-a-number", "abc", "12abc", "12\u0000abc", "Infinity", "-Infinity", "NaN", "", nil ].each do |amount|
+ params = { split: { splits: [ { name: "Bad", amount: amount }, { name: "Rest", amount: @entry.amount.to_s } ] } }
- post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
- assert_response :unprocessable_entity
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity, amount.inspect
+ assert_equal "each split requires a numeric amount", JSON.parse(response.body)["message"], amount.inspect
+ assert_not @entry.reload.split_parent?
+ end
end
test "returns 422 when the transaction is already split" do
@@ -279,6 +283,7 @@ class Api::V1::SplitsControllerTest < ActionDispatch::IntegrationTest
post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
assert_response :unprocessable_entity, "amount: #{huge}"
+ assert_equal "split amount is out of range", JSON.parse(response.body)["message"], "amount: #{huge}"
assert_not @entry.reload.split_parent?
end
end
diff --git a/test/controllers/api/v1/trades_controller_test.rb b/test/controllers/api/v1/trades_controller_test.rb
index fd38d8438a..e3c12e9b03 100644
--- a/test/controllers/api/v1/trades_controller_test.rb
+++ b/test/controllers/api/v1/trades_controller_test.rb
@@ -772,6 +772,127 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
assert_equal "Sweep Out", body["investment_activity_label"]
end
+ test "an update with only a type turns a buy into a sell, fee included" do
+ trade = Trade.find(create_buy_trade("UPDTYPE", fee: 2))
+
+ patch api_v1_trade_url(trade.id), params: { trade: { type: "sell" } }, headers: api_headers(read_write_api_key)
+
+ assert_response :ok
+ trade.reload
+ assert_equal(-5, trade.qty)
+ assert_equal 100, trade.price
+ assert_equal(-498, trade.entry.amount)
+ assert_equal "Sell", trade.investment_activity_label
+ assert_equal Trade.build_name("sell", 5, "UPDTYPE"), trade.entry.name
+ end
+
+ test "an update with only a nature sets the side of the trade" do
+ trade = Trade.find(create_buy_trade("UPDNAT"))
+
+ patch api_v1_trade_url(trade.id), params: { trade: { nature: "inflow" } }, headers: api_headers(read_write_api_key)
+
+ assert_response :ok
+ trade.reload
+ assert_equal(-5, trade.qty)
+ assert_equal(-500, trade.entry.amount)
+ assert_equal "Sell", trade.investment_activity_label
+
+ patch api_v1_trade_url(trade.id), params: { trade: { nature: "outflow" } }, headers: api_headers(read_write_api_key)
+
+ assert_response :ok
+ trade.reload
+ assert_equal 5, trade.qty
+ assert_equal 500, trade.entry.amount
+ assert_equal "Buy", trade.investment_activity_label
+ end
+
+ test "an update refuses a nature other than inflow or outflow" do
+ trade = Trade.find(create_buy_trade("UPDBADNAT"))
+
+ [ "inlfow", "income" ].each do |nature|
+ patch api_v1_trade_url(trade.id), params: { trade: { nature: nature } }, headers: api_headers(read_write_api_key)
+
+ assert_response :unprocessable_entity, nature
+ trade.reload
+ assert_equal 5, trade.qty, nature
+ assert_equal "Buy", trade.investment_activity_label, nature
+ end
+ end
+
+ test "an update refuses a qty or price sent blank" do
+ trade = Trade.find(create_buy_trade("UPDBLANK"))
+
+ [ { qty: "", price: "120" }, { qty: "" }, { price: nil } ].each do |change|
+ patch api_v1_trade_url(trade.id), params: { trade: change }, headers: api_headers(read_write_api_key), as: :json
+
+ assert_response :unprocessable_entity, change.inspect
+ trade.reload
+ assert_equal 5, trade.qty, change.inspect
+ assert_equal 100, trade.price, change.inspect
+ end
+ end
+
+ test "an update with only a price stores the price and recomputes the amount" do
+ trade = Trade.find(create_buy_trade("UPDPRICE", fee: 2))
+
+ patch api_v1_trade_url(trade.id), params: { trade: { price: "120.5" } }, headers: api_headers(read_write_api_key)
+
+ assert_response :ok
+ trade.reload
+ assert_equal 5, trade.qty
+ assert_equal BigDecimal("120.5"), trade.price
+ assert_equal BigDecimal("604.5"), trade.entry.amount
+ end
+
+ test "an update with a qty and a price stores both" do
+ trade = Trade.find(create_buy_trade("UPDBOTH"))
+
+ patch api_v1_trade_url(trade.id), params: { trade: { qty: 3, price: 90 } }, headers: api_headers(read_write_api_key)
+
+ assert_response :ok
+ trade.reload
+ assert_equal 3, trade.qty
+ assert_equal 90, trade.price
+ assert_equal 270, trade.entry.amount
+ end
+
+ test "an update with a qty or price that is not a positive number is refused and changes nothing" do
+ trade = Trade.find(create_buy_trade("UPDBAD"))
+
+ [
+ [ { qty: "abc" }, "Quantity and price must be valid numbers" ],
+ [ { price: "abc" }, "Quantity and price must be valid numbers" ],
+ [ { qty: "2", price: "1e" }, "Quantity and price must be valid numbers" ],
+ [ { qty: "0" }, "Quantity and price are required" ],
+ [ { price: "-3" }, "Quantity and price are required" ]
+ ].each do |attrs, message|
+ patch api_v1_trade_url(trade.id), params: { trade: attrs }, headers: api_headers(read_write_api_key)
+
+ assert_response :unprocessable_entity, attrs.inspect
+ assert_equal message, JSON.parse(response.body)["message"], attrs.inspect
+ trade.reload
+ assert_equal 5, trade.qty
+ assert_equal 100, trade.price
+ assert_equal 500, trade.entry.amount
+ end
+ end
+
+ test "a dividend cannot become a buy without a qty and a price" do
+ post "/api/v1/trades",
+ params: { trade: { account_id: @investment_account.id, type: "dividend", date: Date.current,
+ amount: 25.50, currency: "USD", ticker: "AAPL|XNAS" } },
+ headers: api_headers(read_write_api_key)
+ assert_response :created
+ trade = Trade.find(JSON.parse(response.body)["id"])
+
+ patch api_v1_trade_url(trade.id), params: { trade: { type: "buy" } }, headers: api_headers(read_write_api_key)
+
+ assert_response :unprocessable_entity
+ trade.reload
+ assert_equal "Dividend", trade.investment_activity_label
+ assert_equal BigDecimal("-25.5"), trade.entry.amount
+ end
+
test "rejects unsupported cash trade types on update" do
trade = @investment_account.trades.first
@@ -968,6 +1089,46 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
assert_equal "Amount must be a valid number", body["message"]
end
+ test "create refuses an amount, qty or price with trailing garbage instead of reading its leading digits" do
+ security = Security.create!(ticker: "GARBAGE", name: "Garbage Security", country_code: "US")
+ [
+ [ { type: "deposit", amount: "12abc" }, "Amount must be a valid number" ],
+ [ { type: "buy", qty: "5abc", price: 100, security_id: security.id }, "Quantity and price must be valid numbers" ],
+ [ { type: "buy", qty: 5, price: "Infinity", security_id: security.id }, "Quantity and price must be valid numbers" ]
+ ].each do |attrs, message|
+ assert_no_difference "Entry.count" do
+ post "/api/v1/trades",
+ params: { trade: { account_id: @investment_account.id, date: Date.current, currency: "USD" }.merge(attrs) },
+ headers: api_headers(read_write_api_key)
+ end
+
+ assert_response :unprocessable_entity, attrs.inspect
+ assert_equal message, JSON.parse(response.body)["message"], attrs.inspect
+ end
+ end
+
+ test "create refuses a fee that is not a non-negative number instead of storing it as zero" do
+ security = Security.create!(ticker: "BADFEE", name: "Bad Fee Security", country_code: "US")
+ [ "abc", "12abc", "Infinity", "-1" ].each do |fee|
+ assert_no_difference "Entry.count" do
+ post "/api/v1/trades",
+ params: { trade: { account_id: @investment_account.id, type: "buy", date: Date.current, currency: "USD",
+ qty: 5, price: 100, fee: fee, security_id: security.id } },
+ headers: api_headers(read_write_api_key)
+ end
+
+ assert_response :unprocessable_entity, fee
+ body = JSON.parse(response.body)
+ assert_equal "Fee must be a valid number", body["message"], fee
+ assert_equal [ "fee must be a valid non-negative number" ], body["errors"], fee
+ end
+ end
+
+ test "create stores a numeric fee and treats a blank one as zero" do
+ assert_equal 2, Trade.find(create_buy_trade("GOODFEE", fee: "2")).fee
+ assert_equal 0, Trade.find(create_buy_trade("BLANKFEE", fee: "")).fee
+ end
+
test "create deposit with zero amount returns 422" do
post "/api/v1/trades",
params: { trade: {
@@ -1161,6 +1322,22 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
end
+ test "a sale that stops being a disposal drops the lot it named" do
+ @investment_account.update!(cost_basis_method: "fifo")
+ security = Security.create!(ticker: "LOTFLIP", name: "LOTFLIP")
+ buy = create_trade(security, account: @investment_account, qty: 40, price: 20, date: 3.days.ago.to_date)
+
+ [ "buy", "sweep_out" ].each do |type|
+ sale = create_trade(security, account: @investment_account, qty: -10, price: 25, date: 1.day.ago.to_date)
+ sale.trade.update!(lot_source_entry: buy)
+
+ patch api_v1_trade_url(sale.entryable_id), params: { trade: { type: type } }, headers: api_headers(read_write_api_key)
+
+ assert_response :ok, type
+ assert_nil sale.trade.reload.lot_source_entry_id, type
+ end
+ end
+
test "a sale that names its lot reports the acquiring trade, in show and index" do
@investment_account.update!(cost_basis_method: "fifo")
security = Security.create!(ticker: "LOTAPI", name: "LOTAPI")
@@ -1190,7 +1367,7 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
}
end
- def create_buy_trade(ticker)
+ def create_buy_trade(ticker, fee: nil)
security = Security.create!(ticker: ticker, name: "#{ticker} Security", country_code: "US")
post "/api/v1/trades",
params: { trade: {
@@ -1199,9 +1376,10 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
date: Date.current,
qty: 5,
price: 100,
+ fee: fee,
currency: "USD",
security_id: security.id
- } },
+ }.compact },
headers: api_headers(read_write_api_key)
assert_response :created
JSON.parse(response.body)["id"]
diff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rb
index 39417d51b1..89a1db71a4 100644
--- a/test/controllers/api/v1/transactions_controller_test.rb
+++ b/test/controllers/api/v1/transactions_controller_test.rb
@@ -9,7 +9,7 @@ class Api::V1::TransactionsControllerTest < ActionDispatch::IntegrationTest
@user = users(:family_admin)
@family = @user.family
@account = @family.accounts.first
- @transaction = @family.transactions.first
+ @transaction = transactions(:one)
# Destroy existing active API keys to avoid validation errors
@user.api_keys.active.destroy_all
@@ -736,6 +736,62 @@ class Api::V1::TransactionsControllerTest < ActionDispatch::IntegrationTest
assert_equal "Updated Transaction Name", response_data["name"]
end
+ test "update with only a nature applies it to the stored amount" do
+ entry = create_transaction(account: @account, amount: 40, name: "Nature only")
+
+ [ [ "income", -40 ], [ "inflow", -40 ], [ "expense", 40 ], [ "outflow", 40 ] ].each do |nature, expected|
+ put api_v1_transaction_url(entry.transaction), params: { transaction: { nature: nature } }, headers: api_headers(@api_key)
+
+ assert_response :success, nature
+ assert_equal expected, entry.reload.amount, nature
+ end
+ end
+
+ test "update with only a nature syncs the account when the sign flips" do
+ entry = create_transaction(account: @account, amount: 40, name: "Nature flip")
+
+ assert_enqueued_with(job: SyncJob) do
+ put api_v1_transaction_url(entry.transaction), params: { transaction: { nature: "income" } }, headers: api_headers(@api_key)
+ end
+ assert_response :success
+ end
+
+ test "update refuses a nature or amount that would break a transfer's legs" do
+ transfer = create_transfer_between_accounts
+ outflow = transfer.outflow_transaction.entry
+ inflow = transfer.inflow_transaction.entry
+
+ [ { nature: "income" }, { amount: 120 }, { amount: 100, nature: "inflow" } ].each do |change|
+ put api_v1_transaction_url(transfer.outflow_transaction), params: { transaction: change }, headers: api_headers(@api_key)
+
+ assert_response :unprocessable_entity, change.inspect
+ assert_equal 100, outflow.reload.amount, change.inspect
+ assert_equal(-100, inflow.reload.amount, change.inspect)
+ end
+
+ put api_v1_transaction_url(transfer.outflow_transaction), params: { transaction: { nature: "outflow", notes: "Rent" } }, headers: api_headers(@api_key)
+ assert_response :success
+ assert_equal "Rent", outflow.reload.notes
+ end
+
+ test "create and update refuse a nature outside the documented values" do
+ entry = create_transaction(account: @account, amount: 40, name: "Bad nature")
+
+ [ "inlfow", 1, true ].each do |nature|
+ put api_v1_transaction_url(entry.transaction), params: { transaction: { nature: nature } }, headers: api_headers(@api_key), as: :json
+
+ assert_response :unprocessable_entity, nature.inspect
+ assert_equal 40, entry.reload.amount, nature.inspect
+
+ assert_no_difference("@account.entries.count", nature.inspect) do
+ post api_v1_transactions_url,
+ params: { transaction: { account_id: @account.id, name: "Bad", amount: 5, date: Date.current, nature: nature } },
+ headers: api_headers(@api_key), as: :json
+ end
+ assert_response :unprocessable_entity, nature.inspect
+ end
+ end
+
test "should not sync the account when only notes change" do
assert_no_enqueued_jobs only: SyncJob do
put api_v1_transaction_url(@transaction),
diff --git a/test/models/trade_test.rb b/test/models/trade_test.rb
index 29963288c5..af9e255612 100644
--- a/test/models/trade_test.rb
+++ b/test/models/trade_test.rb
@@ -427,4 +427,18 @@ class TradeTest < ActiveSupport::TestCase
[ account, security ]
end
+
+ test "label_for_side follows the side for Buy, Sell and a missing label, and keeps any other activity" do
+ trade = Trade.new(investment_activity_label: "Buy")
+ assert_equal "Sell", trade.label_for_side(sell: true)
+
+ trade.investment_activity_label = "Sell"
+ assert_equal "Buy", trade.label_for_side(sell: false)
+
+ trade.investment_activity_label = nil
+ assert_equal "Sell", trade.label_for_side(sell: true)
+
+ trade.investment_activity_label = "Sweep In"
+ assert_equal "Sweep In", trade.label_for_side(sell: true)
+ end
end