The personal finance app for everyone (by everyone)
Ruby
Expose cash flow reporting and secure push-device continuity (#3545)
Juan José Matad4d97b8feee2
diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rbindex f69e6f4be4..f0285cb011 100644--- a/app/controllers/api/v1/base_controller.rb+++ b/app/controllers/api/v1/base_controller.rb@@ -24,6 +24,10 @@ class Api::V1::BaseController < ApplicationControllerbefore_action :force_json_format# Use our custom authentication that supports both OAuth and API keysbefore_action :authenticate_request!+ # Localize registers this before API authentication in ApplicationController.+ # Resolve the family zone only after the API identity has populated Current.+ skip_around_action :switch_timezone+ around_action :switch_timezonebefore_action :check_api_key_rate_limitbefore_action :log_api_accessdiff --git a/app/controllers/api/v1/cash_flows_controller.rb b/app/controllers/api/v1/cash_flows_controller.rbnew file mode 100644index 0000000000..2d79321164--- /dev/null+++ b/app/controllers/api/v1/cash_flows_controller.rb@@ -0,0 +1,27 @@+class Api::V1::CashFlowsController < Api::V1::BaseController+ before_action :ensure_read_scope++ def show+ today = Date.current+ value = params[:month]+ month = value.nil? ? today.beginning_of_month : parse_month(value)+ unless month && month.day == 1 && month <= today+ render json: { error: "invalid_month", message: "month must be a non-future ISO first day (YYYY-MM-01)" }, status: :unprocessable_entity+ return+ end+ statement = IncomeStatement.new(current_resource_owner.family, user: current_resource_owner)+ render json: IncomeStatement::CashFlow.new(statement, month: month, as_of: today)+ end++ private+ def ensure_read_scope+ authorize_scope!(:read)+ end++ def parse_month(value)+ return unless value.is_a?(String) && value.match?(/\A\d{4}-\d{2}-01\z/)+ Date.iso8601(value)+ rescue Date::Error+ nil+ end+enddiff --git a/app/controllers/api/v1/push_subscriptions_controller.rb b/app/controllers/api/v1/push_subscriptions_controller.rbindex 5f07ecde14..dcf4b85324 100644--- a/app/controllers/api/v1/push_subscriptions_controller.rb+++ b/app/controllers/api/v1/push_subscriptions_controller.rb@@ -4,32 +4,17 @@ class Api::V1::PushSubscriptionsController < Api::V1::BaseControllerbefore_action :ensure_write_scopedef create- token = subscription_params[:token].to_s.downcase- subscription = current_resource_owner.push_subscriptions.find_or_initialize_by(token: token)- subscription.assign_attributes(- environment: subscription_params[:environment],- platform: subscription_params[:platform],- last_registered_at: Time.current- )- subscription.save!-+ subscription = PushSubscription.register_for!(user: current_resource_owner,+ token: subscription_params[:token].to_s.downcase,+ environment: subscription_params[:environment], platform: subscription_params[:platform],+ device_key: subscription_params[:device_key])render json: serialize(subscription), status: :createdrescue ActiveRecord::RecordInvalid => erender json: { error: "validation_error", message: e.record.errors.full_messages.to_sentence },status: :unprocessable_entityrescue ActiveRecord::RecordNotUnique- subscription = current_resource_owner.push_subscriptions.find_by(token: token)- if subscription- subscription.update!(- environment: subscription_params[:environment],- platform: subscription_params[:platform],- last_registered_at: Time.current- )- render json: serialize(subscription), status: :created- else- render json: { error: "validation_error", message: "Device token is already registered" },- status: :unprocessable_entity- end+ render json: { error: "validation_error", message: "Device token is already registered" },+ status: :unprocessable_entityenddef destroy@@ -43,7 +28,7 @@ class Api::V1::PushSubscriptionsController < Api::V1::BaseControllerenddef subscription_params- params.permit(:token, :environment, :platform)+ params.permit(:token, :environment, :platform, :device_key)enddef serialize(subscription)diff --git a/app/controllers/api/v1/test_controller.rb b/app/controllers/api/v1/test_controller.rbindex fec058377c..7e183658a8 100644--- a/app/controllers/api/v1/test_controller.rb+++ b/app/controllers/api/v1/test_controller.rb@@ -3,8 +3,11 @@# Test controller for API V1 Base Controller functionality# This controller is only used for testing the base controller behaviorclass Api::V1::TestController < Api::V1::BaseController+ before_action :capture_request_date+def index- render_json({ message: "test_success", user: current_resource_owner&.email })+ render_json({ message: "test_success", user: current_resource_owner&.email,+ date: Date.current.iso8601, callback_date: @request_date.iso8601, time_zone: Time.zone.tzinfo.identifier })enddef not_found@@ -44,4 +47,9 @@ class Api::V1::TestController < Api::V1::BaseControllerscopes: current_scopes})end++ private+ def capture_request_date+ @request_date = Date.current+ endenddiff --git a/app/models/income_statement.rb b/app/models/income_statement.rbindex 73961dcf51..dd8479b89e 100644--- a/app/models/income_statement.rb+++ b/app/models/income_statement.rb@@ -123,11 +123,7 @@ class IncomeStatementRails.cache.fetch(["income_statement", "daily_expense_series", family.id, user&.id,included_account_ids_hash, period.start_date, period.end_date,- family.entries_cache_version, family.accounts.maximum(:updated_at)&.to_i,- # Rates change via ExchangeRate::Importer's upsert_all and the target- # currency via settings; neither touches entries/accounts, so both must- # be part of the key to keep the chart from going stale.- family.currency, ExchangeRate.maximum(:updated_at)&.to_i+ *cache_freshness_key]) doDailyExpenseTotals.new(family,@@ -276,11 +272,21 @@ class IncomeStatement@included_account_ids_hash ||= included_account_ids ? Digest::MD5.hexdigest(included_account_ids.sort.join(",")) : nilend+ # An IncomeStatement is a request-scoped reporting snapshot, like its memoized+ # period totals. Share these aggregate reads across totals and daily series.+ # Rates and target currency can change without touching entries or accounts.+ def cache_freshness_key+ @cache_freshness_key ||= [+ family.entries_cache_version, family.accounts.maximum(:updated_at)&.to_i,+ family.currency, ExchangeRate.maximum(:updated_at)&.to_i+ ]+ end+def totals_query(transactions_scope:, date_range:)sql_hash = Digest::MD5.hexdigest(transactions_scope.to_sql)Rails.cache.fetch([- "income_statement", "totals_query", "v2", family.id, user&.id, included_account_ids_hash, sql_hash, date_range.begin, date_range.end, family.entries_cache_version, family.accounts.maximum(:updated_at)&.to_i+ "income_statement", "totals_query", "v2", family.id, user&.id, included_account_ids_hash, sql_hash, date_range.begin, date_range.end, *cache_freshness_key]) { Totals.new(family, transactions_scope: transactions_scope, date_range: date_range, included_account_ids: included_account_ids).call }enddiff --git a/app/models/income_statement/cash_flow.rb b/app/models/income_statement/cash_flow.rbnew file mode 100644index 0000000000..61e52505a5--- /dev/null+++ b/app/models/income_statement/cash_flow.rb@@ -0,0 +1,58 @@+# A bounded monthly projection of Sure's existing reporting calculations.+# The client never needs to download transaction history to reproduce these rules.+class IncomeStatement::CashFlow+ def initialize(statement, month:, as_of: Date.current, time_zone: Time.zone.tzinfo.identifier)+ raise ArgumentError, "month must be a non-future first day" unless month.day == 1 && month <= as_of++ @statement = statement+ @month = month+ @as_of = as_of+ @time_zone = time_zone+ end++ def as_json(*)+ current_period = Period.custom(start_date: @month, end_date: [ @month.end_of_month, @as_of ].min)+ previous_month = @month.prev_month+ previous_period = Period.custom(start_date: previous_month, end_date: previous_month.end_of_month)+ totals = @statement.totals_for(current_period)+ income = totals.income_money.amount+ spending = totals.expense_money.amount+ current = cumulative_series(current_period)+ previous = cumulative_series(previous_period)+ comparison_day = @month == @as_of.beginning_of_month ? [ @as_of.day, previous.size ].min : previous.size+ previous_total = previous.fetch(comparison_day - 1).fetch(:amount).to_d+ current_total = current.last.fetch(:amount).to_d++ {+ month: @month.iso8601, as_of: @as_of.iso8601, time_zone: @time_zone,+ currency: @statement.family.currency,+ period: period_json(current_period), income: decimal(income), spending: decimal(spending),+ net_savings: decimal(income - spending),+ savings_rate: income.positive? ? decimal((income - spending) / income * 100) : nil,+ spending_comparison: {+ previous_period: period_json(previous_period),+ current_total: decimal(current_total), comparison_total: decimal(previous_total),+ comparison_end_date: previous.fetch(comparison_day - 1).fetch(:date),+ delta: decimal(current_total - previous_total), current: current, previous: previous+ }+ }+ end++ private+ def cumulative_series(period)+ daily = @statement.daily_expense_series(period: period).index_by(&:date)+ cumulative = BigDecimal("0")+ period.date_range.map do |date|+ cumulative += daily[date]&.total || 0+ { date: date.iso8601, amount: decimal(cumulative) }+ end+ end++ def period_json(period)+ { start_date: period.start_date.iso8601, end_date: period.end_date.iso8601 }+ end++ def decimal(value)+ value.to_d.to_s("F")+ end+enddiff --git a/app/models/push_subscription.rb b/app/models/push_subscription.rbindex bd5c91c7ef..b22fded197 100644--- a/app/models/push_subscription.rb+++ b/app/models/push_subscription.rb@@ -1,3 +1,5 @@+require "digest"+class PushSubscription < ApplicationRecordbelongs_to :user@@ -10,5 +12,42 @@ class PushSubscription < ApplicationRecordvalidates :platform, inclusion: { in: %w[ios] }validates :last_registered_at, presence: true+ # A per-installation secret proves continuity when the same device changes+ # users while its old subscription could not be removed (for example offline).+ # Never reuse a row ID across users: queued jobs and delayed deletes refer to it.+ def self.register_for!(user:, token:, environment:, platform:, device_key: nil)+ attempts = 0+ begin+ transaction(requires_new: true) do+ subscription = lock.find_by(token: token.downcase)+ candidate = new(user: user, token: token, environment: environment,+ platform: platform, last_registered_at: Time.current)+ if !device_key.nil? && !(device_key.is_a?(String) && device_key.match?(/\A[0-9a-f]{64}\z/))+ candidate.errors.add(:base, "Invalid device key")+ raise ActiveRecord::RecordInvalid, candidate+ end+ digest = Digest::SHA256.hexdigest(device_key) if device_key.present?+ if subscription && subscription.user_id != user.id+ unless digest && subscription.device_key_digest &&+ ActiveSupport::SecurityUtils.secure_compare(subscription.device_key_digest, digest)+ candidate.errors.add(:base, "Device token is already registered")+ raise ActiveRecord::RecordInvalid, candidate+ end+ subscription.destroy!+ subscription = nil+ end+ subscription ||= candidate+ subscription.assign_attributes(environment: environment, platform: platform, last_registered_at: Time.current)+ subscription.device_key_digest = digest if digest+ subscription.save!+ subscription+ end+ rescue ActiveRecord::RecordNotUnique+ attempts += 1+ retry if attempts < 2+ raise+ end+ end+scope :recent, -> { where("last_registered_at > ?", 90.days.ago) }enddiff --git a/config/routes.rb b/config/routes.rbindex a8ab96b5bf..ffcae05184 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -758,6 +758,7 @@ Rails.application.routes.draw dopost :publish, on: :memberendresource :usage, only: [ :show ], controller: :usage+ resource :cash_flow, only: [ :show ], controller: :cash_flowsresource :balance_sheet, only: [ :show ], controller: :balance_sheetresources :insights, only: [ :index ]resources :push_subscriptions, only: [ :create, :destroy ]diff --git a/db/migrate/20260913000000_add_device_key_digest_to_push_subscriptions.rb b/db/migrate/20260913000000_add_device_key_digest_to_push_subscriptions.rbnew file mode 100644index 0000000000..4cd001fa5a--- /dev/null+++ b/db/migrate/20260913000000_add_device_key_digest_to_push_subscriptions.rb@@ -0,0 +1,5 @@+class AddDeviceKeyDigestToPushSubscriptions < ActiveRecord::Migration[7.2]+ def change+ add_column :push_subscriptions, :device_key_digest, :string+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex cdc2abc4a2..2e27333d2f 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_09_10_130000) do+ActiveRecord::Schema[8.1].define(version: 2026_09_13_000000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -1731,6 +1731,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_10_130000) docreate_table "push_subscriptions", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.datetime "created_at", null: false+ t.string "device_key_digest"t.string "environment", null: falset.datetime "last_registered_at", null: falset.string "platform", default: "ios", null: falsediff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex e78770eada..b10d23cfe7 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -344,6 +344,30 @@ components:type: arrayitems:"$ref": "#/components/schemas/Insight"+ PushSubscriptionRegistration:+ type: object+ required:+ - token+ - environment+ - platform+ properties:+ token:+ type: string+ environment:+ type: string+ enum:+ - sandbox+ - production+ platform:+ type: string+ enum:+ - ios+ device_key:+ type: string+ pattern: "^[0-9a-f]{64}$"+ description: Optional 256-bit installation secret, unique per server and+ kept in device secure storage. Required proof to replace another user’s+ registration for this device. Never returned.PushSubscription:type: objectrequired:@@ -3180,6 +3204,97 @@ components:formatted:type: stringdescription: Locale-formatted money string+ FinancialPeriod:+ type: object+ required:+ - start_date+ - end_date+ properties:+ start_date:+ type: string+ format: date+ end_date:+ type: string+ format: date+ SpendingPoint:+ type: object+ required:+ - date+ - amount+ properties:+ date:+ type: string+ format: date+ amount:+ type: string+ description: Cumulative decimal amount in family currency+ CashFlow:+ type: object+ required:+ - month+ - as_of+ - time_zone+ - currency+ - period+ - income+ - spending+ - net_savings+ - savings_rate+ - spending_comparison+ properties:+ month:+ type: string+ format: date+ as_of:+ type: string+ format: date+ time_zone:+ type: string+ currency:+ type: string+ period:+ "$ref": "#/components/schemas/FinancialPeriod"+ income:+ type: string+ spending:+ type: string+ net_savings:+ type: string+ savings_rate:+ type: string+ nullable: true+ description: Percentage points; null when income is nonpositive. May be+ negative.+ spending_comparison:+ type: object+ required:+ - previous_period+ - current_total+ - comparison_total+ - comparison_end_date+ - delta+ - current+ - previous+ properties:+ previous_period:+ "$ref": "#/components/schemas/FinancialPeriod"+ current_total:+ type: string+ comparison_total:+ type: string+ delta:+ type: string+ comparison_end_date:+ type: string+ format: date+ current:+ type: array+ items:+ "$ref": "#/components/schemas/SpendingPoint"+ previous:+ type: array+ items:+ "$ref": "#/components/schemas/SpendingPoint"BalanceSheet:type: objectrequired:@@ -4370,6 +4485,44 @@ paths:application/json:schema:"$ref": "#/components/schemas/ErrorResponse"+ "/api/v1/cash_flow":+ get:+ summary: Show monthly cash flow+ tags:+ - Cash Flow+ description: Server-calculated income, spending, savings, and daily cumulative+ comparison in family currency. Uses the authenticated user’s finance accounts+ and Sure reporting rules.+ parameters:+ - name: month+ in: query+ required: false+ schema:+ type: string+ format: date+ description: Non-future first day YYYY-MM-01; defaults to the current month+ in the family time zone.+ security:+ - apiKeyAuth: []+ responses:+ '200':+ description: summary returned+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/CashFlow"+ '422':+ description: invalid month+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ '401':+ description: unauthorized+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse""/api/v1/categories":get:summary: List categories@@ -6078,23 +6231,7 @@ paths:content:application/json:schema:- type: object- required:- - token- - environment- - platform- properties:- token:- type: string- environment:- type: string- enum:- - sandbox- - production- platform:- type: string- enum:- - ios+ "$ref": "#/components/schemas/PushSubscriptionRegistration"required: true"/api/v1/push_subscriptions/{id}":parameters:diff --git a/docs/clients.md b/docs/clients.mdindex 446553105a..aafc2d14df 100644--- a/docs/clients.md+++ b/docs/clients.md@@ -107,3 +107,18 @@ endpoint guides such as [docs/api/transactions.md](api/transactions.md).All clients should connect to a Sure server the user controls or trusts. Native,mobile, API, and MCP clients do not replace the server; they are different waysto access it.++### Native reporting and device continuity++Read monthly server-calculated totals and the daily spending comparison using+[`GET /api/v1/cash_flow`](api/cash-flow.md). Native clients should+use these values instead of rebuilding Sure's reporting rules from transactions.++Push registration accepts an optional `device_key`: 32 securely random bytes+encoded as 64 lowercase hex characters, generated independently per server and+stored only in secure device storage. Preserve it across user logout. The server+stores only its SHA-256 digest. If the APNs token already belongs to another user,+a matching key allows atomic replacement with a **new subscription ID**, making+old queued deliveries and deletes harmless. A missing or wrong proof returns 422.+An existing registration without a digest must first be enrolled by its original+owner or removed by that owner; knowing the APNs token alone never authorizes transfer.diff --git a/spec/requests/api/v1/cash_flow_spec.rb b/spec/requests/api/v1/cash_flow_spec.rbnew file mode 100644index 0000000000..029eb66b12--- /dev/null+++ b/spec/requests/api/v1/cash_flow_spec.rb@@ -0,0 +1,65 @@+# frozen_string_literal: true++require 'swagger_helper'++RSpec.describe 'API V1 Cash Flow', 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 }++ path '/api/v1/cash_flow' do+ get 'Show monthly cash flow' do+ tags 'Cash Flow'+ description 'Server-calculated income, spending, savings, and daily cumulative comparison in family currency. Uses the authenticated user’s finance accounts and Sure reporting rules.'+ parameter name: :month, in: :query, required: false, schema: { type: :string, format: :date }, description: 'Non-future first day YYYY-MM-01; defaults to the current month in the family time zone.'+ security [ { apiKeyAuth: [] } ]+ produces 'application/json'++ response '200', 'summary returned' do+ schema '$ref' => '#/components/schemas/CashFlow'++ run_test!+ end++ response '422', 'invalid month' do+ schema '$ref' => '#/components/schemas/ErrorResponse'+ let(:month) { 'invalid' }+ run_test!+ end++ response '401', 'unauthorized' do+ schema '$ref' => '#/components/schemas/ErrorResponse'++ let(:'X-Api-Key') { 'invalid-key' }++ run_test!+ end+ end+ end+enddiff --git a/spec/requests/api/v1/push_subscriptions_spec.rb b/spec/requests/api/v1/push_subscriptions_spec.rbindex 9ab2689ce5..7e127f3ae8 100644--- a/spec/requests/api/v1/push_subscriptions_spec.rb+++ b/spec/requests/api/v1/push_subscriptions_spec.rb@@ -19,15 +19,7 @@ RSpec.describe "API V1 Push Subscriptions", type: :request dosecurity [ { apiKeyAuth: [] } ]consumes "application/json"produces "application/json"- parameter name: :subscription, in: :body, required: true, schema: {- type: :object,- required: %w[token environment platform],- properties: {- token: { type: :string },- environment: { type: :string, enum: %w[sandbox production] },- platform: { type: :string, enum: %w[ios] }- }- }+ parameter name: :subscription, in: :body, required: true, schema: { "$ref" => "#/components/schemas/PushSubscriptionRegistration" }let(:subscription) { { token: "ab" * 32, environment: "sandbox", platform: "ios" } }response "201", "token registered" dodiff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rbindex 1e6d02cea4..27eabf4e4c 100644--- a/spec/swagger_helper.rb+++ b/spec/swagger_helper.rb@@ -245,6 +245,14 @@ RSpec.configure do |config|insights: { type: :array, items: { '$ref' => '#/components/schemas/Insight' } }}},+ PushSubscriptionRegistration: {+ type: :object, required: %w[token environment platform],+ properties: {+ token: { type: :string }, environment: { type: :string, enum: %w[sandbox production] },+ platform: { type: :string, enum: %w[ios] },+ device_key: { type: :string, pattern: '^[0-9a-f]{64}$', description: 'Optional 256-bit installation secret, unique per server and kept in device secure storage. Required proof to replace another user’s registration for this device. Never returned.' }+ }+ },PushSubscription: {type: :object,required: %w[id environment platform last_registered_at],@@ -1720,6 +1728,36 @@ RSpec.configure do |config|formatted: { type: :string, description: 'Locale-formatted money string' }}},+ FinancialPeriod: {+ type: :object, required: %w[start_date end_date],+ properties: { start_date: { type: :string, format: :date }, end_date: { type: :string, format: :date } }+ },+ SpendingPoint: {+ type: :object, required: %w[date amount],+ properties: { date: { type: :string, format: :date }, amount: { type: :string, description: 'Cumulative decimal amount in family currency' } }+ },+ CashFlow: {+ type: :object,+ required: %w[month as_of time_zone currency period income spending net_savings savings_rate spending_comparison],+ properties: {+ month: { type: :string, format: :date }, as_of: { type: :string, format: :date },+ time_zone: { type: :string }, currency: { type: :string },+ period: { '$ref' => '#/components/schemas/FinancialPeriod' },+ income: { type: :string }, spending: { type: :string }, net_savings: { type: :string },+ savings_rate: { type: :string, nullable: true, description: 'Percentage points; null when income is nonpositive. May be negative.' },+ spending_comparison: {+ type: :object,+ required: %w[previous_period current_total comparison_total comparison_end_date delta current previous],+ properties: {+ previous_period: { '$ref' => '#/components/schemas/FinancialPeriod' },+ current_total: { type: :string }, comparison_total: { type: :string }, delta: { type: :string },+ comparison_end_date: { type: :string, format: :date },+ current: { type: :array, items: { '$ref' => '#/components/schemas/SpendingPoint' } },+ previous: { type: :array, items: { '$ref' => '#/components/schemas/SpendingPoint' } }+ }+ }+ }+ },BalanceSheet: {type: :object,required: %w[currency net_worth assets liabilities],diff --git a/test/controllers/api/v1/base_controller_test.rb b/test/controllers/api/v1/base_controller_test.rbindex a6dec7ab63..8db9691285 100644--- a/test/controllers/api/v1/base_controller_test.rb+++ b/test/controllers/api/v1/base_controller_test.rb@@ -32,6 +32,30 @@ class Api::V1::BaseControllerTest < ActionDispatch::IntegrationTestRedis.new.del("api_rate_limit:#{@api_key.id}")end+ test "uses each authenticated family's timezone in callbacks and actions without leaking it" do+ other_user = users(:empty)+ other_key = ApiKey.create!(user: other_user, name: "Timezone Read", scopes: [ "read" ],+ display_key: "timezone_#{SecureRandom.hex(8)}")+ @user.family.update!(timezone: "America/Los_Angeles")+ other_user.family.update!(timezone: "Asia/Tokyo")++ Time.use_zone("UTC") do+ travel_to Time.utc(2024, 3, 1, 1) do+ [ [ @plain_api_key, "America/Los_Angeles", "2024-02-29" ],+ [ other_key.display_key, "Asia/Tokyo", "2024-03-01" ] ].each do |key, zone, date|+ get "/api/v1/test", headers: { "X-Api-Key" => key }+ assert_response :success+ assert_equal zone, response.parsed_body["time_zone"]+ assert_equal date, response.parsed_body["date"]+ assert_equal date, response.parsed_body["callback_date"]+ assert_equal "UTC", Time.zone.name+ end+ end+ end+ ensure+ Redis.new.del("api_rate_limit:#{other_key.id}") if other_key+ end+test "should require authentication" do# Test that endpoints require OAuth tokensget "/api/v1/test"diff --git a/test/controllers/api/v1/cash_flows_controller_test.rb b/test/controllers/api/v1/cash_flows_controller_test.rbnew file mode 100644index 0000000000..faa0692987--- /dev/null+++ b/test/controllers/api/v1/cash_flows_controller_test.rb@@ -0,0 +1,60 @@+require "test_helper"++class Api::V1::CashFlowsControllerTest < ActionDispatch::IntegrationTest+ include EntriesTestHelper+ setup do+ @user = users(:family_admin)+ @user.api_keys.active.destroy_all+ @auth = ApiKey.create!(user: @user, name: "Summary Read", scopes: [ "read" ],+ display_key: "test_ro_#{SecureRandom.hex(8)}", source: "mobile")+ Redis.new.del("api_rate_limit:#{@auth.id}")+ end++ test "requires authentication" do+ get "/api/v1/cash_flow"+ assert_response :unauthorized+ end++ test "supports read and read_write and defaults to family month" do+ @user.family.update!(timezone: "Pacific Time (US & Canada)")+ travel_to Time.utc(2024, 3, 1, 1) do+ %w[read read_write].each do |scope|+ @auth.update!(scopes: [ scope ])+ get "/api/v1/cash_flow", headers: api_headers(@auth)+ assert_response :success+ body = response.parsed_body+ assert_equal "2024-02-01", body["month"]+ assert_equal "2024-02-29", body["as_of"]+ assert_equal "America/Los_Angeles", body["time_zone"]+ assert_equal 29, body.dig("spending_comparison", "current").size+ end+ end+ end++ test "rejects invalid and future periods" do+ [ "2024-02-02", "2024-13-01", "not-a-date", "9999-01-01", "" ].each do |month|+ get "/api/v1/cash_flow", params: { month: month }, headers: api_headers(@auth)+ assert_response :unprocessable_entity+ assert_equal "invalid_month", response.parsed_body["error"]+ end+ end++ test "summary uses the authenticated user's finance account selection" do+ month = Date.new(2024, 2, 1)+ own = @user.family.accounts.create!(name: "Own", owner: @user, currency: "USD", balance: 0, accountable: Depository.new)+ other = @user.family.users.where.not(id: @user.id).first!+ excluded = @user.family.accounts.create!(name: "Read only share", owner: other, currency: "USD", balance: 0, accountable: Depository.new)+ excluded.account_shares.create!(user: @user, permission: "read_only", include_in_finances: false)+ create_transaction(account: own, amount: 12, date: month)+ create_transaction(account: excluded, amount: 900, date: month)+ get "/api/v1/cash_flow", params: { month: month.iso8601 }, headers: api_headers(@auth)+ assert_response :success+ assert_equal "12.0", response.parsed_body["spending"]+ assert_equal "12.0", response.parsed_body.dig("spending_comparison", "current_total")+ end++ private+ def api_headers(auth)+ { "X-Api-Key" => auth.display_key }+ end+enddiff --git a/test/controllers/api/v1/family_settings_controller_test.rb b/test/controllers/api/v1/family_settings_controller_test.rbindex e1fb8565c0..2740fe06bf 100644--- a/test/controllers/api/v1/family_settings_controller_test.rb+++ b/test/controllers/api/v1/family_settings_controller_test.rb@@ -47,8 +47,8 @@ class Api::V1::FamilySettingsControllerTest < ActionDispatch::IntegrationTestassert_equal "private", response_body["default_account_sharing"]assert_equal true, response_body["custom_enabled_currencies"]assert_equal @family.enabled_currency_codes, response_body["enabled_currencies"]- assert_equal @family.created_at.iso8601, response_body["created_at"]- assert_equal @family.updated_at.iso8601, response_body["updated_at"]+ assert_equal @family.created_at.change(usec: 0), Time.iso8601(response_body["created_at"])+ assert_equal @family.updated_at.change(usec: 0), Time.iso8601(response_body["updated_at"])assert_not response_body.key?("stripe_customer_id")assert_not response_body.key?("vector_store_id")enddiff --git a/test/controllers/api/v1/push_subscriptions_controller_test.rb b/test/controllers/api/v1/push_subscriptions_controller_test.rbindex fa8bfbafe6..dec0201237 100644--- a/test/controllers/api/v1/push_subscriptions_controller_test.rb+++ b/test/controllers/api/v1/push_subscriptions_controller_test.rb@@ -157,4 +157,42 @@ class Api::V1::PushSubscriptionsControllerTest < ActionDispatch::IntegrationTestassert_response :unauthorizedend+ test "a device can change users only with its original installation proof" do+ secret = "cd" * 32+ old = PushSubscription.register_for!(user: users(:empty), token: @token,+ environment: "sandbox", platform: "ios", device_key: secret)+ [ nil, "ef" * 32, "malformed" ].each do |proof|+ post api_v1_push_subscriptions_url,+ params: { token: @token, environment: "production", platform: "ios", device_key: proof },+ headers: @headers, as: :json+ assert_response :unprocessable_entity+ assert_equal users(:empty), old.reload.user+ end++ assert_no_difference "PushSubscription.count" do+ post api_v1_push_subscriptions_url,+ params: { token: @token, environment: "production", platform: "ios", device_key: secret },+ headers: @headers, as: :json+ assert_response :created+ end+ replacement = PushSubscription.find_by!(token: @token)+ assert_equal @user, replacement.user+ assert_not_equal old.id, replacement.id+ assert_not PushSubscription.exists?(old.id)+ assert_not response.parsed_body.key?("device_key")+ assert_not response.parsed_body.key?("device_key_digest")+ delete api_v1_push_subscription_url(old.id), headers: @headers+ assert_response :not_found+ assert PushSubscription.exists?(replacement.id)+ end++ test "the original owner can enroll an existing subscription for device continuity" do+ old = @user.push_subscriptions.create!(token: @token, environment: "sandbox", platform: "ios", last_registered_at: Time.current)+ post api_v1_push_subscriptions_url,+ params: { token: @token, environment: "sandbox", platform: "ios", device_key: "cd" * 32 },+ headers: @headers, as: :json+ assert_response :created+ assert_equal old.id, response.parsed_body["id"]+ assert_equal Digest::SHA256.hexdigest("cd" * 32), old.reload.device_key_digest+ endenddiff --git a/test/jobs/deliver_insight_notification_job_test.rb b/test/jobs/deliver_insight_notification_job_test.rbindex 266b021ad2..218dfb1c1c 100644--- a/test/jobs/deliver_insight_notification_job_test.rb+++ b/test/jobs/deliver_insight_notification_job_test.rb@@ -11,6 +11,18 @@ class DeliverInsightNotificationJobTest < ActiveJob::TestCase)end+ test "a job queued before a device changed users cannot reach its replacement" do+ @subscription.update!(device_key_digest: Digest::SHA256.hexdigest("cd" * 32))+ old_id = @subscription.id+ next_user = @insight.family.users.where.not(id: @subscription.user_id).first!+ replacement = PushSubscription.register_for!(user: next_user, token: @subscription.token,+ environment: "sandbox", platform: "ios", device_key: "cd" * 32)+ Apns::Client.expects(:new).never+ DeliverInsightNotificationJob.perform_now(insight_id: @insight.id, push_subscription_id: old_id)+ assert PushSubscription.exists?(replacement.id)+ assert_not PushSubscription.exists?(old_id)+ end+test "delivers a privacy-preserving insight notification" doresponse = stub(ok?: true)client = mockdiff --git a/test/models/income_statement/cash_flow_test.rb b/test/models/income_statement/cash_flow_test.rbnew file mode 100644index 0000000000..2ad9ef4dec--- /dev/null+++ b/test/models/income_statement/cash_flow_test.rb@@ -0,0 +1,86 @@+require "test_helper"++class IncomeStatement::CashFlowTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:empty)+ @account = @family.accounts.create! name: "Checking", currency: "USD", balance: 5000, accountable: Depository.new+ @month = Date.new(2024, 2, 1)+ end++ test "reads account and exchange rate freshness once for the complete report" do+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)+ queries = ActiveRecord::Base.uncached { capture_sql_queries { summary } }++ assert_equal 1, queries.grep(/MAX\("accounts"\."updated_at"\)/i).size+ assert_equal 1, queries.grep(/MAX\("exchange_rates"\."updated_at"\)/i).size+ end++ test "uses server reporting rules and exact decimal amounts" do+ create_transaction(account: @account, amount: -1000, date: @month)+ create_transaction(account: @account, amount: 12.345.to_d, date: @month)+ create_transaction(account: @account, amount: -20, date: @month, kind: "loan_payment")+ create_transaction(account: @account, amount: 900, date: @month, kind: "cc_payment")+ create_transaction(account: @account, amount: 800, date: @month, excluded: true)+ pending = create_transaction(account: @account, amount: 700, date: @month)+ pending.entryable.update!(extra: { "simplefin" => { "pending" => true } })+ result = summary+ assert_equal "1000.0", result[:income]+ assert_equal "32.345", result[:spending]+ assert_equal "967.655", result[:net_savings]+ assert_equal "32.345", result[:spending_comparison][:current_total]+ assert_equal "96.7655", result[:savings_rate]+ end++ test "fills every day and compares current month to the same elapsed day" do+ create_transaction(account: @account, amount: 10, date: Date.new(2024, 1, 10))+ create_transaction(account: @account, amount: 90, date: Date.new(2024, 1, 31))+ result = summary(as_of: Date.new(2024, 2, 15))[:spending_comparison]+ assert_equal 15, result[:current].size+ assert_equal 31, result[:previous].size+ assert_equal "10.0", result[:comparison_total]+ assert_equal "100.0", result[:previous].last[:amount]+ assert_equal "2024-01-15", result[:comparison_end_date]+ end++ test "historical leap month retains full previous month and null rate without income" do+ result = summary+ assert_nil result[:savings_rate]+ assert_equal 29, result[:spending_comparison][:current].size+ assert_equal 31, result[:spending_comparison][:previous].size+ assert_equal "2024-01-31", result[:spending_comparison][:comparison_end_date]+ end++ test "rejects future and nonfirst month" do+ assert_raises(ArgumentError) { summary(month: Date.new(2025, 1, 1)) }+ assert_raises(ArgumentError) { summary(month: Date.new(2024, 2, 2)) }+ end++ test "does not include another family" do+ create_transaction(account: accounts(:depository), amount: 100, date: @month)+ assert_equal "0.0", summary[:spending]+ end++ test "reports FX-converted values without rounding to currency minor units" do+ eur = @family.accounts.create!(name: "EUR", currency: "EUR", balance: 0, accountable: Depository.new)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: @month, rate: "1.2345")+ create_transaction(account: eur, currency: "EUR", amount: 10, date: @month)+ assert_equal "12.345", summary[:spending]+ assert_equal "12.345", summary[:spending_comparison][:current_total]+ end++ test "savings rate may be negative and currency remains attached" do+ @family.update!(currency: "JPY")+ @account.update!(currency: "JPY")+ create_transaction(account: @account, currency: "JPY", amount: -100, date: @month)+ create_transaction(account: @account, currency: "JPY", amount: 150, date: @month)+ assert_equal "JPY", summary[:currency]+ assert_equal "-50.0", summary[:savings_rate]+ end++ private+ def summary(month: @month, as_of: Date.new(2024, 3, 5))+ IncomeStatement::CashFlow.new(IncomeStatement.new(@family), month: month, as_of: as_of).as_json+ end+enddiff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rbindex 4068775c4d..ed049e527d 100644--- a/test/models/income_statement_test.rb+++ b/test/models/income_statement_test.rb@@ -20,7 +20,7 @@ class IncomeStatementTest < ActiveSupport::TestCasecreate_transaction(account: @credit_card_account, amount: 400, category: @groceries_category)end- test "daily_expense_series cache busts when the family currency changes" do+ test "a new statement invalidates daily series when the family currency changes" dostatement = IncomeStatement.new(@family)period = Period.last_30_days@@ -29,10 +29,10 @@ class IncomeStatementTest < ActiveSupport::TestCasestatement.daily_expense_series(period: period)@family.update!(currency: "EUR")- statement.daily_expense_series(period: period)+ IncomeStatement.new(@family).daily_expense_series(period: period)end- test "daily_expense_series cache busts when exchange rates change" do+ test "a new statement invalidates daily series when exchange rates change" dostatement = IncomeStatement.new(@family)period = Period.last_30_days@@ -43,7 +43,7 @@ class IncomeStatementTest < ActiveSupport::TestCasetravel 1.second doExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.9)- statement.daily_expense_series(period: period)+ IncomeStatement.new(@family).daily_expense_series(period: period)endend