Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(api): expose kind, exact amount and split state on transactions (#4422)

Bhargav Mehta9b75bdc45c18
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rb
index d67c369a8d..72bdf792fe 100644
--- a/app/controllers/accounts_controller.rb
+++ b/app/controllers/accounts_controller.rb
@@ -151,11 +151,7 @@ class AccountsController < ApplicationController
end
entry_ids = @entries.map(&:id)
- @split_parent_entry_ids = if entry_ids.any?
- Entry.where(parent_entry_id: entry_ids).distinct.pluck(:parent_entry_id).to_set
- else
- Set.new
- end
+ @split_parent_entry_ids = Entry.split_parent_ids_among(entry_ids)
# Load split parent entries for grouped display (only when grouping is enabled)
@split_parents = if Current.user.show_split_grouped?
diff --git a/app/controllers/api/v1/splits_controller.rb b/app/controllers/api/v1/splits_controller.rb
index f3a32d486f..f079633ae2 100644
--- a/app/controllers/api/v1/splits_controller.rb
+++ b/app/controllers/api/v1/splits_controller.rb
@@ -141,6 +141,8 @@ class Api::V1::SplitsController < Api::V1::BaseController
transfer_as_inflow: { outflow_transaction: { entry: :account } }
)
.order("entries.created_at")
+ # A split child is never splittable, so none of them can be a split parent.
+ @split_parent_entry_ids = Set.new
render :show, status: status
end
diff --git a/app/controllers/api/v1/transactions_controller.rb b/app/controllers/api/v1/transactions_controller.rb
index c4bd07872e..766b1dd6d9 100644
--- a/app/controllers/api/v1/transactions_controller.rb
+++ b/app/controllers/api/v1/transactions_controller.rb
@@ -42,6 +42,8 @@ class Api::V1::TransactionsController < Api::V1::BaseController
# Make per_page available to the template
@per_page = safe_per_page_param
+ @split_parent_entry_ids = split_parent_entry_ids_for(@transactions)
+
# Rails will automatically use app/views/api/v1/transactions/index.json.jbuilder
render :index
diff --git a/app/controllers/concerns/api/v1/transaction_lookup.rb b/app/controllers/concerns/api/v1/transaction_lookup.rb
index 37a8087a59..b9efe8fd46 100644
--- a/app/controllers/concerns/api/v1/transaction_lookup.rb
+++ b/app/controllers/concerns/api/v1/transaction_lookup.rb
@@ -22,4 +22,11 @@ module Api::V1::TransactionLookup
message: "Transaction not found"
}, status: :not_found
end
+
+ # Entry ids among `transactions` that have split children, as a Set, in one
+ # query that loads no child rows. The transaction partial reads it for
+ # `split_parent`.
+ def split_parent_entry_ids_for(transactions)
+ Entry.split_parent_ids_among(transactions.map { |transaction| transaction.entry.id })
+ end
end
diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rb
index 08a4df3b22..67ab63c29a 100644
--- a/app/controllers/transactions_controller.rb
+++ b/app/controllers/transactions_controller.rb
@@ -70,11 +70,7 @@ class TransactionsController < ApplicationController
end
# Preload which entries on this page are split parents (have children) to avoid N+1
- @split_parent_entry_ids = if entry_ids.any?
- Entry.where(parent_entry_id: entry_ids).distinct.pluck(:parent_entry_id).to_set
- else
- Set.new
- end
+ @split_parent_entry_ids = Entry.split_parent_ids_among(entry_ids)
# Counts what the categorize wizard can act on, so read-only shares don't
# keep the "Categorize" menu item visible.
diff --git a/app/models/entry.rb b/app/models/entry.rb
index e0cceb454c..6a61b8656e 100644
--- a/app/models/entry.rb
+++ b/app/models/entry.rb
@@ -104,6 +104,14 @@ class Entry < ApplicationRecord
pending.where("entries.date < ?", days.days.ago.to_date)
}
+ # Ids among `entry_ids` that have split children, as a Set, in one query that
+ # loads no child rows. Shared by the web and API list views to avoid N+1.
+ def self.split_parent_ids_among(entry_ids)
+ return Set.new if entry_ids.blank?
+
+ where(parent_entry_id: entry_ids).distinct.pluck(:parent_entry_id).to_set
+ end
+
# Family-scoped query for Enrichable#clear_ai_cache
def self.family_scope(family)
joins(:account).where(accounts: { family_id: family.id })
diff --git a/app/views/api/v1/splits/show.json.jbuilder b/app/views/api/v1/splits/show.json.jbuilder
index 8713477034..4a265efcfc 100644
--- a/app/views/api/v1/splits/show.json.jbuilder
+++ b/app/views/api/v1/splits/show.json.jbuilder
@@ -12,12 +12,9 @@ amount_money = @entry.amount_money
json.amount_cents (amount_money.amount * amount_money.currency.minor_unit_conversion).round(0).to_i.abs
json.currency @entry.currency
+# PATCH replaces every child, so a client editing one field has to send the
+# rest back unchanged. The transaction partial carries the exact
+# `amount_decimal` and the `excluded` flag that needs.
json.children @children do |child|
- json.partial! "api/v1/transactions/transaction", transaction: child
-
- # PATCH replaces every child, so a client editing one field has to send the
- # rest back unchanged. The transaction partial carries neither of these: its
- # amount is display-rounded, and it never emits the exclusion flag.
- json.amount_decimal child.entry.amount.to_s
- json.excluded child.entry.excluded
+ json.partial! "api/v1/transactions/transaction", transaction: child, split_parent_ids: @split_parent_entry_ids
end
diff --git a/app/views/api/v1/transactions/_transaction.json.jbuilder b/app/views/api/v1/transactions/_transaction.json.jbuilder
index dbf276ee86..5584c5da58 100644
--- a/app/views/api/v1/transactions/_transaction.json.jbuilder
+++ b/app/views/api/v1/transactions/_transaction.json.jbuilder
@@ -14,6 +14,14 @@ amount_cents = (amount_money.amount * conversion_factor).round(0).to_i.abs
json.amount_cents amount_cents
json.signed_amount_cents(transaction.entry.classification == "income" ? amount_cents : -amount_cents)
+# `amount` and `amount_cents` are both rounded to the currency's display
+# precision, but entries store decimal(19,4). Expose the stored value
+# unrounded, as a locale-independent string in the entry's own sign
+# convention (positive = outflow, negative = inflow), the same field split
+# show returns, so a client can build a split that sums exactly. "F" keeps
+# it fixed-point (12.3456, never 0.123456e2).
+json.amount_decimal transaction.entry.amount.to_s("F")
+
json.currency transaction.entry.currency
json.name transaction.entry.name
json.notes transaction.entry.notes
@@ -22,6 +30,23 @@ json.source transaction.entry.source
json.user_modified transaction.entry.user_modified
json.classification transaction.entry.classification
+# How budgets and reports treat the row: loan_payment counts as an expense
+# whatever the amount's sign; investment_contribution does too unless the
+# family turned off investment_contributions_as_spending, in which case it is
+# reported as invested and left out (Family#analytics_excluded_kinds); and
+# Transaction::BUDGET_EXCLUDED_KINDS are left out entirely.
+json.kind transaction.kind
+
+# Excluded entries are left out of budget and report totals, and splitting
+# marks the parent excluded. A split parent's amount is carried by its
+# children, so a client summing a list should skip the parent. entries.excluded
+# is nullable, so the predicate keeps the field a boolean. Callers that render
+# many rows pass split_parent_ids (the set of entry ids with children) so
+# split_parent costs no query per row; a single row falls back to an EXISTS.
+json.excluded transaction.entry.excluded?
+split_parent_ids = local_assigns[:split_parent_ids]
+json.split_parent split_parent_ids ? split_parent_ids.include?(transaction.entry.id) : transaction.entry.split_parent?
+
# Account information
json.account do
json.id transaction.entry.account.id
diff --git a/app/views/api/v1/transactions/index.json.jbuilder b/app/views/api/v1/transactions/index.json.jbuilder
index 5718567e4b..5f2e13d09e 100644
--- a/app/views/api/v1/transactions/index.json.jbuilder
+++ b/app/views/api/v1/transactions/index.json.jbuilder
@@ -1,7 +1,7 @@
# frozen_string_literal: true
json.transactions @transactions do |transaction|
- json.partial! "transaction", transaction: transaction
+ json.partial! "transaction", transaction: transaction, split_parent_ids: @split_parent_entry_ids
end
json.pagination do
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 1fb10764e1..79f8f6e79a 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -1735,9 +1735,13 @@ components:
- id
- date
- amount
+ - amount_decimal
- currency
- name
- classification
+ - kind
+ - excluded
+ - split_parent
- account
- tags
- created_at
@@ -1751,6 +1755,11 @@ components:
format: date
amount:
type: string
+ description: Formatted amount, rounded to the currency display precision
+ amount_decimal:
+ type: string
+ description: Exact stored amount as an unrounded, locale-independent decimal
+ string. Positive is an outflow, negative an inflow.
currency:
type: string
name:
@@ -1768,6 +1777,28 @@ components:
type: boolean
classification:
type: string
+ kind:
+ type: string
+ enum:
+ - standard
+ - funds_movement
+ - cc_payment
+ - loan_payment
+ - one_time
+ - investment_contribution
+ description: How budgets and reports treat the transaction. loan_payment
+ counts as an expense; investment_contribution does too when the family
+ counts investment contributions as spending, and is otherwise reported
+ as invested and left out of spending and income; funds_movement, cc_payment
+ and one_time are left out of budget totals.
+ excluded:
+ type: boolean
+ description: Whether the transaction is excluded from budget and report
+ totals. Splitting a transaction marks it excluded.
+ split_parent:
+ type: boolean
+ description: Whether the transaction has been split; its amount is then
+ carried by its split children.
account:
"$ref": "#/components/schemas/Account"
category:
diff --git a/docs/api/transactions.md b/docs/api/transactions.md
index e0eee37831..752023a882 100644
--- a/docs/api/transactions.md
+++ b/docs/api/transactions.md
@@ -66,10 +66,16 @@ A transaction response includes:
"id": "uuid",
"date": "2024-01-15",
"amount": "$75.50",
+ "amount_cents": 7550,
+ "signed_amount_cents": -7550,
+ "amount_decimal": "75.5",
"currency": "USD",
"name": "Grocery shopping",
"notes": "Weekly groceries",
"classification": "expense",
+ "kind": "standard",
+ "excluded": false,
+ "split_parent": false,
"account": {
"id": "uuid",
"name": "Checking Account",
@@ -99,6 +105,17 @@ A transaction response includes:
}
```
+### Amounts, kind and exclusion
+
+| Field | Description |
+| --- | --- |
+| `amount` | Formatted for display and rounded to the currency's precision. Don't parse it. |
+| `amount_cents` / `signed_amount_cents` | Integer minor units, also rounded. |
+| `amount_decimal` | The exact stored amount as an unrounded decimal string (for example `"12.3456"`), independent of locale. Positive is an outflow, negative an inflow. Use it when the amount has to match exactly, such as the split amounts sent to `POST /api/v1/transactions/{id}/split`. |
+| `kind` | One of `standard`, `funds_movement`, `cc_payment`, `loan_payment`, `one_time`, `investment_contribution`. Budgets and reports count `loan_payment` as an expense whatever the sign of its amount, and leave `funds_movement`, `cc_payment` and `one_time` out. `investment_contribution` also counts as an expense when the family counts investment contributions as spending (the default); when that setting is off it is reported as invested and left out of spending and income. `classification` only follows the amount's sign. |
+| `excluded` | `true` when the transaction is left out of budget and report totals. |
+| `split_parent` | `true` when the transaction has been split. Splitting a transaction marks it excluded, and its split children carry the amount. |
+
## Creating transactions
When creating a transaction, the `nature` field determines how the amount is stored:
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index de256ad2ca..5635ec807d 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -936,11 +936,15 @@ RSpec.configure do |config|
},
Transaction: {
type: :object,
- required: %w[id date amount currency name classification account tags created_at updated_at],
+ required: %w[id date amount amount_decimal currency name classification kind excluded split_parent account tags created_at updated_at],
properties: {
id: { type: :string, format: :uuid },
date: { type: :string, format: :date },
- amount: { type: :string },
+ amount: { type: :string, description: 'Formatted amount, rounded to the currency display precision' },
+ amount_decimal: {
+ type: :string,
+ description: 'Exact stored amount as an unrounded, locale-independent decimal string. Positive is an outflow, negative an inflow.'
+ },
currency: { type: :string },
name: { type: :string },
notes: { type: :string, nullable: true },
@@ -948,6 +952,16 @@ RSpec.configure do |config|
source: { type: :string, nullable: true },
user_modified: { type: :boolean },
classification: { type: :string },
+ kind: {
+ type: :string,
+ enum: Transaction.kinds.keys,
+ description: 'How budgets and reports treat the transaction. loan_payment counts as an expense; ' \
+ 'investment_contribution does too when the family counts investment contributions as ' \
+ 'spending, and is otherwise reported as invested and left out of spending and income; ' \
+ 'funds_movement, cc_payment and one_time are left out of budget totals.'
+ },
+ excluded: { type: :boolean, description: 'Whether the transaction is excluded from budget and report totals. Splitting a transaction marks it excluded.' },
+ split_parent: { type: :boolean, description: 'Whether the transaction has been split; its amount is then carried by its split children.' },
account: { '$ref' => '#/components/schemas/Account' },
category: { '$ref' => '#/components/schemas/Category', nullable: true },
merchant: { '$ref' => '#/components/schemas/Merchant', nullable: true },
diff --git a/test/controllers/api/v1/transactions_controller_test.rb b/test/controllers/api/v1/transactions_controller_test.rb
index 4d9b6e71f0..3573ab1935 100644
--- a/test/controllers/api/v1/transactions_controller_test.rb
+++ b/test/controllers/api/v1/transactions_controller_test.rb
@@ -949,6 +949,128 @@ end
assert_empty queries.grep(/SELECT "accounts"\.\* FROM "accounts" WHERE "accounts"\."id" =/)
end
+ test "transaction JSON exposes the exact stored amount alongside the rounded ones" do
+ entry = create_transaction(account: @account, amount: 12.3456, name: "Four decimals")
+
+ get api_v1_transaction_url(entry.transaction), headers: api_headers(@api_key)
+ assert_response :success
+
+ data = JSON.parse(response.body)
+ assert_equal "12.3456", data["amount_decimal"]
+ assert_equal 1235, data["amount_cents"], "amount_cents stays display-rounded"
+ assert_amount_cents_fields(data)
+ end
+
+ test "amount_decimal keeps the stored sign and ignores the request locale" do
+ entry = create_transaction(account: @account, amount: -1234.5, name: "Refund")
+
+ get api_v1_transaction_url(entry.transaction),
+ headers: api_headers(@api_key).merge("Accept-Language" => "de")
+ assert_response :success
+
+ assert_equal "-1234.5", JSON.parse(response.body)["amount_decimal"]
+ end
+
+ test "transaction JSON exposes kind" do
+ entry = create_transaction(account: @account, amount: -250, name: "Loan payment", kind: "loan_payment")
+
+ get api_v1_transaction_url(entry.transaction), headers: api_headers(@api_key)
+ assert_response :success
+
+ data = JSON.parse(response.body)
+ assert_equal "loan_payment", data["kind"]
+ assert_equal "income", data["classification"], "classification still follows the amount sign; kind lets a client tell"
+ end
+
+ test "an ordinary transaction is neither a split parent nor excluded" do
+ entry = create_transaction(account: @account, amount: 40, name: "Plain")
+
+ get api_v1_transaction_url(entry.transaction), headers: api_headers(@api_key)
+ assert_response :success
+
+ data = JSON.parse(response.body)
+ assert_equal "standard", data["kind"]
+ assert_equal false, data["split_parent"]
+ assert_equal false, data["excluded"]
+ end
+
+ test "index marks split parents and their children" do
+ parent = create_transaction(account: @account, amount: 100, name: "Split parent", date: 3.days.ago.to_date)
+ parent.split!([
+ { name: "Kept", amount: 60, category_id: nil },
+ { name: "Left out", amount: 40, category_id: nil, excluded: true }
+ ])
+
+ get api_v1_transactions_url,
+ params: { account_id: @account.id, start_date: 3.days.ago.to_date, end_date: 3.days.ago.to_date, per_page: 100 },
+ headers: api_headers(@api_key)
+ assert_response :success
+
+ rows = JSON.parse(response.body)["transactions"].index_by { |row| row["name"] }
+ assert_equal true, rows["Split parent"]["split_parent"]
+ assert_equal true, rows["Split parent"]["excluded"]
+ assert_equal false, rows["Kept"]["split_parent"]
+ assert_equal false, rows["Kept"]["excluded"]
+ assert_equal false, rows["Left out"]["split_parent"]
+ assert_equal true, rows["Left out"]["excluded"]
+
+ # show renders the same partial without the batched ids and must still report it
+ get api_v1_transaction_url(parent.transaction), headers: api_headers(@api_key)
+ assert_response :success
+ assert_equal true, JSON.parse(response.body)["split_parent"]
+ end
+
+ test "index works out split_parent without a query per row" do
+ split_parent = lambda do |name|
+ create_transaction(account: @account, amount: 10, name: name).split!([
+ { name: "#{name} a", amount: 4, category_id: nil },
+ { name: "#{name} b", amount: 6, category_id: nil }
+ ])
+ end
+
+ split_parent.call("Baseline")
+ baseline_queries = count_db_queries do
+ get api_v1_transactions_url, params: { per_page: 100 }, headers: api_headers(@api_key)
+ assert_response :success
+ end
+
+ 3.times { |i| split_parent.call("More #{i}") }
+ expanded_queries = count_db_queries do
+ get api_v1_transactions_url, params: { per_page: 100 }, headers: api_headers(@api_key)
+ assert_response :success
+ end
+
+ assert_equal baseline_queries, expanded_queries
+ end
+
+ test "index works out split_parent without loading the split children" do
+ create_transaction(account: @account, amount: 10, name: "Big split").split!(
+ [ { name: "Part a", amount: 4, category_id: nil }, { name: "Part b", amount: 6, category_id: nil } ]
+ )
+
+ queries = capture_sql_queries do
+ get api_v1_transactions_url, params: { per_page: 100 }, headers: api_headers(@api_key)
+ end
+ assert_response :success
+
+ assert_empty queries.grep(/SELECT "entries"\.\* FROM "entries" WHERE "entries"\."parent_entry_id"/),
+ "split children should not be loaded just to compute split_parent"
+ end
+
+ test "excluded is false, not null, when the stored flag is null" do
+ entry = create_transaction(account: @account, amount: 20, name: "Null exclusion")
+ entry.update_column(:excluded, nil)
+
+ get api_v1_transaction_url(entry.transaction), headers: api_headers(@api_key)
+ assert_response :success
+ assert_equal false, JSON.parse(response.body)["excluded"]
+
+ get api_v1_transactions_url, params: { per_page: 100 }, headers: api_headers(@api_key)
+ assert_response :success
+ row = JSON.parse(response.body)["transactions"].find { |t| t["id"] == entry.transaction.id }
+ assert_equal false, row["excluded"]
+ end
+
private
def api_headers(api_key)