Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add Account Statements to the API (#4826)

Taaqif Peck (Tye)7f8d2f458b57
diff --git a/app/controllers/api/v1/account_statements_controller.rb b/app/controllers/api/v1/account_statements_controller.rb
new file mode 100644
index 0000000000..b1c6ddc80d
--- /dev/null
+++ b/app/controllers/api/v1/account_statements_controller.rb
@@ -0,0 +1,158 @@
+# frozen_string_literal: true
+
+class Api::V1::AccountStatementsController < Api::V1::BaseController
+ include Pagy::Backend
+
+ before_action :ensure_read_scope, only: [ :index, :show ]
+ before_action :ensure_write_scope, only: [ :create ]
+ before_action :ensure_statement_manager
+ before_action :set_statement, only: [ :show ]
+
+ helper_method :accessible_account_ids
+
+ def index
+ # Mirrors AccountStatement#viewable_by? for a statement manager in SQL, so
+ # pages are never underfilled: unlinked statements are visible, linked ones
+ # follow the account.
+ statements = family.account_statements
+ .where(account_id: nil)
+ .or(family.account_statements.where(account_id: current_resource_owner.accessible_accounts.select(:id)))
+ .includes(:account, :suggested_account)
+ .ordered
+
+ statements = apply_filters(statements)
+ @per_page = safe_per_page_param
+ @pagy, @statements = pagy(statements, page: safe_page_param, limit: @per_page)
+
+ render :index
+ end
+
+ def show
+ render :show
+ end
+
+ def create
+ file = params[:file]
+ unless file.respond_to?(:read) && file.respond_to?(:original_filename)
+ render_validation_error("file is required (multipart/form-data)")
+ return
+ end
+
+ account = target_account
+ return if performed?
+
+ prepared_upload = AccountStatement.prepare_upload!(file)
+ @statement = AccountStatement.create_from_prepared_upload!(
+ family: family,
+ account: account,
+ prepared_upload: prepared_upload
+ )
+
+ render :show, status: :created
+ rescue AccountStatement::DuplicateUploadError => e
+ render_duplicate(e.statement)
+ rescue AccountStatement::InvalidUploadError
+ render_validation_error(
+ "file must be a readable #{AccountStatement::ACCEPTED_FILE_EXTENSIONS.join(", ")} document whose contents match its extension, " \
+ "at most #{AccountStatement::MAX_FILE_SIZE / 1.megabyte} MB"
+ )
+ rescue ActiveRecord::RecordInvalid => e
+ render json: {
+ error: "validation_failed",
+ message: "Statement could not be stored",
+ errors: e.record.errors.full_messages
+ }, status: :unprocessable_entity
+ end
+
+ private
+
+ def family
+ current_resource_owner.family
+ end
+
+ # Loaded once per request so rendering a page of statements checks each
+ # suggested account without a query per row.
+ def accessible_account_ids
+ @accessible_account_ids ||= current_resource_owner.accessible_accounts.pluck(:id).to_set
+ end
+
+ def set_statement
+ raise ActiveRecord::RecordNotFound unless valid_uuid?(params[:id])
+
+ @statement = family.account_statements
+ .includes(:account, :suggested_account)
+ .find(params[:id])
+
+ raise ActiveRecord::RecordNotFound unless @statement.viewable_by?(current_resource_owner)
+ end
+
+ # Uploading links the statement straight away, so it needs the same write
+ # access to the account as the web upload form.
+ def target_account
+ account_id = params[:account_id].presence
+ return nil if account_id.blank?
+
+ account = family.accounts.writable_by(current_resource_owner).find_by(id: account_id) if valid_uuid?(account_id)
+ return account if account
+
+ render json: {
+ error: "not_found",
+ message: "No account you can write to matched account_id. Omit account_id to upload the statement unlinked."
+ }, status: :not_found
+ nil
+ end
+
+ # The existing copy may be filed against an account this user cannot see,
+ # so its details are only returned when it is visible to them.
+ def render_duplicate(statement)
+ if statement.viewable_by?(current_resource_owner)
+ @statement = statement
+ @duplicate = true
+ render :show, status: :ok
+ else
+ render json: {
+ error: "duplicate",
+ message: "This file is already in the Statement Vault"
+ }, status: :conflict
+ end
+ end
+
+ def apply_filters(scope)
+ if params[:account_id].present?
+ raise InvalidFilterError, "account_id must be a valid UUID" unless valid_uuid?(params[:account_id])
+
+ scope = scope.where(account_id: params[:account_id])
+ end
+
+ if params[:review_status].present?
+ unless AccountStatement.review_statuses.key?(params[:review_status].to_s)
+ raise InvalidFilterError, "review_status must be one of: #{AccountStatement.review_statuses.keys.join(", ")}"
+ end
+
+ scope = scope.where(review_status: params[:review_status].to_s)
+ end
+
+ # The column only holds lowercase hex.
+ scope = scope.where(content_sha256: params[:content_sha256].to_s.strip.downcase) if params[:content_sha256].present?
+ scope = scope.where("period_end_on >= ?", parse_date_param(:start_date)) if params[:start_date].present?
+ scope = scope.where("period_start_on <= ?", parse_date_param(:end_date)) if params[:end_date].present?
+ scope
+ end
+
+ def ensure_statement_manager
+ return if AccountStatement.statement_manager?(current_resource_owner)
+
+ render json: {
+ error: "forbidden",
+ message: "The Statement Vault requires an admin or member role"
+ }, status: :forbidden
+ end
+
+ def ensure_read_scope
+ authorize_scope!(:read)
+ end
+
+ def ensure_write_scope
+ authorize_scope!(:write)
+ end
+end
diff --git a/app/views/api/v1/account_statements/_account_statement.json.jbuilder b/app/views/api/v1/account_statements/_account_statement.json.jbuilder
new file mode 100644
index 0000000000..effa309146
--- /dev/null
+++ b/app/views/api/v1/account_statements/_account_statement.json.jbuilder
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+json.id account_statement.id
+json.filename account_statement.filename
+json.content_type account_statement.content_type
+json.byte_size account_statement.byte_size
+json.content_sha256 account_statement.content_sha256
+json.review_status account_statement.review_status
+json.period_start_on account_statement.period_start_on&.iso8601
+json.period_end_on account_statement.period_end_on&.iso8601
+json.currency account_statement.statement_currency
+json.opening_balance account_statement.opening_balance&.to_s
+json.closing_balance account_statement.closing_balance&.to_s
+json.institution_name_hint account_statement.institution_name_hint
+json.account_last4_hint account_statement.account_last4_hint
+
+if account_statement.account
+ json.account do
+ json.id account_statement.account.id
+ json.name account_statement.account.name
+ json.currency account_statement.account.currency
+ end
+else
+ json.account nil
+end
+
+# Only reveal a suggestion the caller could see on its own.
+suggested = account_statement.suggested_account
+if suggested && accessible_account_ids.include?(suggested.id)
+ json.suggested_account do
+ json.id suggested.id
+ json.name suggested.name
+ json.currency suggested.currency
+ end
+ json.match_confidence account_statement.match_confidence&.to_f
+else
+ json.suggested_account nil
+ json.match_confidence nil
+end
+
+json.created_at account_statement.created_at.iso8601
+json.updated_at account_statement.updated_at.iso8601
diff --git a/app/views/api/v1/account_statements/index.json.jbuilder b/app/views/api/v1/account_statements/index.json.jbuilder
new file mode 100644
index 0000000000..be1cc793c4
--- /dev/null
+++ b/app/views/api/v1/account_statements/index.json.jbuilder
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+
+json.data do
+ json.array! @statements, partial: "api/v1/account_statements/account_statement", as: :account_statement
+end
+
+json.meta do
+ json.page @pagy.page
+ json.per_page @per_page
+ json.total_count @pagy.count
+ json.total_pages @pagy.pages
+end
diff --git a/app/views/api/v1/account_statements/show.json.jbuilder b/app/views/api/v1/account_statements/show.json.jbuilder
new file mode 100644
index 0000000000..98d2a47cdb
--- /dev/null
+++ b/app/views/api/v1/account_statements/show.json.jbuilder
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+json.data do
+ json.partial! "api/v1/account_statements/account_statement", account_statement: @statement
+end
+
+json.meta do
+ json.duplicate !!@duplicate
+end
diff --git a/config/routes.rb b/config/routes.rb
index 559bd2b7b1..eee35a2ecf 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -827,6 +827,7 @@ Rails.application.routes.draw do
# Production API endpoints
resources :accounts, only: [ :index, :show ]
+ resources :account_statements, only: [ :index, :show, :create ]
resources :balances, only: [ :index, :show ]
resources :budgets, only: [ :index, :show ]
resources :budget_categories, only: [ :index, :show ]
diff --git a/docs/api/account_statements.md b/docs/api/account_statements.md
new file mode 100644
index 0000000000..20461c0b9d
--- /dev/null
+++ b/docs/api/account_statements.md
@@ -0,0 +1,99 @@
+# Account Statements API
+
+The Account Statements API lets external applications file statement documents (PDF, CSV or XLSX) in the Statement Vault and look up what is already there. It is the API counterpart of the vault's upload form and of the `upload_account_statement` / `list_account_statements` assistant tools, and it applies the same rules.
+
+Statements are archived only: uploading one never imports transactions. Use the [Imports API](imports.md) for that.
+
+## Generated OpenAPI specification
+
+- The source of truth for the documentation lives in [`spec/requests/api/v1/account_statements_spec.rb`](../../spec/requests/api/v1/account_statements_spec.rb).
+- Regenerate the OpenAPI document with:
+
+ ```sh
+ RAILS_ENV=test bundle exec rake rswag:specs:swaggerize
+ ```
+
+## Authentication requirements
+
+| Operation | Scope Required |
+| --- | --- |
+| List/View statements | `read` |
+| Upload a statement | `write` |
+
+The Statement Vault is available to admins and members; guests get `403`.
+
+## Available endpoints
+
+| Endpoint | Scope | Description |
+| --- | --- | --- |
+| `GET /api/v1/account_statements` | `read` | List statements the caller can see, newest first. |
+| `GET /api/v1/account_statements/{id}` | `read` | Retrieve a single statement. |
+| `POST /api/v1/account_statements` | `write` | Upload a statement (`multipart/form-data`). |
+
+### Visibility
+
+Unlinked statements (the vault inbox) are visible to every admin and member. A statement linked to an account is visible only to people the account is shared with. Statements the caller cannot see are left out of lists and return `404`.
+
+### Uploading
+
+```sh
+curl -X POST https://sure.example.com/api/v1/account_statements \
+ -H "X-Api-Key: $SURE_API_KEY" \
+ -F "account_id=8f0d5c6e-..."
+```
+
+- `file` (required): `.pdf`, `.csv` or `.xlsx`, at most 25 MB. The content must match the extension.
+- `account_id` (optional): links the statement to this account. It needs write access to the account (owner or full control), as in the app; otherwise the response is `404`. Without it, the statement goes to the vault inbox and the vault suggests a matching account, which someone confirms in the app.
+
+Responses:
+
+| Status | Meaning |
+| --- | --- |
+| `201` | Stored. `meta.duplicate` is `false`. |
+| `200` | The same file (by SHA-256) is already in the vault. The existing statement is returned with `meta.duplicate: true`; nothing is created. |
+| `409` | The same file is already in the vault, linked to an account the caller cannot see. No details are returned. |
+| `422` | Missing file, unsupported type, or a file that fails validation. |
+
+Uploading the same file again is safe, so clients can retry or re-send without checking first. To check without uploading, list with `content_sha256`.
+
+### Listing filters
+
+| Parameter | Description |
+| --- | --- |
+| `account_id` | Statements linked to this account. |
+| `review_status` | `unmatched`, `linked` or `rejected`. |
+| `content_sha256` | The statement for a file, by its SHA-256 (hex). |
+| `start_date` | Statements whose period ends on or after this date (`YYYY-MM-DD`). |
+| `end_date` | Statements whose period starts on or before this date (`YYYY-MM-DD`). |
+| `page`, `per_page` | Pagination (default 25, max 100). |
+
+## Statement object
+
+```json
+{
+ "data": {
+ "id": "uuid",
+ "filename": "2026-03-statement.pdf",
+ "content_type": "application/pdf",
+ "byte_size": 182734,
+ "content_sha256": "9f2c...",
+ "review_status": "linked",
+ "period_start_on": "2026-03-01",
+ "period_end_on": "2026-03-31",
+ "currency": "USD",
+ "opening_balance": "1520.00",
+ "closing_balance": "1735.42",
+ "institution_name_hint": "Example Bank",
+ "account_last4_hint": "1234",
+ "account": { "id": "uuid", "name": "Everyday", "currency": "USD" },
+ "suggested_account": null,
+ "match_confidence": null,
+ "created_at": "2026-04-02T09:15:00Z",
+ "updated_at": "2026-04-02T09:15:00Z"
+ },
+ "meta": { "duplicate": false }
+}
+```
+
+Period, balances and hints are read from the document when possible and may be `null`. `suggested_account` and `match_confidence` are set for unlinked statements when the vault finds a likely account the caller can see.
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 42d8dbf229..48c6a95596 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -150,6 +150,127 @@ components:
total_pages:
type: integer
minimum: 0
+ AccountStatementAccount:
+ type: object
+ required:
+ - id
+ - name
+ - currency
+ properties:
+ id:
+ type: string
+ format: uuid
+ name:
+ type: string
+ currency:
+ type: string
+ AccountStatement:
+ type: object
+ required:
+ - id
+ - filename
+ - content_type
+ - byte_size
+ - content_sha256
+ - review_status
+ - created_at
+ - updated_at
+ properties:
+ id:
+ type: string
+ format: uuid
+ filename:
+ type: string
+ content_type:
+ type: string
+ byte_size:
+ type: integer
+ minimum: 1
+ content_sha256:
+ type: string
+ description: SHA-256 of the file (lowercase hex); the vault stores each
+ file once per family
+ review_status:
+ type: string
+ enum:
+ - unmatched
+ - linked
+ - rejected
+ period_start_on:
+ type: string
+ format: date
+ nullable: true
+ period_end_on:
+ type: string
+ format: date
+ nullable: true
+ currency:
+ type: string
+ nullable: true
+ opening_balance:
+ type: string
+ nullable: true
+ closing_balance:
+ type: string
+ nullable: true
+ institution_name_hint:
+ type: string
+ nullable: true
+ account_last4_hint:
+ type: string
+ nullable: true
+ account:
+ allOf:
+ - "$ref": "#/components/schemas/AccountStatementAccount"
+ nullable: true
+ description: Account the statement is linked to
+ suggested_account:
+ allOf:
+ - "$ref": "#/components/schemas/AccountStatementAccount"
+ nullable: true
+ description: Account the vault suggests for an unlinked statement; linking
+ it is confirmed in the app
+ match_confidence:
+ type: number
+ nullable: true
+ minimum: 0
+ maximum: 1
+ created_at:
+ type: string
+ format: date-time
+ updated_at:
+ type: string
+ format: date-time
+ AccountStatementResponse:
+ type: object
+ required:
+ - data
+ - meta
+ properties:
+ data:
+ "$ref": "#/components/schemas/AccountStatement"
+ meta:
+ type: object
+ required:
+ - duplicate
+ properties:
+ duplicate:
+ type: boolean
+ description: True when the uploaded file was already in the vault; the
+ existing statement is returned and nothing is created
+ AccountStatementCollection:
+ type: object
+ required:
+ - data
+ - meta
+ properties:
+ data:
+ type: array
+ maxItems: 100
+ items:
+ "$ref": "#/components/schemas/AccountStatement"
+ meta:
+ "$ref": "#/components/schemas/Pagination"
FamilyExportFile:
type: object
required:
@@ -4827,6 +4948,195 @@ components:
error:
type: string
paths:
+ "/api/v1/account_statements":
+ get:
+ summary: List statements in the Statement Vault
+ description: 'Lists statements the caller can see: unlinked statements and statements
+ linked to accounts shared with them. Requires an admin or member.'
+ tags:
+ - Account Statements
+ security:
+ - apiKeyAuth: []
+ parameters:
+ - name: account_id
+ in: query
+ format: uuid
+ required: false
+ description: Only statements linked to this account
+ schema:
+ type: string
+ - name: review_status
+ in: query
+ required: false
+ schema:
+ type: string
+ enum:
+ - unmatched
+ - linked
+ - rejected
+ - name: content_sha256
+ in: query
+ required: false
+ description: Find the statement for a file by its SHA-256 (hex)
+ schema:
+ type: string
+ - name: start_date
+ in: query
+ format: date
+ required: false
+ description: Only statements whose period ends on or after this date
+ schema:
+ type: string
+ - name: end_date
+ in: query
+ format: date
+ required: false
+ description: Only statements whose period starts on or before this date
+ schema:
+ type: string
+ - name: page
+ in: query
+ required: false
+ description: 'Page number (default: 1)'
+ schema:
+ type: integer
+ - name: per_page
+ in: query
+ required: false
+ description: 'Items per page (default: 25, max: 100)'
+ schema:
+ type: integer
+ responses:
+ '200':
+ description: statements listed
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/AccountStatementCollection"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: guests cannot use the Statement Vault
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '422':
+ description: invalid filter
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ post:
+ summary: Upload a statement to the Statement Vault
+ description: 'Stores a PDF, CSV or XLSX statement (max 25 MB). With account_id
+ the statement is linked to that account (needs write access to it); without
+ it the vault suggests a match to confirm in the app. The vault stores each
+ file once: uploading the same file again returns the existing statement with
+ meta.duplicate = true. Statements are archived only; no transactions are imported.'
+ tags:
+ - Account Statements
+ security:
+ - apiKeyAuth: []
+ parameters: []
+ responses:
+ '201':
+ description: statement stored
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/AccountStatementResponse"
+ '200':
+ description: file already in the vault
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/AccountStatementResponse"
+ '401':
+ description: unauthorized
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '403':
+ description: guest, or API key without write scope
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '404':
+ description: account_id is not an account the caller can write to
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '409':
+ description: file already in the vault, linked to an account the caller
+ cannot see
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '422':
+ description: missing or invalid file
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ requestBody:
+ content:
+ multipart/form-data:
+ schema:
+ type: object
+ required:
+ - file
+ properties:
+ file:
+ type: string
+ format: binary
+ account_id:
+ type: string
+ format: uuid
+ description: Account to link the statement to
+ required: true
+ description: Statement file (.pdf, .csv or .xlsx)
+ "/api/v1/account_statements/{id}":
+ parameters:
+ - name: id
+ in: path
+ format: uuid
+ required: true
+ schema:
+ type: string
+ get:
+ summary: Show a statement
+ tags:
+ - Account Statements
+ security:
+ - apiKeyAuth: []
+ responses:
+ '200':
+ description: statement found
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/AccountStatementResponse"
+ '403':
+ description: guests cannot use the Statement Vault
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '404':
+ description: statement not found
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
"/api/v1/accounts":
get:
summary: List accounts
diff --git a/spec/requests/api/v1/account_statements_spec.rb b/spec/requests/api/v1/account_statements_spec.rb
new file mode 100644
index 0000000000..1e4dd5873e
--- /dev/null
+++ b/spec/requests/api/v1/account_statements_spec.rb
@@ -0,0 +1,222 @@
+# frozen_string_literal: true
+
+require 'swagger_helper'
+
+RSpec.describe 'API V1 Account Statements', 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',
+ role: 'admin'
+ )
+ 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(:guest) do
+ family.users.create!(
+ email: '[email protected]',
+ password: 'password123',
+ password_confirmation: 'password123',
+ role: 'guest'
+ )
+ end
+ let(:guest_api_key) do
+ ApiKey.create!(user: guest, name: 'Guest Docs Key', key: ApiKey.generate_secure_key, scopes: %w[read_write], source: 'web')
+ end
+ let(:account) do
+ Account.create!(
+ family: family,
+ owner: user,
+ name: 'Test Checking',
+ balance: 1000,
+ currency: 'USD',
+ accountable: Depository.new
+ )
+ end
+
+ def statement_file(content: "date,amount\n2024-01-01,1\n", filename: 'statement_2024-01.csv')
+ Rack::Test::UploadedFile.new(StringIO.new(content), 'text/csv', true, original_filename: filename)
+ end
+
+ let!(:statement) do
+ AccountStatement.create_from_upload!(
+ family: user.family,
+ account: account,
+ file: statement_file(content: "date,amount\n2024-02-01,2\n", filename: 'statement_2024-02.csv')
+ )
+ end
+
+ path '/api/v1/account_statements' do
+ get 'List statements in the Statement Vault' do
+ description 'Lists statements the caller can see: unlinked statements and statements linked to accounts shared with them. Requires an admin or member.'
+ tags 'Account Statements'
+ security [ { apiKeyAuth: [] } ]
+ produces 'application/json'
+
+ parameter name: :account_id, in: :query, type: :string, format: :uuid, required: false,
+ description: 'Only statements linked to this account'
+ parameter name: :review_status, in: :query, required: false,
+ schema: { type: :string, enum: %w[unmatched linked rejected] }
+ parameter name: :content_sha256, in: :query, type: :string, required: false,
+ description: 'Find the statement for a file by its SHA-256 (hex)'
+ parameter name: :start_date, in: :query, type: :string, format: :date, required: false,
+ description: 'Only statements whose period ends on or after this date'
+ parameter name: :end_date, in: :query, type: :string, format: :date, required: false,
+ description: 'Only statements whose period starts on or before this date'
+ 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)'
+
+ response '200', 'statements listed' do
+ schema '$ref' => '#/components/schemas/AccountStatementCollection'
+ run_test!
+ end
+
+ response '401', 'unauthorized' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+ let(:'X-Api-Key') { nil }
+ run_test!
+ end
+
+ response '403', 'guests cannot use the Statement Vault' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+ let(:'X-Api-Key') { guest_api_key.plain_key }
+ run_test!
+ end
+
+ response '422', 'invalid filter' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+ let(:start_date) { 'not-a-date' }
+ run_test!
+ end
+ end
+
+ post 'Upload a statement to the Statement Vault' do
+ description 'Stores a PDF, CSV or XLSX statement (max 25 MB). With account_id the statement is linked to that account ' \
+ '(needs write access to it); without it the vault suggests a match to confirm in the app. ' \
+ 'The vault stores each file once: uploading the same file again returns the existing statement with meta.duplicate = true. ' \
+ 'Statements are archived only; no transactions are imported.'
+ tags 'Account Statements'
+ security [ { apiKeyAuth: [] } ]
+ consumes 'multipart/form-data'
+ produces 'application/json'
+
+ parameter name: :file, in: :formData, required: true,
+ description: 'Statement file (.pdf, .csv or .xlsx)',
+ schema: {
+ type: :object,
+ required: [ 'file' ],
+ properties: {
+ file: { type: :string, format: :binary },
+ account_id: { type: :string, format: :uuid, description: 'Account to link the statement to' }
+ }
+ }
+ parameter name: :account_id, in: :formData, required: false,
+ description: 'Account to link the statement to (needs write access to it)',
+ schema: { type: :string, format: :uuid }
+
+ response '201', 'statement stored' do
+ schema '$ref' => '#/components/schemas/AccountStatementResponse'
+ let(:file) { statement_file }
+ run_test!
+ end
+
+ response '200', 'file already in the vault' do
+ schema '$ref' => '#/components/schemas/AccountStatementResponse'
+ let(:file) { statement_file(content: "date,amount\n2024-02-01,2\n") }
+ run_test!
+ end
+
+ response '401', 'unauthorized' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+ let(:'X-Api-Key') { nil }
+ let(:file) { statement_file }
+ run_test!
+ end
+
+ response '403', 'guest, or API key without write scope' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+ let(:'X-Api-Key') { guest_api_key.plain_key }
+ let(:file) { statement_file }
+ run_test!
+ end
+
+ response '404', 'account_id is not an account the caller can write to' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+ let(:file) { statement_file }
+ let(:account_id) { SecureRandom.uuid }
+ run_test!
+ end
+
+ response '409', 'file already in the vault, linked to an account the caller cannot see' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+ let(:hidden_account) do
+ Account.create!(family: family, owner: user, name: 'Private', balance: 0, currency: 'USD', accountable: Depository.new)
+ end
+ let(:member) do
+ family.users.create!(
+ email: '[email protected]',
+ password: 'password123',
+ password_confirmation: 'password123',
+ role: 'member'
+ )
+ end
+ let(:'X-Api-Key') do
+ ApiKey.create!(user: member, name: 'Member Docs Key', key: ApiKey.generate_secure_key, scopes: %w[read_write], source: 'web').plain_key
+ end
+ let(:file) do
+ AccountStatement.create_from_upload!(family: family, account: hidden_account, file: statement_file(content: "date,amount\n2024-04-01,4\n"))
+ statement_file(content: "date,amount\n2024-04-01,4\n")
+ end
+ run_test!
+ end
+
+ response '422', 'missing or invalid file' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+ let(:file) { nil }
+ run_test!
+ end
+ end
+ end
+
+ path '/api/v1/account_statements/{id}' do
+ parameter name: :id, in: :path, type: :string, format: :uuid, required: true
+
+ get 'Show a statement' do
+ tags 'Account Statements'
+ security [ { apiKeyAuth: [] } ]
+ produces 'application/json'
+
+ response '200', 'statement found' do
+ schema '$ref' => '#/components/schemas/AccountStatementResponse'
+ let(:id) { statement.id }
+ run_test!
+ end
+
+ response '403', 'guests cannot use the Statement Vault' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+ let(:id) { statement.id }
+ let(:'X-Api-Key') { guest_api_key.plain_key }
+ run_test!
+ end
+
+ response '404', 'statement not found' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+ let(:id) { SecureRandom.uuid }
+ run_test!
+ end
+ end
+ end
+end
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index 83f5849921..713d6e0083 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -126,6 +126,73 @@ RSpec.configure do |config|
total_pages: { type: :integer, minimum: 0 }
}
},
+ AccountStatementAccount: {
+ type: :object,
+ required: %w[id name currency],
+ properties: {
+ id: { type: :string, format: :uuid },
+ name: { type: :string },
+ currency: { type: :string }
+ }
+ },
+ AccountStatement: {
+ type: :object,
+ required: %w[id filename content_type byte_size content_sha256 review_status created_at updated_at],
+ properties: {
+ id: { type: :string, format: :uuid },
+ filename: { type: :string },
+ content_type: { type: :string },
+ byte_size: { type: :integer, minimum: 1 },
+ content_sha256: { type: :string, description: 'SHA-256 of the file (lowercase hex); the vault stores each file once per family' },
+ review_status: { type: :string, enum: %w[unmatched linked rejected] },
+ period_start_on: { type: :string, format: :date, nullable: true },
+ period_end_on: { type: :string, format: :date, nullable: true },
+ currency: { type: :string, nullable: true },
+ opening_balance: { type: :string, nullable: true },
+ closing_balance: { type: :string, nullable: true },
+ institution_name_hint: { type: :string, nullable: true },
+ account_last4_hint: { type: :string, nullable: true },
+ account: {
+ allOf: [ { '$ref' => '#/components/schemas/AccountStatementAccount' } ],
+ nullable: true,
+ description: 'Account the statement is linked to'
+ },
+ suggested_account: {
+ allOf: [ { '$ref' => '#/components/schemas/AccountStatementAccount' } ],
+ nullable: true,
+ description: 'Account the vault suggests for an unlinked statement; linking it is confirmed in the app'
+ },
+ match_confidence: { type: :number, nullable: true, minimum: 0, maximum: 1 },
+ created_at: { type: :string, format: :'date-time' },
+ updated_at: { type: :string, format: :'date-time' }
+ }
+ },
+ AccountStatementResponse: {
+ type: :object,
+ required: %w[data meta],
+ properties: {
+ data: { '$ref' => '#/components/schemas/AccountStatement' },
+ meta: {
+ type: :object,
+ required: %w[duplicate],
+ properties: {
+ duplicate: { type: :boolean, description: 'True when the uploaded file was already in the vault; the existing statement is returned and nothing is created' }
+ }
+ }
+ }
+ },
+ AccountStatementCollection: {
+ type: :object,
+ required: %w[data meta],
+ properties: {
+ data: {
+ type: :array,
+ maxItems: 100,
+ items: { '$ref' => '#/components/schemas/AccountStatement' }
+ },
+ meta: { '$ref' => '#/components/schemas/Pagination' }
+ }
+ },
FamilyExportFile: {
type: :object,
required: %w[attached],
diff --git a/test/controllers/api/v1/account_statements_controller_test.rb b/test/controllers/api/v1/account_statements_controller_test.rb
new file mode 100644
index 0000000000..9e689516b7
--- /dev/null
+++ b/test/controllers/api/v1/account_statements_controller_test.rb
@@ -0,0 +1,303 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class Api::V1::AccountStatementsControllerTest < ActionDispatch::IntegrationTest
+ setup do
+ @admin = users(:family_admin)
+ @member = users(:family_member)
+ @family = @admin.family
+ @account = accounts(:depository)
+
+ @admin.api_keys.active.destroy_all
+ @member.api_keys.active.destroy_all
+
+ @api_key = create_api_key(@admin, "read_write")
+ @read_only_api_key = create_api_key(@admin, "read")
+ @member_api_key = create_api_key(@member, "read_write")
+ end
+
+ teardown do
+ redis = Redis.new
+ [ @api_key, @read_only_api_key, @member_api_key, @guest_api_key ].compact.each do |key|
+ redis.del("api_rate_limit:#{key.id}")
+ end
+ redis.close
+ end
+
+ test "requires authentication" do
+ get api_v1_account_statements_url
+ assert_response :unauthorized
+
+ post api_v1_account_statements_url, params: { file: statement_upload }
+ assert_response :unauthorized
+ end
+
+ test "uploads a statement linked to an account without importing transactions" do
+ assert_difference "AccountStatement.count", 1 do
+ assert_no_difference [ "Import.count", "Entry.count" ] do
+ post api_v1_account_statements_url,
+ params: { file: statement_upload, account_id: @account.id },
+ headers: api_headers(@api_key)
+ end
+ end
+
+ assert_response :created
+ body = JSON.parse(response.body)
+ statement = AccountStatement.find(body["data"]["id"])
+
+ assert_equal @account, statement.account
+ assert statement.linked?
+ assert_equal false, body["meta"]["duplicate"]
+ assert_equal "linked", body["data"]["review_status"]
+ assert_equal @account.id, body["data"]["account"]["id"]
+ assert_equal statement.content_sha256, body["data"]["content_sha256"]
+ assert_equal "statement_2024-01.csv", body["data"]["filename"]
+ end
+
+ test "uploads an unlinked statement to the inbox" do
+ post api_v1_account_statements_url,
+ params: { file: statement_upload },
+ headers: api_headers(@api_key)
+
+ assert_response :created
+ statement = AccountStatement.find(JSON.parse(response.body)["data"]["id"])
+ assert_nil statement.account
+ assert_not statement.linked?
+ end
+
+ test "returns the existing statement for a duplicate upload" do
+ existing = AccountStatement.create_from_upload!(family: @family, account: @account, file: statement_upload)
+
+ assert_no_difference "AccountStatement.count" do
+ post api_v1_account_statements_url,
+ params: { file: statement_upload(filename: "renamed.csv"), account_id: @account.id },
+ headers: api_headers(@api_key)
+ end
+
+ assert_response :ok
+ body = JSON.parse(response.body)
+ assert_equal existing.id, body["data"]["id"]
+ assert_equal true, body["meta"]["duplicate"]
+ end
+
+ test "does not reveal a duplicate filed against an account the caller cannot see" do
+ private_account = accounts(:other_asset)
+ AccountStatement.create_from_upload!(family: @family, account: private_account, file: statement_upload)
+
+ assert_no_difference "AccountStatement.count" do
+ post api_v1_account_statements_url,
+ params: { file: statement_upload },
+ headers: api_headers(@member_api_key)
+ end
+
+ assert_response :conflict
+ body = JSON.parse(response.body)
+ assert_equal "duplicate", body["error"]
+ assert_nil body["data"]
+ refute_includes response.body, private_account.id
+ end
+
+ test "requires a file" do
+ assert_no_difference "AccountStatement.count" do
+ post api_v1_account_statements_url, params: { account_id: @account.id }, headers: api_headers(@api_key)
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal "validation_failed", JSON.parse(response.body)["error"]
+ end
+
+ test "rejects unsupported file types" do
+ assert_no_difference "AccountStatement.count" do
+ post api_v1_account_statements_url,
+ params: { file: uploaded_file(filename: "notes.txt", content_type: "text/plain", content: "hello") },
+ headers: api_headers(@api_key)
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal "validation_failed", JSON.parse(response.body)["error"]
+ end
+
+ test "rejects an account the caller cannot write to" do
+ assert_no_difference "AccountStatement.count" do
+ post api_v1_account_statements_url,
+ params: { file: statement_upload, account_id: accounts(:credit_card).id },
+ headers: api_headers(@member_api_key)
+ end
+
+ assert_response :not_found
+ end
+
+ test "rejects an account from another family or a malformed id" do
+ other_family_account = Account.create!(
+ family: families(:empty),
+ name: "Other family",
+ balance: 0,
+ currency: "USD",
+ accountable: Depository.new
+ )
+
+ [ other_family_account.id, "not-a-uuid" ].each do |account_id|
+ assert_no_difference "AccountStatement.count" do
+ post api_v1_account_statements_url,
+ params: { file: statement_upload, account_id: account_id },
+ headers: api_headers(@api_key)
+ end
+
+ assert_response :not_found
+ end
+ end
+
+ test "read-only key cannot upload" do
+ assert_no_difference "AccountStatement.count" do
+ post api_v1_account_statements_url, params: { file: statement_upload }, headers: api_headers(@read_only_api_key)
+ end
+
+ assert_response :forbidden
+ end
+
+ test "guest cannot use the vault" do
+ @guest_api_key = create_api_key(family_guest, "read_write")
+
+ get api_v1_account_statements_url, headers: api_headers(@guest_api_key)
+ assert_response :forbidden
+
+ post api_v1_account_statements_url, params: { file: statement_upload }, headers: api_headers(@guest_api_key)
+ assert_response :forbidden
+ end
+
+ test "guest cannot read a statement on an account shared with them" do
+ guest = family_guest
+ @account.account_shares.create!(user: guest, permission: "read_only")
+ statement = AccountStatement.create_from_upload!(family: @family, account: @account, file: statement_upload)
+ assert statement.viewable_by?(guest)
+ @guest_api_key = create_api_key(guest, "read")
+
+ get api_v1_account_statement_url(statement), headers: api_headers(@guest_api_key)
+
+ assert_response :forbidden
+ refute_includes response.body, statement.id
+ end
+
+ test "lists statements the caller can see" do
+ linked = AccountStatement.create_from_upload!(family: @family, account: @account, file: statement_upload)
+ unlinked = AccountStatement.create_from_upload!(family: @family, account: nil, file: statement_upload(content: "date,amount\n2024-02-01,2\n"))
+ private_statement = AccountStatement.create_from_upload!(
+ family: @family,
+ account: accounts(:other_asset),
+ file: statement_upload(content: "date,amount\n2024-03-01,3\n")
+ )
+
+ get api_v1_account_statements_url, headers: api_headers(@member_api_key)
+
+ assert_response :success
+ body = JSON.parse(response.body)
+ ids = body["data"].map { |s| s["id"] }
+ assert_includes ids, linked.id
+ assert_includes ids, unlinked.id
+ refute_includes ids, private_statement.id
+ assert_equal ids.size, body["meta"]["total_count"]
+ end
+
+ test "filters statements" do
+ linked = AccountStatement.create_from_upload!(family: @family, account: @account, file: statement_upload)
+ unlinked = AccountStatement.create_from_upload!(family: @family, account: nil, file: statement_upload(content: "date,amount\n2024-02-01,2\n"))
+ linked.update!(period_start_on: Date.new(2024, 1, 1), period_end_on: Date.new(2024, 1, 31))
+ unlinked.update!(period_start_on: Date.new(2024, 2, 1), period_end_on: Date.new(2024, 2, 29))
+
+ get api_v1_account_statements_url, params: { account_id: @account.id }, headers: api_headers(@read_only_api_key)
+ assert_equal [ linked.id ], JSON.parse(response.body)["data"].map { |s| s["id"] }
+
+ get api_v1_account_statements_url, params: { content_sha256: unlinked.content_sha256.upcase }, headers: api_headers(@read_only_api_key)
+ assert_equal [ unlinked.id ], JSON.parse(response.body)["data"].map { |s| s["id"] }
+
+ get api_v1_account_statements_url, params: { start_date: "2024-01-15", end_date: "2024-01-20" }, headers: api_headers(@read_only_api_key)
+ assert_equal [ linked.id ], JSON.parse(response.body)["data"].map { |s| s["id"] }
+
+ get api_v1_account_statements_url, params: { start_date: "2024-03-01" }, headers: api_headers(@read_only_api_key)
+ assert_empty JSON.parse(response.body)["data"]
+ end
+
+ test "rejects invalid filters" do
+ [ { account_id: "nope" }, { review_status: "approved" }, { start_date: "2024-13-01" } ].each do |filter|
+ get api_v1_account_statements_url, params: filter, headers: api_headers(@read_only_api_key)
+ assert_response :unprocessable_entity
+ assert_equal "validation_failed", JSON.parse(response.body)["error"]
+ end
+ end
+
+ test "shows a statement" do
+ statement = AccountStatement.create_from_upload!(family: @family, account: @account, file: statement_upload)
+
+ get api_v1_account_statement_url(statement), headers: api_headers(@read_only_api_key)
+
+ assert_response :success
+ body = JSON.parse(response.body)
+ assert_equal statement.id, body["data"]["id"]
+ assert_equal @account.name, body["data"]["account"]["name"]
+ assert_equal false, body["meta"]["duplicate"]
+ end
+
+ test "only shows a suggested account the caller can see" do
+ statement = AccountStatement.create_from_upload!(family: @family, account: nil, file: statement_upload)
+ statement.update_columns(suggested_account_id: accounts(:other_asset).id, match_confidence: 0.9)
+
+ get api_v1_account_statement_url(statement), headers: api_headers(@api_key)
+ assert_equal accounts(:other_asset).id, JSON.parse(response.body)["data"]["suggested_account"]["id"]
+
+ get api_v1_account_statement_url(statement), headers: api_headers(@member_api_key)
+ body = JSON.parse(response.body)
+ assert_nil body["data"]["suggested_account"]
+ assert_nil body["data"]["match_confidence"]
+ end
+
+ test "checks suggested accounts without a query per statement" do
+ 3.times do |i|
+ statement = AccountStatement.create_from_upload!(
+ family: @family,
+ account: nil,
+ file: statement_upload(content: "date,amount\n2024-0#{i + 1}-01,#{i}\n")
+ )
+ statement.update_columns(suggested_account_id: accounts(:other_asset).id, match_confidence: 0.9)
+ end
+
+ share_queries = 0
+ counter = ->(*, payload) { share_queries += 1 if payload[:sql].include?("account_shares") }
+ ActiveSupport::Notifications.subscribed(counter, "sql.active_record") do
+ get api_v1_account_statements_url, headers: api_headers(@member_api_key)
+ end
+
+ assert_response :success
+ assert JSON.parse(response.body)["data"].all? { |s| s["suggested_account"].nil? }
+ assert_operator share_queries, :<=, 3
+ end
+
+ test "hides statements the caller cannot see" do
+ private_statement = AccountStatement.create_from_upload!(family: @family, account: accounts(:other_asset), file: statement_upload)
+
+ get api_v1_account_statement_url(private_statement), headers: api_headers(@member_api_key)
+ assert_response :not_found
+
+ get api_v1_account_statement_url("not-a-uuid"), headers: api_headers(@api_key)
+ assert_response :not_found
+
+ get api_v1_account_statement_url(SecureRandom.uuid), headers: api_headers(@api_key)
+ assert_response :not_found
+ end
+
+ private
+
+ def create_api_key(user, scope)
+ ApiKey.create!(
+ user: user,
+ name: "Test #{scope} key",
+ scopes: [ scope ],
+ display_key: "test_#{scope}_#{SecureRandom.hex(8)}",
+ source: scope == "read" ? "mobile" : "web"
+ )
+ end
+
+ def statement_upload(content: "date,amount\n2024-01-01,1\n", filename: "statement_2024-01.csv")
+ uploaded_file(filename: filename, content_type: "text/csv", content: content)
+ end
+end