Files
sure/spec/requests/api/v1/valuations_spec.rb
MkDev11 d88c2151cb Add REST API for holdings and trades (Discussion #905) (#918)
* Add REST API for holdings and trades (Discussion #905)

- Trades: GET index (filter by account_id, account_ids, start_date, end_date),
  GET show, POST create (buy/sell with security_id or ticker), PATCH update,
  DELETE destroy. Create restricted to accounts that support trades (investment
  or crypto exchange). Uses existing Trade::CreateForm for creation.
- Holdings: GET index (filter by account_id, account_ids, date, start_date,
  end_date, security_id), GET show. Read-only; scoped to family.
- Auth: read scope for index/show; write scope for create/update/destroy.
- Responses: JSON via jbuilder (trade: id, date, amount, qty, price, account,
  security, category; holding: id, date, qty, price, amount, account, security,
  avg_cost). Pagination for index endpoints (page, per_page).

Co-authored-by: Cursor <cursoragent@cursor.com>

* API v1 holdings & trades: validation, docs, specs

- Holdings: validate date params, return 400 for invalid dates (parse_date!)
- Trades: validate start_date/end_date, return 422 for invalid dates
- Trades: accept buy/sell and inflow/outflow in update (trade_sell_from_type_or_nature?)
- Trades view: nil guard for trade.security
- Trades apply_filters: single join(:entry) when filtering
- OpenAPI: add Trade/TradeCollection schemas, ErrorResponse.errors
- Add spec/requests/api/v1/holdings_spec.rb and trades_spec.rb (rswag)
- Regenerate docs/api/openapi.yaml

Co-authored-by: Cursor <cursoragent@cursor.com>

* CI: fix Brakeman and test rate-limit failures

- Disable Rack::Attack in test (use existing enabled flag) so parallel
  API tests no longer hit 429 from shared api_ip throttle
- Add Brakeman ignore for trades_controller trade_params mass-assignment
  (account_id/security_id validated in create/update)
- Trades/holdings API and OpenAPI spec updates

Co-authored-by: Cursor <cursoragent@cursor.com>

* Trades: partial qty/price update fallback; fix PATCH OpenAPI schema

- Fall back to existing trade qty/price when only one is supplied so sign
  normalisation and amount recalculation always run
- OpenAPI: remove top-level qty, price, investment_activity_label,
  category_id from PATCH body; document entryable_attributes only

Co-authored-by: Cursor <cursoragent@cursor.com>

* Trades: fix update/DELETE OpenAPI and avoid sell-trade corruption

- Only run qty/price normalisation when client sends qty or price; preserve
  existing trade direction when type/nature omitted
- OpenAPI: remove duplicate PATCH path param; add 422 for PATCH; document
  DELETE 200 body (DeleteResponse)

Co-authored-by: Cursor <cursoragent@cursor.com>

* API: flat trade update params, align holdings errors, spec/OpenAPI fixes

- Trades update: accept flat params (qty, price, type, etc.), build
  entryable_attributes in build_entry_params_for_update (match transactions)
- Holdings: ArgumentError → 422 validation_failed; parse_date!(value, name)
  with safe message; extract render_validation_error, log_and_render_error
- Specs: path id required (trades, holdings); trades delete 200 DeleteResponse;
  remove holdings 500; trades update body flat; holdings 422 invalid date
- OpenAPI: PATCH trade request body flat

Co-authored-by: Cursor <cursoragent@cursor.com>

* OpenAPI: add 422 invalid date filter to holdings index

Co-authored-by: Cursor <cursoragent@cursor.com>

* API consistency and RSwag doc-only fixes

- Trades: use render_validation_error in all 4 validation paths; safe_per_page_param case/when
- Holdings: set_holding to family.holdings.find; price as Money.format in API; safe_per_page_param case/when
- Swagger: Holding qty/price descriptions (Quantity of shares held, Formatted price per share)
- RSwag: trades delete and valuations 201 use bare run_test! (documentation only, no expect)

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix index-vs-show visibility inconsistencies and preserve custom activity labels

- Add account status filter to set_holding to match index behavior
- Add visible scope to set_trade to match index behavior
- Preserve existing investment_activity_label when updating qty/price

Co-authored-by: Cursor <cursoragent@cursor.com>

* Trades: clearer validation for non-numeric qty/price

Return 'must be valid numbers' when qty or price is non-numeric (e.g. abc)
instead of misleading 'must be present and positive'.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: mkdev11 <jaysmth689+github@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-08 11:22:32 +01:00

281 lines
6.7 KiB
Ruby

# frozen_string_literal: true
require 'swagger_helper'
RSpec.describe 'API V1 Valuations', type: :request do
let(:family) do
Family.create!(
name: 'API Family',
currency: 'USD',
locale: 'en',
date_format: '%m-%d-%Y'
)
end
let(:user) do
family.users.create!(
email: 'api-user@example.com',
password: 'password123',
password_confirmation: 'password123'
)
end
let(:oauth_application) do
Doorkeeper::Application.create!(
name: 'API Docs',
redirect_uri: 'https://example.com/callback',
scopes: 'read read_write'
)
end
let(:access_token) do
Doorkeeper::AccessToken.create!(
application: oauth_application,
resource_owner_id: user.id,
scopes: 'read_write',
expires_in: 2.hours,
token: SecureRandom.hex(32)
)
end
let(:Authorization) { "Bearer #{access_token.token}" }
let(:account) do
Account.create!(
family: family,
name: 'Investment Account',
balance: 10000,
currency: 'USD',
accountable: Investment.create!
)
end
let!(:valuation_entry) do
account.entries.create!(
name: 'Investment Reconciliation',
date: Date.current,
amount: 10000,
currency: 'USD',
entryable: Valuation.new(
kind: 'reconciliation'
)
)
end
let!(:valuation) { valuation_entry.entryable }
let!(:valuation_id) { valuation_entry.id }
path '/api/v1/valuations' do
post 'Create valuation' do
tags 'Valuations'
security [ { apiKeyAuth: [] } ]
consumes 'application/json'
produces 'application/json'
parameter name: :Authorization, in: :header, required: true, schema: { type: :string },
description: 'Bearer token with write scope'
parameter name: :body, in: :body, required: true, schema: {
type: :object,
properties: {
valuation: {
type: :object,
properties: {
account_id: { type: :string, format: :uuid, description: 'Account ID (required)' },
amount: { type: :number, description: 'Valuation amount (required)' },
date: { type: :string, format: :date, description: 'Valuation date (required)' },
notes: { type: :string, description: 'Additional notes' }
},
required: %w[account_id amount date]
}
},
required: %w[valuation]
}
let(:body) do
{
valuation: {
account_id: account.id,
amount: 15000.00,
date: Date.current.to_s
}
}
end
response '201', 'valuation created' do
schema '$ref' => '#/components/schemas/Valuation'
run_test!
end
response '422', 'validation error - missing account_id' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:body) do
{
valuation: {
amount: 15000.00,
date: Date.current.to_s
}
}
end
run_test!
end
response '422', 'validation error - missing amount' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:body) do
{
valuation: {
account_id: account.id,
date: Date.current.to_s
}
}
end
run_test!
end
response '422', 'validation error - missing date' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:body) do
{
valuation: {
account_id: account.id,
amount: 15000.00
}
}
end
run_test!
end
response '404', 'account not found' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:body) do
{
valuation: {
account_id: SecureRandom.uuid,
amount: 15000.00,
date: Date.current.to_s
}
}
end
run_test!
end
end
end
path '/api/v1/valuations/{id}' do
parameter name: :Authorization, in: :header, required: true, schema: { type: :string },
description: 'Bearer token'
parameter name: :id, in: :path, type: :string, required: true, description: 'Valuation ID (entry ID)'
get 'Retrieve a valuation' do
tags 'Valuations'
security [ { apiKeyAuth: [] } ]
produces 'application/json'
let(:id) { valuation_id }
response '200', 'valuation retrieved' do
schema '$ref' => '#/components/schemas/Valuation'
run_test!
end
response '404', 'valuation not found' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:id) { SecureRandom.uuid }
run_test!
end
end
patch 'Update a valuation' do
tags 'Valuations'
security [ { apiKeyAuth: [] } ]
consumes 'application/json'
produces 'application/json'
let(:id) { valuation_id }
parameter name: :body, in: :body, required: true, schema: {
type: :object,
properties: {
valuation: {
type: :object,
properties: {
amount: { type: :number, description: 'New valuation amount (must provide with date)' },
date: { type: :string, format: :date, description: 'New valuation date (must provide with amount)' },
notes: { type: :string, description: 'Additional notes' }
}
}
}
}
response '200', 'valuation updated with notes' do
schema '$ref' => '#/components/schemas/Valuation'
let(:body) do
{
valuation: {
notes: 'Quarterly valuation update'
}
}
end
run_test!
end
response '200', 'valuation updated with amount and date' do
schema '$ref' => '#/components/schemas/Valuation'
let(:body) do
{
valuation: {
amount: 12000.00,
date: (Date.current - 1.day).to_s
}
}
end
run_test!
end
response '422', 'validation error - only one of amount/date provided' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:body) do
{
valuation: {
amount: 12000.00
}
}
end
run_test!
end
response '404', 'valuation not found' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:id) { SecureRandom.uuid }
let(:body) do
{
valuation: {
notes: 'This will fail'
}
}
end
run_test!
end
end
end
end