Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(API): Add API endpoints for transaction splits (#4117)

Lotte B9a732ecc855d
diff --git a/app/controllers/api/v1/splits_controller.rb b/app/controllers/api/v1/splits_controller.rb
new file mode 100644
index 0000000000..49c921b8e2
--- /dev/null
+++ b/app/controllers/api/v1/splits_controller.rb
@@ -0,0 +1,254 @@
+# frozen_string_literal: true
+
+# Splits a transaction into child transactions that sum to it.
+#
+# The model has supported this since splits shipped (`Entry#split!` /
+# `Entry#unsplit!`), and the web UI exposes it, but the API did not -- and
+# `Api::V1::TransactionsController` actively refuses split edits with "Use the
+# split editor", which an API consumer cannot reach. These actions close that
+# gap using the same model calls the UI makes.
+class Api::V1::SplitsController < Api::V1::BaseController
+ include Api::V1::TransactionLookup
+
+ AlreadySplit = Class.new(StandardError)
+ NotSplit = Class.new(StandardError)
+
+ # entries.amount is decimal(19,4). Children are rounded independently on
+ # assignment, so raw values that sum to the parent can persist as a total
+ # that does not: 33.33335 + 66.66665 becomes 33.3334 + 66.6667 = 100.0001.
+ AMOUNT_SCALE = 4
+ # 15 integer digits. Oversized amounts that cancel out pass split!'s sum
+ # check and then overflow the column, which surfaces as a 500.
+ AMOUNT_LIMIT = BigDecimal(10)**15
+ before_action :ensure_read_scope, only: [ :show ]
+ before_action :ensure_write_scope, only: [ :create, :update, :destroy ]
+ before_action :set_transaction
+ before_action :resolve_to_parent
+ before_action :ensure_account_write_permission, only: [ :create, :update, :destroy ]
+
+ # GET /api/v1/transactions/:transaction_id/split
+ def show
+ return render_not_split unless @entry.split_parent?
+
+ render_split
+ end
+
+ # POST /api/v1/transactions/:transaction_id/split
+ def create
+ unless @transaction.splittable?
+ return render_unprocessable("Transaction cannot be split", [ not_splittable_reason ])
+ end
+
+ splits = build_splits
+ return if performed?
+
+ # Explicit transaction + lock!, NOT Entry#with_lock: on Rails 8.1 the
+ # with_lock form silently discards the whole split -- no children, no
+ # exception. Verified against real data before relying on this.
+ Entry.transaction do
+ @entry.lock!
+ # Re-check inside the lock: two concurrent POSTs can both clear the
+ # check above, and split! validates only its own amounts, so both sets
+ # of children would be inserted and the transaction counted twice.
+ raise AlreadySplit if @entry.split_parent?
+
+ @entry.split!(splits)
+ end
+ @entry.sync_account_later
+ @entry.reload
+
+ render_split status: :created
+ rescue AlreadySplit
+ render_unprocessable("Transaction cannot be split", [ "Transaction is already split" ])
+ rescue ActiveRecord::RecordInvalid => e
+ render_unprocessable(e.message)
+ end
+
+ # PATCH/PUT /api/v1/transactions/:transaction_id/split
+ #
+ # Replaces the existing children. They are destroyed and recreated, exactly as
+ # the web UI does it, so anything set on a child afterwards -- a category, an
+ # exclusion -- is NOT carried over. Send the full set you want.
+ def update
+ return render_not_split unless @entry.split_parent?
+
+ splits = build_splits
+ return if performed?
+
+ Entry.transaction do
+ @entry.lock!
+ # The split_parent? test above runs before the lock, so a concurrent
+ # DELETE can unsplit in between; without this the replacement would
+ # resurrect a split the other caller just removed.
+ raise NotSplit unless @entry.split_parent?
+
+ @entry.unsplit!
+ @entry.split!(splits)
+ end
+ @entry.sync_account_later
+ @entry.reload
+
+ render_split
+ rescue NotSplit
+ render_not_split
+ rescue ActiveRecord::RecordInvalid => e
+ render_unprocessable(e.message)
+ end
+
+ # DELETE /api/v1/transactions/:transaction_id/split
+ def destroy
+ return render_not_split unless @entry.split_parent?
+
+ Entry.transaction do
+ @entry.lock!
+ raise NotSplit unless @entry.split_parent?
+
+ @entry.unsplit!
+ end
+ @entry.sync_account_later
+
+ head :no_content
+ rescue NotSplit
+ render_not_split
+ rescue ActiveRecord::RecordInvalid => e
+ render_unprocessable(e.message)
+ end
+
+ private
+
+ def ensure_read_scope
+ authorize_scope!(:read)
+ end
+
+ def ensure_write_scope
+ authorize_scope!(:write)
+ end
+
+ # The token scope says what the KEY may do; this says what its owner may do
+ # to this account. `Account.accessible_by` admits every share, read-only
+ # ones included, so without this a read-only share could rewrite someone
+ # else's transaction. SplitsController enforces the same thing through
+ # require_account_permission!.
+ def ensure_account_write_permission
+ return if performed?
+ return if @entry.account.permission_for(current_resource_owner).in?([ :owner, :full_control ])
+
+ render json: {
+ error: "forbidden",
+ message: "You do not have write access to this account"
+ }, status: :forbidden
+ end
+
+ def set_transaction
+ load_accessible_transaction(params[:transaction_id])
+ end
+
+ # Loaded from the Transaction side because that is the direction the
+ # transaction partial reads in (transaction.entry.account). Preloading
+ # child_entries.entryable does not help: the polymorphic pair has no
+ # inverse, so each child would reload its entry and account.
+ def render_split(status: :ok)
+ @children = Transaction
+ .joins(:entry)
+ .where(entries: { parent_entry_id: @entry.id })
+ .preload(
+ { entry: :account },
+ :category, :merchant, :tags,
+ transfer_as_outflow: { inflow_transaction: { entry: :account } },
+ transfer_as_inflow: { outflow_transaction: { entry: :account } }
+ )
+ .order("entries.created_at")
+
+ render :show, status: status
+ end
+
+ # Addressing a child by id resolves to its parent, so a caller holding any
+ # id from the split can operate on it. Mirrors the web controller.
+ def resolve_to_parent
+ return if performed?
+ return unless @entry&.split_child?
+
+ @entry = @entry.parent_entry
+ @transaction = @entry.transaction
+ end
+
+ # Amounts use the SAME sign convention as the parent's `amount`, which is
+ # what `GET /api/v1/transactions/:id` returns. The web controller negates
+ # what its form submits; that is a property of the form, not of the model,
+ # and an API that flipped the sign of its input would contradict the
+ # transaction endpoints it sits beside.
+ def build_splits
+ raw = params.dig(:split, :splits)
+ raw = raw.values if raw.respond_to?(:values)
+
+ unless raw.is_a?(Array) && raw.any?
+ render_unprocessable("splits must be a non-empty array")
+ return nil
+ end
+
+ raw.map do |s|
+ unless s.respond_to?(:permit)
+ render_unprocessable("each split must be an object")
+ return nil
+ end
+
+ s = s.permit(:name, :amount, :category_id, :excluded)
+ category_id = s[:category_id].presence
+ if category_id && !family_category_ids.include?(category_id)
+ render_unprocessable("Unknown category: #{category_id}")
+ return nil
+ end
+
+ # 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
+ render_unprocessable("split amount is out of range")
+ return nil
+ end
+
+ {
+ # Documented as optional, defaulting to the parent's name; Entry
+ # validates presence, so apply the default rather than 422 on it.
+ name: s[:name].presence || @entry.name,
+ amount: amount,
+ category_id: category_id,
+ excluded: s[:excluded]
+ }
+ end
+ rescue ArgumentError, TypeError
+ render_unprocessable("each split requires a numeric amount")
+ nil
+ end
+
+ # belongs_to :category is unscoped, so a known UUID from another family
+ # would be accepted and then serialized back to the caller.
+ def family_category_ids
+ @family_category_ids ||= current_resource_owner.family.categories.pluck(:id).to_set
+ end
+
+ def not_splittable_reason
+ return "Transaction is part of a transfer" if @transaction.transfer?
+ return "Transaction is already split" if @entry.split_parent?
+ return "Transaction is pending" if @transaction.pending?
+ return "Transaction is excluded" if @entry.excluded?
+
+ "Transaction is not splittable"
+ end
+
+ def render_not_split
+ render json: {
+ error: "not_found",
+ message: "Transaction is not split"
+ }, status: :not_found
+ end
+
+ def render_unprocessable(message, errors = nil)
+ render json: {
+ error: "validation_failed",
+ message: message,
+ errors: errors || [ message ]
+ }, status: :unprocessable_entity
+ end
+end
diff --git a/app/controllers/api/v1/transactions_controller.rb b/app/controllers/api/v1/transactions_controller.rb
index dbb5e4b2b7..c4bd07872e 100644
--- a/app/controllers/api/v1/transactions_controller.rb
+++ b/app/controllers/api/v1/transactions_controller.rb
@@ -2,6 +2,7 @@
class Api::V1::TransactionsController < Api::V1::BaseController
include Pagy::Backend
+ include Api::V1::TransactionLookup
# Ensure proper scope authorization for read vs write access
before_action :ensure_read_scope, only: [ :index, :show ]
@@ -205,19 +206,7 @@ class Api::V1::TransactionsController < Api::V1::BaseController
private
def set_transaction
- raise ActiveRecord::RecordNotFound unless valid_uuid?(params[:id])
-
- family = current_resource_owner.family
- @transaction = family.transactions
- .joins(entry: :account)
- .merge(Account.accessible_by(current_resource_owner))
- .find(params[:id])
- @entry = @transaction.entry
- rescue ActiveRecord::RecordNotFound
- render json: {
- error: "not_found",
- message: "Transaction not found"
- }, status: :not_found
+ load_accessible_transaction(params[:id])
end
def ensure_read_scope
diff --git a/app/controllers/concerns/api/v1/transaction_lookup.rb b/app/controllers/concerns/api/v1/transaction_lookup.rb
new file mode 100644
index 0000000000..37a8087a59
--- /dev/null
+++ b/app/controllers/concerns/api/v1/transaction_lookup.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+# Family- and share-scoped transaction lookup, shared by the controllers that
+# address a transaction by id so the scoping has one place to change.
+module Api::V1::TransactionLookup
+ extend ActiveSupport::Concern
+
+ private
+
+ def load_accessible_transaction(id)
+ raise ActiveRecord::RecordNotFound unless valid_uuid?(id)
+
+ family = current_resource_owner.family
+ @transaction = family.transactions
+ .joins(entry: :account)
+ .merge(Account.accessible_by(current_resource_owner))
+ .find(id)
+ @entry = @transaction.entry
+ rescue ActiveRecord::RecordNotFound
+ render json: {
+ error: "not_found",
+ message: "Transaction not found"
+ }, status: :not_found
+ end
+end
diff --git a/app/views/api/v1/splits/show.json.jbuilder b/app/views/api/v1/splits/show.json.jbuilder
new file mode 100644
index 0000000000..8713477034
--- /dev/null
+++ b/app/views/api/v1/splits/show.json.jbuilder
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+json.transaction_id @transaction.id
+json.amount @entry.amount_money.format
+
+# The formatted amount above rounds to the currency's display precision, but
+# split! requires submitted children to sum to the stored decimal(19,4) value.
+# A client replacing a split needs the exact figure, so expose it unrounded,
+# alongside the minor-unit integer the transaction partial already uses.
+json.amount_decimal @entry.amount.to_s
+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
+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
+end
diff --git a/config/routes.rb b/config/routes.rb
index ee09c80fb1..0a7ceae692 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -759,7 +759,9 @@ Rails.application.routes.draw do
resources :security_prices, only: [ :index, :show ]
resources :tags, only: [ :index, :show, :create, :update, :destroy ]
- resources :transactions, only: [ :index, :show, :create, :update, :destroy ]
+ resources :transactions, only: [ :index, :show, :create, :update, :destroy ] do
+ resource :split, only: [ :show, :create, :update, :destroy ]
+ end
resources :trades, only: [ :index, :show, :create, :update, :destroy ]
resources :holdings, only: [ :index, :show ]
resources :transfers, only: [ :index, :show ]
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index d2e694b615..2da85e13c8 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -32,6 +32,80 @@ components:
read: Read access
read_write: Read and write access
schemas:
+ SplitRequest:
+ type: object
+ required:
+ - split
+ properties:
+ split:
+ type: object
+ required:
+ - splits
+ properties:
+ splits:
+ type: array
+ minItems: 1
+ description: Child transactions. Amounts must sum exactly to the parent
+ amount.
+ items:
+ type: object
+ required:
+ - amount
+ properties:
+ name:
+ type: string
+ nullable: true
+ description: Defaults to the parent name when omitted
+ amount:
+ type: string
+ description: Same sign convention as the transaction amount
+ category_id:
+ type: string
+ nullable: true
+ excluded:
+ type: boolean
+ nullable: true
+ Split:
+ type: object
+ required:
+ - transaction_id
+ - amount
+ - amount_decimal
+ - amount_cents
+ - currency
+ - children
+ properties:
+ transaction_id:
+ type: string
+ amount:
+ type: string
+ description: Formatted parent amount, rounded for display
+ amount_decimal:
+ type: string
+ description: Exact stored amount; children must sum to this
+ amount_cents:
+ type: integer
+ description: Absolute amount in minor units
+ currency:
+ type: string
+ children:
+ type: array
+ items:
+ "$ref": "#/components/schemas/SplitChild"
+ SplitChild:
+ allOf:
+ - "$ref": "#/components/schemas/Transaction"
+ - type: object
+ required:
+ - amount_decimal
+ - excluded
+ properties:
+ amount_decimal:
+ type: string
+ description: Exact stored amount; send this back when replacing the split
+ excluded:
+ type: boolean
+ description: Whether this child is excluded from totals
Pagination:
type: object
required:
@@ -9090,6 +9164,88 @@ paths:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
+ "/api/v1/transactions/{transaction_id}/split":
+ parameters:
+ - name: transaction_id
+ in: path
+ description: Transaction ID. A split child resolves to its parent.
+ required: true
+ schema:
+ type: string
+ post:
+ summary: Split a transaction
+ tags:
+ - Transactions
+ security:
+ - apiKeyAuth: []
+ description: Splits a transaction into child transactions. The child amounts
+ must sum exactly to the parent amount, using the same sign convention the
+ transaction endpoints return. The parent becomes excluded from totals.
+ parameters: []
+ responses:
+ '201':
+ description: transaction split
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/Split"
+ '422':
+ description: amounts do not sum to the parent, or the transaction cannot
+ be split
+ requestBody:
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/SplitRequest"
+ get:
+ summary: Retrieve a transaction split
+ tags:
+ - Transactions
+ security:
+ - apiKeyAuth: []
+ description: Returns the child transactions of a split.
+ responses:
+ '200':
+ description: split returned
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/Split"
+ '404':
+ description: transaction is not split
+ patch:
+ summary: Replace a transaction split
+ tags:
+ - Transactions
+ security:
+ - apiKeyAuth: []
+ description: Replaces the children of an existing split. The previous children
+ are destroyed, so anything set on them afterwards is not carried over.
+ parameters: []
+ responses:
+ '200':
+ description: split replaced
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/Split"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/SplitRequest"
+ delete:
+ summary: Remove a transaction split
+ tags:
+ - Transactions
+ security:
+ - apiKeyAuth: []
+ description: Removes the children and restores the parent transaction.
+ responses:
+ '204':
+ description: split removed
+ '404':
+ description: transaction is not split
"/api/v1/syncs":
get:
summary: Lists sync history
diff --git a/spec/requests/api/v1/splits_spec.rb b/spec/requests/api/v1/splits_spec.rb
new file mode 100644
index 0000000000..dca430dec8
--- /dev/null
+++ b/spec/requests/api/v1/splits_spec.rb
@@ -0,0 +1,150 @@
+# frozen_string_literal: true
+
+require 'swagger_helper'
+
+# Documentation only. Behavioral coverage lives in
+# test/controllers/api/v1/splits_controller_test.rb, per
+# docs/llm-guides/api-endpoint-consistency.md.
+RSpec.describe 'API V1 Transaction Split', 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: '[email protected]',
+ password: 'password123',
+ password_confirmation: 'password123'
+ )
+ end
+
+ let(:api_key) do
+ key = ApiKey.generate_secure_key
+ ApiKey.create!(
+ user: user,
+ name: 'API Docs Key',
+ key: key,
+ scopes: %w[read_write],
+ source: 'web'
+ )
+ end
+
+ let(:'X-Api-Key') { api_key.plain_key }
+
+ let(:account) do
+ Account.create!(
+ family: family,
+ name: 'Checking Account',
+ balance: 1000,
+ currency: 'USD',
+ accountable: Depository.create!
+ )
+ end
+
+ let!(:transaction) do
+ entry = account.entries.create!(
+ name: 'Marketplace order',
+ date: Date.current,
+ amount: 100,
+ currency: 'USD',
+ entryable: Transaction.new
+ )
+ entry.transaction
+ end
+
+ let(:transaction_id) { transaction.id }
+
+ let(:split_payload) do
+ {
+ split: {
+ splits: [
+ { name: 'Groceries portion', amount: '60.0' },
+ { name: 'Household portion', amount: '40.0' }
+ ]
+ }
+ }
+ end
+
+ path '/api/v1/transactions/{transaction_id}/split' do
+ parameter name: :transaction_id, in: :path, type: :string,
+ description: 'Transaction ID. A split child resolves to its parent.'
+
+ post 'Split a transaction' do
+ tags 'Transactions'
+ security [ { apiKeyAuth: [] } ]
+ description 'Splits a transaction into child transactions. The child amounts must sum ' \
+ 'exactly to the parent amount, using the same sign convention the ' \
+ 'transaction endpoints return. The parent becomes excluded from totals.'
+ consumes 'application/json'
+ produces 'application/json'
+ parameter name: :split, in: :body, schema: { '$ref' => '#/components/schemas/SplitRequest' }
+
+ let(:split) { split_payload }
+
+ response '201', 'transaction split' do
+ schema '$ref' => '#/components/schemas/Split'
+ run_test!
+ end
+
+ response '422', 'amounts do not sum to the parent, or the transaction cannot be split' do
+ let(:split) { { split: { splits: [ { name: 'Too small', amount: '1.0' } ] } } }
+ run_test!
+ end
+ end
+
+ get 'Retrieve a transaction split' do
+ tags 'Transactions'
+ security [ { apiKeyAuth: [] } ]
+ description 'Returns the child transactions of a split.'
+ produces 'application/json'
+
+ response '200', 'split returned' do
+ schema '$ref' => '#/components/schemas/Split'
+ before { transaction.entry.split!([ { name: 'A', amount: 60 }, { name: 'B', amount: 40 } ]) }
+ run_test!
+ end
+
+ response '404', 'transaction is not split' do
+ run_test!
+ end
+ end
+
+ patch 'Replace a transaction split' do
+ tags 'Transactions'
+ security [ { apiKeyAuth: [] } ]
+ description 'Replaces the children of an existing split. The previous children are ' \
+ 'destroyed, so anything set on them afterwards is not carried over.'
+ consumes 'application/json'
+ produces 'application/json'
+ parameter name: :split, in: :body, schema: { '$ref' => '#/components/schemas/SplitRequest' }
+
+ let(:split) { split_payload }
+
+ response '200', 'split replaced' do
+ schema '$ref' => '#/components/schemas/Split'
+ before { transaction.entry.split!([ { name: 'A', amount: 70 }, { name: 'B', amount: 30 } ]) }
+ run_test!
+ end
+ end
+
+ delete 'Remove a transaction split' do
+ tags 'Transactions'
+ security [ { apiKeyAuth: [] } ]
+ description 'Removes the children and restores the parent transaction.'
+
+ response '204', 'split removed' do
+ before { transaction.entry.split!([ { name: 'A', amount: 60 }, { name: 'B', amount: 40 } ]) }
+ run_test!
+ end
+
+ response '404', 'transaction is not split' do
+ run_test!
+ end
+ end
+ end
+end
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index d9c2ff723b..67fbe52643 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -53,6 +53,58 @@ RSpec.configure do |config|
}
},
schemas: {
+ SplitRequest: {
+ type: :object,
+ required: %w[split],
+ properties: {
+ split: {
+ type: :object,
+ required: %w[splits],
+ properties: {
+ splits: {
+ type: :array,
+ minItems: 1,
+ description: 'Child transactions. Amounts must sum exactly to the parent amount.',
+ items: {
+ type: :object,
+ required: %w[amount],
+ properties: {
+ name: { type: :string, nullable: true, description: 'Defaults to the parent name when omitted' },
+ amount: { type: :string, description: 'Same sign convention as the transaction amount' },
+ category_id: { type: :string, nullable: true },
+ excluded: { type: :boolean, nullable: true }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ Split: {
+ type: :object,
+ required: %w[transaction_id amount amount_decimal amount_cents currency children],
+ properties: {
+ transaction_id: { type: :string },
+ amount: { type: :string, description: 'Formatted parent amount, rounded for display' },
+ amount_decimal: { type: :string, description: 'Exact stored amount; children must sum to this' },
+ amount_cents: { type: :integer, description: 'Absolute amount in minor units' },
+ currency: { type: :string },
+ children: { type: :array, items: { '$ref' => '#/components/schemas/SplitChild' } }
+ }
+ },
+ SplitChild: {
+ allOf: [
+ { '$ref' => '#/components/schemas/Transaction' },
+ {
+ type: :object,
+ required: %w[amount_decimal excluded],
+ properties: {
+ amount_decimal: { type: :string, description: 'Exact stored amount; send this back when replacing the split' },
+ excluded: { type: :boolean, description: 'Whether this child is excluded from totals' }
+ }
+ }
+ ]
+ },
Pagination: {
type: :object,
required: %w[page per_page total_count total_pages],
diff --git a/test/controllers/api/v1/splits_controller_test.rb b/test/controllers/api/v1/splits_controller_test.rb
new file mode 100644
index 0000000000..98b795a2b3
--- /dev/null
+++ b/test/controllers/api/v1/splits_controller_test.rb
@@ -0,0 +1,364 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Api::V1::SplitsControllerTest < ActionDispatch::IntegrationTest
+ include EntriesTestHelper
+
+ setup do
+ @user = users(:family_admin)
+ @family = @user.family
+ @account = @family.accounts.first
+ @entry = create_transaction(account: @account, amount: 100, name: "Splittable")
+ @transaction = @entry.entryable
+
+ @user.api_keys.active.destroy_all
+
+ @api_key = ApiKey.create!(
+ user: @user,
+ name: "Test Read-Write Key",
+ scopes: [ "read_write" ],
+ display_key: "test_rw_#{SecureRandom.hex(8)}"
+ )
+
+ @read_only_api_key = ApiKey.create!(
+ user: @user,
+ name: "Test Read-Only Key",
+ scopes: [ "read" ],
+ display_key: "test_ro_#{SecureRandom.hex(8)}",
+ source: "mobile"
+ )
+
+ Redis.new.del("api_rate_limit:#{@api_key.id}")
+ Redis.new.del("api_rate_limit:#{@read_only_api_key.id}")
+ end
+
+ def halves
+ { split: { splits: [
+ { name: "First half", amount: (@entry.amount / 2).to_s },
+ { name: "Second half", amount: (@entry.amount / 2).to_s }
+ ] } }
+ end
+
+ # CREATE
+
+ test "splits a transaction into children that sum to it" do
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+ assert_response :created
+
+ body = JSON.parse(response.body)
+ assert_equal @transaction.id, body["transaction_id"]
+ assert_equal 2, body["children"].length
+
+ @entry.reload
+ assert @entry.split_parent?
+ assert @entry.excluded?, "parent is excluded once split"
+ assert_equal @entry.amount, @entry.child_entries.sum(:amount)
+ end
+
+ test "assigns categories to children" do
+ category = @family.categories.first
+ params = { split: { splits: [
+ { name: "Categorised", amount: (@entry.amount / 2).to_s, category_id: category.id },
+ { name: "Plain", amount: (@entry.amount / 2).to_s }
+ ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :created
+
+ categories = @entry.reload.child_entries.map { |c| c.entryable.category_id }
+ assert_includes categories, category.id
+ assert_includes categories, nil
+ end
+
+ test "returns 422 when the children do not sum to the parent" do
+ params = { split: { splits: [ { name: "Too small", amount: "1.00" } ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+ assert_equal "validation_failed", JSON.parse(response.body)["error"]
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "returns 422 when splits is empty" do
+ post api_v1_transaction_split_url(@transaction), params: { split: { splits: [] } },
+ headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+ end
+
+ test "returns 422 when an amount is not numeric" do
+ params = { split: { splits: [ { name: "Bad", amount: "not-a-number" } ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+ end
+
+ test "returns 422 when the transaction is already split" do
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+ assert_response :created
+
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+ end
+
+ # SHOW
+
+ test "shows the children of a split transaction" do
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+
+ get api_v1_transaction_split_url(@transaction), headers: api_headers(@api_key)
+ assert_response :success
+ assert_equal 2, JSON.parse(response.body)["children"].length
+ end
+
+ test "returns 404 showing a transaction that is not split" do
+ get api_v1_transaction_split_url(@transaction), headers: api_headers(@api_key)
+ assert_response :not_found
+ end
+
+ test "resolves a child id to its parent" do
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+ child = @entry.reload.child_entries.first
+
+ get api_v1_transaction_split_url(child.entryable), headers: api_headers(@api_key)
+ assert_response :success
+ assert_equal @transaction.id, JSON.parse(response.body)["transaction_id"]
+ end
+
+ # UPDATE
+
+ test "replaces the children" do
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+
+ thirds = { split: { splits: 3.times.map { |i| { name: "Part #{i}", amount: (@entry.amount / 3).round(2).to_s } } } }
+ thirds[:split][:splits][0][:amount] = (@entry.amount - (@entry.amount / 3).round(2) * 2).to_s
+
+ patch api_v1_transaction_split_url(@transaction), params: thirds, headers: api_headers(@api_key), as: :json
+ assert_response :success
+ assert_equal 3, @entry.reload.child_entries.count
+ assert_equal @entry.amount, @entry.child_entries.sum(:amount)
+ end
+
+ test "returns 404 updating a transaction that is not split" do
+ patch api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+ assert_response :not_found
+ end
+
+ # DESTROY
+
+ test "unsplits a transaction" do
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+
+ delete api_v1_transaction_split_url(@transaction), headers: api_headers(@api_key)
+ assert_response :no_content
+
+ @entry.reload
+ assert_not @entry.split_parent?
+ assert_not @entry.excluded?, "parent is restored when unsplit"
+ end
+
+ test "returns 404 unsplitting a transaction that is not split" do
+ delete api_v1_transaction_split_url(@transaction), headers: api_headers(@api_key)
+ assert_response :not_found
+ end
+
+ # AUTH
+
+ test "read-only key cannot split" do
+ post api_v1_transaction_split_url(@transaction), params: halves,
+ headers: api_headers(@read_only_api_key), as: :json
+ assert_response :forbidden
+ end
+
+ test "read-only key cannot unsplit" do
+ delete api_v1_transaction_split_url(@transaction), headers: api_headers(@read_only_api_key)
+ assert_response :forbidden
+ end
+
+ test "read-only key can read a split" do
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+
+ get api_v1_transaction_split_url(@transaction), headers: api_headers(@read_only_api_key)
+ assert_response :success
+ end
+
+ # Review findings from PR #4117
+
+ test "a read-only share cannot split, even with a read_write key" do
+ other = User.create!(family: @family, email: "viewer-#{SecureRandom.hex(4)}@example.com",
+ password: "password123", password_confirmation: "password123", role: "member")
+ @account.update!(owner: @user)
+ AccountShare.create!(account: @account, user: other, permission: "read_only")
+ other.api_keys.active.destroy_all
+ key = ApiKey.create!(user: other, name: "Viewer RW", scopes: [ "read_write" ],
+ display_key: "test_v_#{SecureRandom.hex(8)}")
+ Redis.new.del("api_rate_limit:#{key.id}")
+
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(key), as: :json
+ assert_response :forbidden
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "rejects a category belonging to another family" do
+ other_family = Family.create!(name: "Other", currency: "USD", locale: "en", date_format: "%m-%d-%Y")
+ foreign = other_family.categories.create!(name: "Foreign", color: "#000000", lucide_icon: "circle")
+ params = { split: { splits: [
+ { name: "A", amount: (@entry.amount / 2).to_s, category_id: foreign.id },
+ { name: "B", amount: (@entry.amount / 2).to_s }
+ ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "rounds amounts to the stored scale so children sum exactly" do
+ params = { split: { splits: [
+ { name: "A", amount: "33.33335" },
+ { name: "B", amount: "66.66660" }
+ ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :created
+ assert_equal [ BigDecimal("33.3334"), BigDecimal("66.6666") ],
+ @entry.reload.child_entries.order(:name).map(&:amount)
+ end
+
+ test "rejects amounts that only sum to the parent before rounding" do
+ params = { split: { splits: [
+ { name: "A", amount: "33.33335" },
+ { name: "B", amount: "66.66665" }
+ ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "returns 422 when a split element is not an object" do
+ [ [ true ], [ nil ], [ "x" ], [ 1 ], [ [ { amount: "100" } ] ] ].each do |splits|
+ post api_v1_transaction_split_url(@transaction), params: { split: { splits: splits } },
+ headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity, "splits: #{splits.inspect}"
+ assert_equal "validation_failed", JSON.parse(response.body)["error"]
+ end
+ assert_not @entry.reload.split_parent?
+ end
+
+ test "a split read back and re-sent keeps each child's exclusion and exact amount" do
+ params = { split: { splits: [
+ { name: "Excluded", amount: "50.0049", excluded: true },
+ { name: "Counted", amount: "49.9951" }
+ ] } }
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :created
+
+ get api_v1_transaction_split_url(@transaction), headers: api_headers(@api_key)
+ children = JSON.parse(response.body)["children"]
+ assert_equal [ [ "Excluded", "50.0049", true ], [ "Counted", "49.9951", false ] ],
+ children.map { |c| c.values_at("name", "amount_decimal", "excluded") }
+
+ resent = children.map { |c| { name: c["name"] == "Counted" ? "Renamed" : c["name"], amount: c["amount_decimal"], excluded: c["excluded"] } }
+ patch api_v1_transaction_split_url(@transaction), params: { split: { splits: resent } },
+ headers: api_headers(@api_key), as: :json
+ assert_response :success
+
+ assert_equal [ [ "Excluded", BigDecimal("50.0049"), true ], [ "Renamed", BigDecimal("49.9951"), false ] ],
+ @entry.reload.child_entries.order(:name).map { |c| [ c.name, c.amount, c.excluded ] }
+ end
+
+ test "returns 422 for amounts too large to store, even when they sum to the parent" do
+ # The second is under the limit as sent and only reaches it once rounded.
+ [ "1#{"0" * 20}", "999999999999999.99995" ].each do |huge|
+ params = { split: { splits: [
+ { name: "A", amount: huge },
+ { name: "B", amount: "-#{huge}" },
+ { name: "C", 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, "amount: #{huge}"
+ assert_not @entry.reload.split_parent?
+ end
+ end
+
+ test "accepts the largest amount the column can store" do
+ max = "999999999999999.9999"
+ params = { split: { splits: [
+ { name: "A", amount: max },
+ { name: "B", amount: "-#{max}" },
+ { name: "C", amount: @entry.amount.to_s }
+ ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :created
+ end
+
+ test "a rejected replacement leaves the existing split untouched" do
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+ assert_response :created
+ before = @entry.reload.child_entries.order(:id).pluck(:id, :name, :amount)
+
+ patch api_v1_transaction_split_url(@transaction), params: { split: { splits: [ { name: "Too small", amount: "1.00" } ] } },
+ headers: api_headers(@api_key), as: :json
+ assert_response :unprocessable_entity
+
+ assert_equal before, @entry.reload.child_entries.order(:id).pluck(:id, :name, :amount)
+ assert @entry.excluded?, "parent stays excluded while still split"
+ end
+
+ test "showing a split does not query per child" do
+ splits = 5.times.map { |i| { name: "Part #{i}", amount: (@entry.amount / 5).to_s } }
+ post api_v1_transaction_split_url(@transaction), params: { split: { splits: splits } },
+ headers: api_headers(@api_key), as: :json
+ assert_response :created
+
+ selects = ->(&block) do
+ count = 0
+ counter = ->(*, payload) { count += 1 if payload[:sql].start_with?("SELECT") && payload[:name] != "SCHEMA" }
+ ActiveSupport::Notifications.subscribed(counter, "sql.active_record", &block)
+ count
+ end
+
+ five = selects.call { get api_v1_transaction_split_url(@transaction), headers: api_headers(@api_key) }
+ assert_response :success
+
+ patch api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+ two = selects.call { get api_v1_transaction_split_url(@transaction), headers: api_headers(@api_key) }
+
+ assert_equal two, five, "query count must not grow with the number of children"
+ end
+
+ test "defaults a missing child name to the parent name" do
+ params = { split: { splits: [
+ { amount: (@entry.amount / 2).to_s },
+ { amount: (@entry.amount / 2).to_s }
+ ] } }
+
+ post api_v1_transaction_split_url(@transaction), params: params, headers: api_headers(@api_key), as: :json
+ assert_response :created
+ assert_equal [ @entry.name, @entry.name ], @entry.reload.child_entries.map(&:name)
+ end
+
+ test "exposes the exact amount a client needs to replace a split" do
+ post api_v1_transaction_split_url(@transaction), params: halves, headers: api_headers(@api_key), as: :json
+ body = JSON.parse(response.body)
+ assert_equal @entry.amount.to_s, body["amount_decimal"]
+ assert body["amount_cents"].is_a?(Integer)
+ end
+
+ test "returns 401 without an API key" do
+ get api_v1_transaction_split_url(@transaction)
+ assert_response :unauthorized
+ end
+
+ test "returns 404 for an unknown transaction" do
+ get api_v1_transaction_split_url(SecureRandom.uuid), headers: api_headers(@api_key)
+ assert_response :not_found
+ end
+
+ test "returns 404 for a malformed transaction id" do
+ get api_v1_transaction_split_url("not-a-uuid"), headers: api_headers(@api_key)
+ assert_response :not_found
+ end
+end