Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Stop accepting category_id on the trades API (#4734)

jaysbeekay9769257fb1cb
diff --git a/app/controllers/api/v1/trades_controller.rb b/app/controllers/api/v1/trades_controller.rb
index 036c3f57c3..f94c566ca0 100644
--- a/app/controllers/api/v1/trades_controller.rb
+++ b/app/controllers/api/v1/trades_controller.rb
@@ -99,14 +99,25 @@ class Api::V1::TradesController < Api::V1::BaseController
updatable = build_entry_params_for_update
- if @entry.update(updatable.except(:nature))
- @entry.lock_saved_attributes!
- @entry.mark_user_modified!
- @entry.sync_account_later
- @trade = @entry.trade
- render :show
- else
- render_validation_error("Trade could not be updated", @entry.errors.full_messages)
+ # The edit and its follow-up writes commit together, as in
+ # TransactionsController#update: if one fails, a retry still finds the
+ # change to make.
+ Entry.transaction do
+ if @entry.update(updatable.except(:nature))
+ # Read before the follow-up writes below reset saved_changes. A request
+ # that changes nothing must not mark the entry user-modified, which would
+ # stop provider imports from updating it.
+ if @entry.saved_changes.any? || @entry.entryable.saved_changes.any?
+ @entry.lock_saved_attributes!
+ @entry.mark_user_modified!
+ @entry.sync_account_later
+ end
+ @trade = @entry.trade
+ render :show
+ else
+ render_validation_error("Trade could not be updated", @entry.errors.full_messages)
+ raise ActiveRecord::Rollback
+ end
end
rescue => e
log_and_render_error("update", e)
@@ -163,7 +174,7 @@ class Api::V1::TradesController < Api::V1::BaseController
def trade_params
params.require(:trade).permit(
:account_id, :date, :qty, :price, :currency,
- :security_id, :ticker, :manual_ticker, :investment_activity_label, :category_id,
+ :security_id, :ticker, :manual_ticker, :investment_activity_label,
:fee, :type, :amount, :transfer_account_id
)
end
@@ -171,7 +182,7 @@ class Api::V1::TradesController < Api::V1::BaseController
def trade_update_params
params.require(:trade).permit(
:name, :date, :amount, :currency, :notes, :nature, :type,
- :qty, :price, :investment_activity_label, :category_id
+ :qty, :price, :investment_activity_label
)
end
@@ -186,8 +197,7 @@ class Api::V1::TradesController < Api::V1::BaseController
entryable_type: "Trade",
entryable_attributes: {
id: @trade.id,
- investment_activity_label: flat[:investment_activity_label],
- category_id: flat[:category_id]
+ investment_activity_label: flat[:investment_activity_label]
}.compact_blank
}.compact
@@ -391,14 +401,6 @@ class Api::V1::TradesController < Api::V1::BaseController
end
attrs[:investment_activity_label] = label
end
- if trade_params[:category_id].present?
- 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 {}
- end
- attrs[:category_id] = category.id
- end
attrs
end
diff --git a/config/brakeman.ignore b/config/brakeman.ignore
index 579afb3038..d5939e3153 100644
--- a/config/brakeman.ignore
+++ b/config/brakeman.ignore
@@ -72,13 +72,13 @@
{
"warning_type": "Mass Assignment",
"warning_code": 105,
- "fingerprint": "81c63f2c375da309440b9308df3ae9d1fcbada7043a26919898b08f3a38b29f6",
+ "fingerprint": "1cf4587eb3a07c5172e3de254747a1806cb4e454941da6c2fd3ba2f0f64a749f",
"check_name": "PermitAttributes",
"message": "Potentially dangerous key allowed for mass assignment",
"file": "app/controllers/api/v1/trades_controller.rb",
"line": 159,
"link": "https://brakemanscanner.org/docs/warning_types/mass_assignment/",
- "code": "params.require(:trade).permit(:account_id, :date, :qty, :price, :currency, :security_id, :ticker, :manual_ticker, :investment_activity_label, :category_id, :fee, :type, :amount, :transfer_account_id)",
+ "code": "params.require(:trade).permit(:account_id, :date, :qty, :price, :currency, :security_id, :ticker, :manual_ticker, :investment_activity_label, :fee, :type, :amount, :transfer_account_id)",
"render_path": null,
"location": {
"type": "method",
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index fea2c23c3b..f521a60fdb 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -10444,10 +10444,6 @@ paths:
investment_activity_label:
type: string
description: Activity label (e.g. Buy, Sell)
- category_id:
- type: string
- format: uuid
- description: Category ID
transfer_account_id:
type: string
format: uuid
@@ -10563,9 +10559,6 @@ paths:
type: string
investment_activity_label:
type: string
- category_id:
- type: string
- format: uuid
required: true
delete:
summary: Delete trade
diff --git a/spec/requests/api/v1/trades_spec.rb b/spec/requests/api/v1/trades_spec.rb
index b7af019310..f51352dad7 100644
--- a/spec/requests/api/v1/trades_spec.rb
+++ b/spec/requests/api/v1/trades_spec.rb
@@ -51,14 +51,6 @@ RSpec.describe 'API V1 Trades', type: :request do
)
end
- let(:category) do
- family.categories.create!(
- name: 'Investments',
- color: '#2196F3',
- lucide_icon: 'trending-up'
- )
- end
-
let!(:trade) do
trade_record = Trade.new(
security: security,
@@ -180,7 +172,6 @@ RSpec.describe 'API V1 Trades', type: :request do
manual_ticker: { type: :string, description: 'Manual ticker for offline securities' },
currency: { type: :string, description: 'Currency (defaults to account currency)' },
investment_activity_label: { type: :string, description: 'Activity label (e.g. Buy, Sell)' },
- category_id: { type: :string, format: :uuid, description: 'Category ID' },
transfer_account_id: { type: :string, format: :uuid, description: 'Destination/source account ID for linked transfers. Must be an account the user can write to; otherwise the request returns 404.' }
},
required: %w[account_id date type]
@@ -531,8 +522,7 @@ RSpec.describe 'API V1 Trades', type: :request do
name: { type: :string },
notes: { type: :string },
currency: { type: :string },
- investment_activity_label: { type: :string },
- category_id: { type: :string, format: :uuid }
+ investment_activity_label: { type: :string }
}
}
}
diff --git a/test/controllers/api/v1/trades_controller_test.rb b/test/controllers/api/v1/trades_controller_test.rb
index 924fd20119..053aaca926 100644
--- a/test/controllers/api/v1/trades_controller_test.rb
+++ b/test/controllers/api/v1/trades_controller_test.rb
@@ -215,25 +215,118 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
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")
+ # Trades have no category column, so a category_id is not a trade field: it
+ # is ignored like any other unpermitted parameter, whoever owns the category.
+ test "create ignores a category_id and saves the trade" do
+ security = Security.create!(ticker: "CATBUY", name: "Category Buy Security", country_code: "US")
- 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
- } },
+ category_ids_from_every_source.each do |source, category_id|
+ assert_difference [ "Entry.count", "Trade.count" ], 1, "#{source} category" do
+ post "/api/v1/trades",
+ params: { trade: {
+ account_id: @investment_account.id,
+ type: "buy",
+ date: Date.current,
+ qty: 10,
+ price: 3,
+ security_id: security.id,
+ category_id: category_id
+ } },
+ headers: api_headers(read_write_api_key)
+ end
+
+ assert_response :created, "#{source} category"
+ body = JSON.parse(response.body)
+ trade = Trade.find(body["id"])
+ assert_equal 10, trade.qty, "#{source} category"
+ assert_equal 3, trade.price, "#{source} category"
+ assert body.key?("category"), "#{source} category"
+ assert_nil body["category"], "#{source} category"
+ end
+ end
+
+ test "update ignores a category_id and saves the other fields" do
+ trade_id = create_buy_trade("CATUPD")
+
+ category_ids_from_every_source.each do |source, category_id|
+ put api_v1_trade_url(trade_id),
+ params: { trade: { notes: "Notes with #{source} category", category_id: category_id } },
headers: api_headers(read_write_api_key)
+
+ assert_response :ok, "#{source} category"
+ body = JSON.parse(response.body)
+ assert_equal "Notes with #{source} category", body["notes"]
+ assert_equal "Notes with #{source} category", Trade.find(trade_id).entry.notes
+ assert_nil body["category"], "#{source} category"
end
+ end
- assert_response :unprocessable_entity
+ test "an update carrying only a category_id changes nothing" do
+ trade = Trade.find(create_buy_trade("CATNOOP"))
+ reset_update_side_effects(trade)
+ entry_before = trade.entry.reload.attributes
+ trade_before = trade.reload.attributes
+
+ assert_no_enqueued_jobs only: SyncJob do
+ put api_v1_trade_url(trade),
+ params: { trade: { category_id: categories(:food_and_drink).id } },
+ headers: api_headers(read_write_api_key)
+ end
+
+ assert_response :ok
+ assert_equal entry_before, trade.entry.reload.attributes
+ assert_equal trade_before, trade.reload.attributes
+ assert_not trade.entry.user_modified?
+ assert_empty trade.entry.locked_attributes
+ assert_empty trade.locked_attributes
+ end
+
+ # One change saves only the entry, the other only the trade, so each half of
+ # the changed-anything check is exercised on its own.
+ test "an update that changes a field marks, locks and syncs the trade" do
+ {
+ "entry" => [ { notes: "Changed notes" }, :entry, "notes" ],
+ "trade" => [ { investment_activity_label: "Other" }, :trade, "investment_activity_label" ]
+ }.each do |source, (fields, locked_on, locked_attr)|
+ trade = Trade.find(create_buy_trade("CAT#{source.upcase}"))
+ reset_update_side_effects(trade)
+
+ assert_enqueued_with(job: SyncJob) do
+ put api_v1_trade_url(trade),
+ params: { trade: fields.merge(category_id: categories(:food_and_drink).id) },
+ headers: api_headers(read_write_api_key)
+ end
+
+ assert_response :ok, "#{source} change"
+ trade.reload
+ assert trade.entry.reload.user_modified?, "#{source} change"
+ locked = locked_on == :entry ? trade.entry.locked_attributes : trade.locked_attributes
+ assert_includes locked.keys, locked_attr, "#{source} change"
+ end
+ end
+
+ # The update and its follow-up writes are one change: if marking fails, the
+ # edit rolls back too, so a retry finds the change still to make and marks,
+ # locks and syncs it then.
+ test "an update whose follow-up write fails changes nothing, and a retry completes it" do
+ trade = Trade.find(create_buy_trade("CATROLL"))
+ reset_update_side_effects(trade)
+ trade.entry.update_columns(notes: "Original notes")
+ original_notes = trade.entry.reload.notes
+
+ Entry.any_instance.stubs(:mark_user_modified!).raises(ActiveRecord::StatementInvalid, "write failed")
+ put api_v1_trade_url(trade), params: { trade: { notes: "Retried notes" } }, headers: api_headers(read_write_api_key)
+ assert_response :internal_server_error
+ assert_equal original_notes, trade.entry.reload.notes, "the edit was kept without its follow-ups"
+ Entry.any_instance.unstub(:mark_user_modified!)
+
+ assert_enqueued_with(job: SyncJob) do
+ put api_v1_trade_url(trade), params: { trade: { notes: "Retried notes" } }, headers: api_headers(read_write_api_key)
+ end
+ assert_response :ok
+ assert_equal "Retried notes", trade.entry.reload.notes
+ assert trade.entry.user_modified?
+ assert_includes trade.entry.locked_attributes.keys, "notes"
end
test "create deposit returns 201" do
@@ -647,7 +740,7 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
put api_v1_trade_url(trade_id),
params: update_params,
headers: api_headers(read_write_api_key)
- assert_response :success
+ assert_response :ok
response_data = JSON.parse(response.body)
assert_equal "Updated notes", response_data["notes"]
@@ -671,7 +764,7 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
params: { trade: { type: "sweep_out", qty: 4 } },
headers: api_headers(read_write_api_key)
- assert_response :success
+ assert_response :ok
body = JSON.parse(response.body)
assert_equal(-4, body["qty"].to_d)
assert_equal "Sweep Out", body["investment_activity_label"]
@@ -781,7 +874,7 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
put api_v1_trade_url(trade_id),
params: update_params,
headers: api_headers(read_write_api_key)
- assert_response :success
+ assert_response :ok
response_data = JSON.parse(response.body)
assert_equal "Updated dividend notes", response_data["notes"]
@@ -1002,6 +1095,39 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest
private
+ def category_ids_from_every_source
+ {
+ "own" => categories(:food_and_drink).id,
+ "foreign" => families(:empty).categories.create!(name: "Other family category", color: "#123456", lucide_icon: "circle").id,
+ "unknown" => SecureRandom.uuid
+ }
+ end
+
+ def create_buy_trade(ticker)
+ security = Security.create!(ticker: ticker, name: "#{ticker} Security", country_code: "US")
+ post "/api/v1/trades",
+ params: { trade: {
+ account_id: @investment_account.id,
+ type: "buy",
+ date: Date.current,
+ qty: 5,
+ price: 100,
+ currency: "USD",
+ security_id: security.id
+ } },
+ headers: api_headers(read_write_api_key)
+ assert_response :created
+ JSON.parse(response.body)["id"]
+ end
+
+ # Creating through the API marks, locks and syncs the trade, so clear that
+ # state before measuring what an update does.
+ def reset_update_side_effects(trade)
+ trade.entry.update_columns(user_modified: false, locked_attributes: {})
+ trade.update_columns(locked_attributes: {})
+ trade.entry.account.syncs.delete_all
+ end
+
def read_write_api_key
@read_write_api_key ||= ApiKey.create!(
user: @user,