Events: date-ranged spending with true cost (11.2, #130)

Merged
JA
2mo ago
+1986-1

Summary

Part of #130 (IP11, PR 11.2: Events). Adds a family-scoped, date-ranged Event so a person can ask "what did the Bali trip cost?".

  • An event's transactions are the reportable transactions whose entry date is inside its inclusive range, plus manual included overrides, minus manual excluded ones. Events are lenses, not partitions, so a transaction can belong to several overlapping events.
  • True cost is expenses minus refunds over that set, in family currency, through the same IncomeStatement::Totals seam the dashboard uses (transfers and other budget-excluded kinds, excluded entries, pending rows and accounts excluded from reports do not count).
  • Event#transactions, #true_cost, #category_breakdown, #daily_series (plus #cumulative_series for the chart).
  • Preview-gated pages: events index, show (true cost, running-cost chart, category donut, transaction list, add/remove/restore a transaction), new/edit/delete. Linked from the Reports header for preview users only.

Exit criterion covered: "An event spanning 5 days attributes only transactions inside the range; true cost equals the sum of its transactions net of refunds."

Scope and dependencies

  • Issue: Part of #130.
  • Parent PR/branch, if stacked: none. Branched from fork main at af2c49c. Independent of 11.1 (#292), 11.3 and 11.4 (#293). The shared files are config/routes.rb, locale files and db/schema.rb: this PR and #292 each add a migration, so whichever merges second needs the schema version line and table block resolved by re-running migrations, never by hand (20261001090000 is #292's, 20261003190000 is this one's; it was renumbered from 20261001100000 on 2026-10-03 because #287 uses that version).
  • Intentionally out of scope: auto-detecting events, tagging transactions with an event, per-event budgets, upstream-visible nav, a cost column on the index (one aggregate query per event), event export/import, and translations other than English.

Note on the data model: events and event_transactions are new tables (db/migrate/20261003190000_create_events.rb). event_transactions rows exist only for manual overrides; the ordinary case has no row. Both foreign keys to events and transactions cascade, so deleting a transaction or an event leaves no orphan.

Blast radius: who else hits these lines, and what do they pass? New tables and a new controller. The only shared code touched is one preview_features_enabled?-gated link in app/views/reports/index.html.erb and has_many :events on Family. IncomeStatement, IncomeStatement::Totals, IncomeStatement::DailyExpenseTotals and IncomeStatement::ScopedTransactionsQuery are read, not changed; the net daily series is a new query object (Event::DailyCosts) because DailyExpenseTotals keeps only expense rows.

What else reads what this PR changed the reading of (sibling grep):

  • IncomeStatement::ScopedTransactionsQuery consumers: Totals (reused), DailyExpenseTotals (deliberately unchanged, expense rows only), FamilyStats, CategoryStats (not relevant to an arbitrary transaction set, unchanged). Event::DailyCosts includes the module and so shares its fragments.
  • Event#reportable_transactions re-expresses the SQL WHERE of those queries (BUDGET_EXCLUDED_KINDS, entries.excluded, accounts.exclude_from_reports, tax-advantaged accounts, INTERNAL_MOVEMENT_LABELS, pending) as a relation so the page can list what it costs. The SQL still applies on top, and test "the transaction list and the true cost agree" pins the two against drift.
  • Family::FinancialDataReset deletes entries (and so transactions); overrides go with them through the DB cascade. Events themselves hold no money and, like goals, survive a reset: deliberately unchanged.
  • Family::DataExporter / DataImporter do not know events (nor goals): deliberately unchanged, listed as a follow-up.
  • API and OpenAPI: no /api/v1 endpoint added.

Relation to upstream: this is a fork PR. No upstream PR exists yet for this slice (UI is held on fork main until its drop).

Evidence checklist

  • Each issue in this PR has its own acceptance criteria and no unrelated issue work is included.
  • Contract rows touched by this change name existing tests. (not applicable: no contract rows are touched)
  • Any gate test has an observed failing mutation transcript attached. (not applicable: no gate test; the mutation table below covers the preview gate and the Reports link)
  • Fixtures used as evidence assert internal consistency. (Model tests build their own data in an otherwise empty family on fixed 2020 dates; the list/cost parity test asserts the list sums to the cost.)
  • Financial calculations use BigDecimal and documented rounding points. (Amounts are BigDecimal from the shared SQL and Money; nothing is rounded in the model, display rounding is Money#format.)
  • De-identification uses token-shape allowlists; no personal data is included. (No personal data.)
  • Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.

Mutation pass (each break confirmed by a named failing test, then restored):

BreakFailing test
range end exclusivea five day event attributes exactly the transactions dated inside the inclusive range, a one day event holds that day and nothing around it
range start exclusivesame two, plus true-cost tests
included override ignoredan included override pulls in a transaction dated outside the range, true cost follows the manual overrides
excluded override ignoredan excluded override removes a transaction dated inside the range, resetting a transaction removes its override...
refunds not netted in true costtrue cost is expenses minus refunds, not the gross sum, the daily series sums to the true cost
refunds dropped from daily seriesthe daily series has one row per day, nets a refund...
refunds ignored in category breakdownthe category breakdown nets refunds within each category
transfer / excluded-entry / hidden-account / pending / investment-label filters removedtransfers do not count..., excluded entries do not count..., accounts excluded from reports..., pending transactions..., internal investment movements...
viewer account scoping dropped (model, show, removed list, nearby list, attach)scoping to a user leaves out accounts that user cannot see, show does not reveal..., show does not list a hidden account's transaction among those removed by hand, a transaction on an account the viewer cannot see cannot be attached
Event.find instead of Current.family.events.find / unscoped index / unscoped transaction lookupanother family's event is a 404 on every member route, index lists this family's events..., another family's transaction cannot be attached
require_preview_features! removedredirects users without preview access, the gate stops writes as well as reads
Reports link removed / ungatedthe two ReportsControllerTest link tests
DB check end_date >= start_date, inclusion check, unique index, cascade FK droppedthe four the database refuses... / deleting the transaction removes its overrides tests
model validations (date order, colour, uniqueness, family) offthe matching model tests

One mutant survives by design: dropping included_account_ids from the IncomeStatement::Totals call changes nothing, because the transaction scope handed to it is already limited to the viewer's accounts (belt and braces, as IncomeStatement does). Likewise permitting family_id on create changes nothing, since the association build overwrites it; the update path is covered.

Validation

Commands and results (Ruby 3.3.6, repo pins 3.4.9; Postgres 16; worktree-private DB):

bundle exec rails test test/models/event_test.rb test/models/event_transaction_test.rb \
  test/controllers/events_controller_test.rb test/controllers/reports_controller_test.rb
130 runs, 485 assertions, 0 failures, 0 errors, 0 skips

bundle exec rails test            (full suite)
11446 runs, 49490 assertions, 4 failures, 1 errors, 33 skips

The 4 failures and 1 error are unrelated to events and fail identically on origin/main af2c49c in this environment (also run on a clean checkout): Provider::OpenaiTest#test_extra_headers_stringifies_nested_values_Ruby-style (Hash#inspect format differs under Ruby 3.3.6), Provider::RegistryTest#test_anthropic_provider_initializes_from_ANTHROPIC_API_KEY_env and three Settings::HostingsControllerTest anthropic-base-url tests (the sandbox exports ANTHROPIC_BASE_URL).

bundle exec rubocop                      2963 files inspected, no offenses detected
bundle exec erb_lint app/views/events app/views/reports/index.html.erb   No errors were found in ERB files
bundle exec brakeman --no-pager -q       Security Warnings: 0 (Ignored Warnings: 9, pre-existing)

npm run lint was not run: no JavaScript is added or changed (the existing time_series_chart_controller and donut_chart_controller are reused) and node_modules is not installed here.

db/schema.rb was regenerated; the unrelated check_constraint rewrites this machine's Postgres makes to the retirement_plan* constraints were reverted, so the diff is the version bump plus the two new tables, their indexes, check constraints and foreign keys. The migration was run once locally for that purpose only.

Checked against upstream AGENTS.md (fetched from we-promise/sure main on 2026-10-01; identical to this fork's copy): tenancy via Current.family, no new gems, logic in models, DS::* components with functional tokens, icon helper, t() strings, preview gate per gating-a-preview-feature.md, Minitest and fixtures.

Risks, blockers, and follow-up

  • A viewer sees an event through their own finance accounts (user.finance_accounts), the same scope as the Reports page, so two family members can see different costs for one event. That is deliberate (no leaking of accounts someone has not shared) but is a product decision for the owner.
  • The show page lists at most 200 transactions and links to the transactions page for the date range for the rest.
  • The category breakdown shows categories with positive net spend (subcategories roll up into their parent), so its rows sum to net spend, which differs from true cost only when a category is refunded beyond what was spent in it.
  • An event's date edit moves its transactions immediately; overrides are kept as written and are inert when the date rule already agrees.
  • Decisions for the owner: whether events belong in Family::DataExporter/DataImporter and FinancialDataReset (left out, as goals are).
  • Follow-up, not done here: a cost column on the index; translations other than English; removing the preview gate when the programme ships it.
  • No visual check in a browser was possible here; screenshots to be added before ready.
  • Gatekeeper review fires automatically on this draft; it is not handled here.