Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
15.3 KB
Raw Blame
# frozen_string_literal: true

require 'swagger_helper'

RSpec.describe 'API V1 Transactions', 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(:read_only_transaction) do
    owner = family.users.create!(
      email: '[email protected]',
      password: 'password123',
      password_confirmation: 'password123'
    )
    shared_account = Account.create!(
      family: family,
      owner: owner,
      name: 'Shared Checking',
      balance: 1000,
      currency: 'USD',
      accountable: Depository.new
    )
    shared_account.account_shares.create!(user: user, permission: 'read_only', include_in_finances: true)
    shared_account.entries.create!(
      name: 'Shared transaction', amount: 10, currency: 'USD', date: Date.current, entryable: Transaction.new
    ).transaction
  end

  let(:account) do
    Account.create!(
      family: family,
      owner: user,
      name: 'Checking Account',
      balance: 1000,
      currency: 'USD',
      accountable: Depository.create!
    )
  end

  let(:category) do
    family.categories.create!(
      name: 'Groceries',
      color: '#4CAF50',
      lucide_icon: 'shopping-cart'
    )
  end

  let(:merchant) do
    family.merchants.create!(name: 'Whole Foods')
  end

  let(:tag) do
    family.tags.create!(name: 'Essential', color: '#2196F3')
  end

  let!(:transaction) do
    entry = account.entries.create!(
      name: 'Grocery shopping',
      date: Date.current,
      amount: 75.50,
      currency: 'USD',
      entryable: Transaction.new(
        category: category,
        merchant: merchant
      )
    )
    entry.transaction.tags << tag
    entry.transaction
  end

  # An imported EUR dividend in the USD account, so the documented
  # investment_activity_label, provider_type, security_id, exchange_rate and
  # amount_currency fields are populated.
  let!(:dividend_transaction) do
    security = Security.create!(ticker: 'VTI', name: 'Vanguard Total Stock Market ETF', country_code: 'US')
    entry = account.entries.create!(
      name: 'Dividend VTI',
      date: Date.current - 2.days,
      amount: -12.40,
      currency: 'EUR',
      source: 'ibkr',
      external_id: 'ibkr_cash_docs_1',
      entryable: Transaction.new(
        investment_activity_label: 'Dividend',
        extra: {
          'exchange_rate' => 1.08,
          'security_id' => security.id,
          'ibkr' => { 'type' => 'Dividends' }
        }
      )
    )
    entry.transaction
  end

  let!(:another_transaction) do
    entry = account.entries.create!(
      name: 'Coffee',
      date: Date.current - 1.day,
      amount: 5.00,
      currency: 'USD',
      entryable: Transaction.new
    )
    entry.transaction
  end

  path '/api/v1/transactions' do
    get 'List transactions' do
      tags 'Transactions'
      security [ { apiKeyAuth: [] } ]
      description 'Returns global ledger history for accessible accounts, including disabled accounts but excluding accounts pending deletion.'
      produces 'application/json'
      parameter name: :page, in: :query, type: :integer, required: false,
                description: 'Page number (default: 1)'
      parameter name: :per_page, in: :query, type: :integer, required: false,
                description: 'Items per page (default: 25, max: 100)'
      parameter name: :account_id, in: :query, type: :string, required: false,
                description: 'Filter by account ID'
      parameter name: :category_id, in: :query, type: :string, required: false,
                description: 'Filter by category ID'
      parameter name: :merchant_id, in: :query, type: :string, required: false,
                description: 'Filter by merchant ID'
      parameter name: :start_date, in: :query, required: false,
                description: 'Filter transactions from this date',
                schema: { type: :string, format: :date }
      parameter name: :end_date, in: :query, required: false,
                description: 'Filter transactions until this date',
                schema: { type: :string, format: :date }
      parameter name: :min_amount, in: :query, type: :number, required: false,
                description: 'Filter by minimum amount'
      parameter name: :max_amount, in: :query, type: :number, required: false,
                description: 'Filter by maximum amount'
      parameter name: :type, in: :query, required: false,
                description: 'Filter by transaction type',
                schema: { type: :string, enum: %w[income expense] }
      parameter name: :search, in: :query, type: :string, required: false,
                description: 'Search by name, notes, or merchant name'
      parameter name: :account_ids, in: :query, required: false,
                description: 'Filter by multiple account IDs',
                schema: { type: :array, items: { type: :string } }
      parameter name: :category_ids, in: :query, required: false,
                description: 'Filter by multiple category IDs',
                schema: { type: :array, items: { type: :string } }
      parameter name: :merchant_ids, in: :query, required: false,
                description: 'Filter by multiple merchant IDs',
                schema: { type: :array, items: { type: :string } }
      parameter name: :tag_ids, in: :query, required: false,
                description: 'Filter by tag IDs',
                schema: { type: :array, items: { type: :string } }

      response '200', 'transactions listed' do
        schema '$ref' => '#/components/schemas/TransactionCollection'

        run_test!
      end

      response '200', 'transactions filtered by account' do
        schema '$ref' => '#/components/schemas/TransactionCollection'

        let(:account_id) { account.id }

        run_test!
      end

      response '200', 'transactions filtered by date range' do
        schema '$ref' => '#/components/schemas/TransactionCollection'

        let(:start_date) { (Date.current - 7.days).to_s }
        let(:end_date) { Date.current.to_s }

        run_test!
      end
    end

    post 'Create transaction' do
      tags 'Transactions'
      security [ { apiKeyAuth: [] } ]
      consumes 'application/json'
      produces 'application/json'
      parameter name: :body, in: :body, required: true, schema: {
        type: :object,
        properties: {
          transaction: {
            type: :object,
            properties: {
              account_id: { type: :string, format: :uuid, description: 'Account ID (required)' },
              date: { type: :string, format: :date, description: 'Transaction date' },
              amount: { type: :number, description: 'Transaction amount' },
              name: { type: :string, description: 'Transaction name/description' },
              description: { type: :string, description: 'Alternative to name field' },
              notes: { type: :string, description: 'Additional notes' },
              currency: { type: :string, description: 'Currency code (defaults to family currency)' },
              category_id: { type: :string, format: :uuid, description: 'Category ID' },
              merchant_id: { type: :string, format: :uuid, description: 'Merchant ID' },
              nature: { type: :string, enum: %w[income expense inflow outflow], description: 'Transaction nature (determines sign)' },
              external_id: { type: :string, description: 'Optional external idempotency key scoped to account and source' },
              source: { type: :string, description: 'Optional source namespace for external_id. Requires external_id and defaults to api when external_id is provided' },
              user_modified: { type: :boolean, description: 'Whether provider syncs should preserve user-supplied transaction changes' },
              tag_ids: { type: :array, items: { type: :string, format: :uuid }, description: 'Array of tag IDs' }
            },
            required: %w[account_id date amount name]
          }
        },
        required: %w[transaction]
      }

      let(:body) do
        {
          transaction: {
            account_id: account.id,
            date: Date.current.to_s,
            amount: 50.00,
            name: 'Test purchase',
            nature: 'expense',
            category_id: category.id,
            merchant_id: merchant.id
          }
        }
      end

      response '201', 'transaction created' do
        schema '$ref' => '#/components/schemas/Transaction'

        run_test!
      end

      response '200', 'transaction already exists for external idempotency key' do
        schema '$ref' => '#/components/schemas/Transaction'

        let(:body) do
          {
            transaction: {
              account_id: account.id,
              date: Date.current.to_s,
              amount: 50.00,
              name: 'Test purchase',
              nature: 'expense',
              external_id: 'docs-import-transaction-1',
              source: 'external_import'
            }
          }
        end

        before do
          account.entries.create!(
            name: 'Test purchase',
            date: Date.current,
            amount: 50.00,
            currency: 'USD',
            external_id: 'docs-import-transaction-1',
            source: 'external_import',
            entryable: Transaction.new
          )
        end

        run_test!
      end

      response '422', 'validation error - missing account_id' do
        schema '$ref' => '#/components/schemas/ErrorResponse'

        let(:body) do
          {
            transaction: {
              date: Date.current.to_s,
              amount: 50.00,
              name: 'Test purchase'
            }
          }
        end

        run_test!
      end

      response '422', 'validation error - missing required fields, malformed tag_ids, or a tag, category or merchant id the family cannot use' do
        schema '$ref' => '#/components/schemas/ErrorResponse'

        let(:body) do
          {
            transaction: {
              account_id: account.id
            }
          }
        end

        run_test!
      end
    end
  end

  path '/api/v1/transactions/{id}' do
    parameter name: :id, in: :path, schema: { type: :string, format: :uuid }, required: true, description: 'Transaction ID'

    get 'Retrieve a transaction' do
      tags 'Transactions'
      security [ { apiKeyAuth: [] } ]
      produces 'application/json'

      let(:id) { transaction.id }

      response '200', 'transaction retrieved' do
        schema '$ref' => '#/components/schemas/Transaction'

        # The dividend, so the populated exchange_rate and amount_currency are
        # checked against the schema too.
        let(:id) { dividend_transaction.id }

        run_test! do |response|
          data = JSON.parse(response.body)
          expect(data['exchange_rate']).to eq(1.08)
          expect(data['amount_currency']).to eq('EUR')
        end
      end

      response '404', 'transaction not found' do
        schema '$ref' => '#/components/schemas/ErrorResponse'

        let(:id) { SecureRandom.uuid }

        run_test!
      end
    end

    patch 'Update a transaction' do
      tags 'Transactions'
      security [ { apiKeyAuth: [] } ]
      consumes 'application/json'
      produces 'application/json'

      let(:id) { transaction.id }

      parameter name: :body, in: :body, required: true, schema: {
        type: :object,
        properties: {
          transaction: {
            type: :object,
            properties: {
              date: { type: :string, format: :date },
              amount: { type: :number },
              name: { type: :string },
              description: { type: :string, description: 'Alternative to name field' },
              notes: { type: :string },
              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], description: 'Sign of the amount. Without amount, applies to the stored amount.' },
              tag_ids: {
                type: :array,
                items: { type: :string, format: :uuid },
                description: 'Array of tag IDs to assign. Omit to preserve existing tags; use [] to clear all tags.'
              },
              user_modified: { type: :boolean, description: 'Whether provider syncs should preserve user-supplied transaction changes' }
            }
          }
        }
      }

      let(:body) do
        {
          transaction: {
            name: 'Updated grocery shopping',
            notes: 'Weekly groceries'
          }
        }
      end

      response '200', 'transaction updated' do
        schema '$ref' => '#/components/schemas/Transaction'

        run_test!
      end

      response '403', 'account is shared with you without permission to change this transaction' do
        schema '$ref' => '#/components/schemas/ErrorResponse'

        let(:id) { read_only_transaction.id }

        run_test!
      end

      response '404', 'transaction not found' do
        schema '$ref' => '#/components/schemas/ErrorResponse'

        let(:id) { SecureRandom.uuid }

        run_test!
      end

      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 ] } } }

        run_test!
      end
    end

    delete 'Delete a transaction' do
      tags 'Transactions'
      security [ { apiKeyAuth: [] } ]
      produces 'application/json'

      let(:id) { another_transaction.id }

      response '200', 'transaction deleted' do
        schema '$ref' => '#/components/schemas/DeleteResponse'

        run_test!
      end

      response '403', 'account is shared with you without full control' do
        schema '$ref' => '#/components/schemas/ErrorResponse'

        let(:id) { read_only_transaction.id }

        run_test!
      end

      response '404', 'transaction not found' do
        schema '$ref' => '#/components/schemas/ErrorResponse'

        let(:id) { SecureRandom.uuid }

        run_test!
      end

      response '422', 'the transaction is split and a part is linked as a transfer; remove that transfer first' do
        schema '$ref' => '#/components/schemas/ErrorResponse'

        before do
          part = another_transaction.entry.split!([ { name: 'Principal', amount: 3 }, { name: 'Interest', amount: 2 } ]).first
          loan_account = Account.create!(family: family, name: 'Mortgage', balance: 100_000, currency: 'USD', accountable: Loan.create!)
          loan_entry = loan_account.entries.create!(name: 'Payment', date: part.date, amount: -3, currency: 'USD', entryable: Transaction.new)
          Transfer.create!(inflow_transaction: loan_entry.transaction, outflow_transaction: part.transaction, status: 'confirmed', amount: 3)
        end

        run_test!
      end
    end
  end
end