Commit Graph

2762 Commits

Author SHA1 Message Date
Guillem Arias
f672aae3cf perf + tests(goals): share account-ids across velocity windows + cover gaps
- Family#savings_inflow_windows wraps the current/prior 30d sums in a
  single helper that memoizes the linked-account-id lookup. The KPI tile
  on the goals index used to run the join+pluck twice per request.
- Replace two instance_variable_set pokes and one any_instance.stubs in
  the goal/controller tests. Refetching the goal exercises the real
  request lifecycle and stops the tests from leaning on implementation
  details. The 'All caught up' assertion now relies on a real reached
  state (target 1 vs the depository fixture's 5000 balance) rather than
  stubbing :status.
- Add tests covering: hex format validation on Goal#color, AASM cache
  reset (display_status reads the new state on the same instance after
  pause!), negative pledge amount rejection, expire! no-op on already-
  expired pledge, cancel! NotOpenError on non-open pledge, sweep job
  idempotency on a second pass, and strong-params rejection of state /
  family_id on goal create.
2026-05-18 21:11:30 +02:00
Guillem Arias
fbcd13c44d fix(a11y): focus trap + returnFocus on DS::Dialog
Native <dialog>.showModal() moves focus inside the dialog on open but
doesn't trap Tab / Shift+Tab, and focus restoration on close is
inconsistent across engines. Add three things to the dialog controller:

- Capture document.activeElement before showModal() so the trigger is
  recoverable when the dialog closes (ESC, backdrop click, explicit
  close button, programmatic close all route through the native close
  event).
- Wrap Tab inside the dialog so a keyboard user can't tab out into the
  scrim-covered page behind.
- Restore focus to the captured trigger on the close event. If the
  trigger has been detached (Turbo morphed it out), skip silently
  rather than throw.

Verified manually: opening the new-goal modal moves focus to the name
input; ESC restores focus to the "New goal" link; Tab wraps from the
last focusable back to the first.
2026-05-18 21:06:47 +02:00
Guillem Arias
d51c88d323 fix(goals JS): listener cleanup on color/icon picker + debounce filter URL sync
- color_icon_picker: listeners were attached in initialize() with inline
  arrows, so they had no removable reference and no disconnect() cleanup.
  Every Turbo navigation that re-rendered the picker stacked another
  listener on the same node and left the Pickr instance alive. Move
  attachment to connect(), store bound references, and clean up in
  disconnect() (including destroyAndRemove on the Pickr).
- goals_filter: replaceState fired on every keystroke. Debounce the URL
  sync 200 ms so a typing burst collapses into a single update. The
  visible filtering stays real-time. Clear the timer in disconnect()
  so a pending sync doesn't fire on an unmounted controller.
2026-05-18 21:03:55 +02:00
Guillem Arias
79c81377ac i18n + a11y(goals): extract picker strings + drop redundant status-pill aria-label
- Color picker had four hardcoded English strings ("Color", "Icon",
  "Poor contrast, choose darker color or", "auto-adjust."). Move them
  under `goals.color_picker.*` and call them through `t()`. CLAUDE.md
  requires every user-facing string go through i18n.
- Status pill duplicated its visible label in `aria-label`, which makes
  screen readers ignore the visible text. Drop the override so the
  visible label is the accessible name.
2026-05-18 21:02:05 +02:00
Guillem Arias
67726f88a6 fix(goals): clear state-dependent caches on AASM transition + harden sweep job
- Goal: `display_status` and `projection_summary` memoize a value that
  depends on the AASM state column. Without resetting them after a
  transition the same instance keeps returning the pre-transition value.
  Hook `after_all_transitions :reset_state_dependent_caches!` undoes the
  memos so post-`archive!` / post-`pause!` reads see the new state.
- SweepExpiredGoalPledgesJob: the inner rescue covered per-pledge failures
  but not cursor-phase failures (DB blip, OOM mid-batch). Add an outer
  rescue that reports + re-raises so Sentry sees the failure and Sidekiq
  retries the job.
2026-05-18 21:00:18 +02:00
Guillem Arias
fb36ac319a fix(goals): validate color format + restore cascade on drop migration
- Add hex-format validation on Goal#color so submissions can't smuggle
  arbitrary CSS into the style attribute on the avatar / picker preview.
  The picker accepts custom hexes, so format validation (not inclusion)
  is the right shape — anything not matching #RRGGBB is rejected at
  the model boundary.
- Fix the on_delete in the down block of drop_goal_contributions to
  match the original cascade. Restoring with restrict was a schema
  drift that would have shifted referential behavior after a rollback.
2026-05-18 20:57:22 +02:00
Guillem Arias
30c2638fd0 refactor(css): move .goal-avatar rules out of application.css
Goals-specific styling doesn't belong in the global stylesheet. Extract
the avatar tint + theme-aware text color into a topical goals.css and
@import it alongside the other feature CSS files.
2026-05-18 20:46:56 +02:00
Guillem Arias
af647a9cfc feat(beta-gating): beta_gated_nav_item helper auto-marks gated entries
Wraps the conditional + dot wiring into a single call so adding a new
beta nav entry doesn't require remembering to set `beta: true` by hand
or duplicating the `beta_features_enabled?` check. Naming mirrors the
existing `BetaGateable` concern.
2026-05-18 20:43:02 +02:00
Guillem Arias
7b4cee60aa docs(beta-gating): document main-nav dot marker via beta: local
The nav-item partial already supports a `beta: true` local that overlays
the DS::Pill dot on the icon, but the gating guide didn't show how to
wire a gated nav entry through it. Add a short "Gating the main nav"
section with the compact-array pattern, and mention the flag in the GA
removal checklist.
2026-05-18 20:37:46 +02:00
Guillem Arias
f7adcac2eb fix(DS::Pill): readable contrast in light mode + drop pill from Goal detail
- Bind CSS `color-scheme` to Sure's `data-theme` attribute so the pill's
  `light-dark()` resolves to the side that matches the active theme. In
  the dark theme it was previously falling back to the light branch.
- Darken light-mode pill text 30% with black on top of the 700 stop so
  the 10–11px uppercase label reads against the violet-50 background.
- Drop the Beta pill from the Goal detail page header. A single goal is
  not the feature; the pill belongs on the feature index, not on each
  record.
2026-05-18 20:27:35 +02:00
Guillem Arias
3479904387 feat(goals): add Beta dot marker on sidebar nav rail
Pass beta: true on gated nav items so the nav_item partial renders a
violet dot-only pill in the top-right of the icon. The doc covers the
dot_only usage; the nav itself was never wired up before merge.
2026-05-18 20:21:23 +02:00
Guillem Arias
5c7babc44e feat(goals): gate Goals v2 behind beta features toggle
Add require_beta_features! to GoalsController and GoalPledgesController,
hide the Goals nav item for non-beta users, and tag index/show headers
with the Beta pill marker. Update controller tests to enable the
preference in setup and assert the redirect for users without access.
2026-05-18 20:13:44 +02:00
Guillem Arias
ac23521c0a Merge remote-tracking branch 'origin/main' into feat/goals-v2-architecture 2026-05-18 20:09:48 +02:00
Guillem Arias Fauste
5249842c76 feat: beta features toggle + Beta pill primitive (#1829)
* feat: beta features toggle + Beta pill primitive

Adds the infrastructure for self-service beta opt-in. No call sites yet:
this PR is meant to land first so feature PRs (Goals, etc.) can ship
behind the gate incrementally.

User opts in via a single toggle at the bottom of Settings → Preferences.
The flag persists in the existing `users.preferences` JSONB column under
`beta_features_enabled` — same shape as `dashboard_two_column` and
`show_split_grouped`, so no migration is needed.

Controllers gate a beta feature by adding `before_action
:require_beta_features!` from the new `BetaGateable` concern (included in
ApplicationController). Views use the `beta_features_enabled?` helper to
hide / show nav items, banners, etc. Logged-out callers always return
false.

Ships `DS::BetaPill`, a small inline marker for tagging features as
Beta / Canary in nav, headers, and lists. Five tones (violet by default,
indigo, fuchsia, amber, gray) map to existing Sure color tokens — no raw
hex. Three styles (soft / filled / outline) and two sizes (sm / md) cover
the surfaces in the design handoff. The `dot_only:` mode renders just
the colored dot for use on a collapsed sidebar.

* review: rename to DS::Pill, fix CR/Codex nits, add tests

CodeRabbit + Codex review feedback:

- Rename DS::BetaPill → DS::Pill. The component was already generic in
  shape (tones, styles, sizes); the name was misleading scope. "Beta"
  becomes the default label (still i18n-driven). Goals' StatusPill can
  later refactor onto this primitive without a third pill.
- Localize the default pill label via i18n (`ds.pill.default_label`)
  instead of hard-coding English.
- Add role="img" to the dot-only span so the aria-label is consistently
  exposed to assistive tech.
- Wrap the Preferences toggle row in <label for="…"> so the title and
  description become an honest click target for the toggle (matches the
  cursor-pointer affordance).
- Drop arbitrary Tailwind values (py-[3px], gap-[5px], tracking-[…]) in
  favor of scale tokens. text-[10/11px] stays because the pill is
  intentionally sub-12px (Sure's smallest scale token is text-xs / 12px)
  to read as a marker, not a label.
- Add User#beta_features_enabled? predicate tests covering default-off,
  explicit-true, and non-boolean truthy values.

Won't fix:
- Palette refs (`--color-violet-*` etc.). Sure has no semantic Beta/
  Canary tokens; introducing them in this PR would be a design-system
  change beyond the scope. The component centralizes palette use in one
  `palette` method, matching the existing pattern in
  Goals::StatusPillComponent.

* review: consistent title fallback in full-pill branch

* docs: how to gate a feature behind the beta toggle

* docs: unwrap doc lines to match existing style

* chore(preview): run Cloudflare PR previews on basic instances (#1831)

* fix(preview): use Rails health endpoint for container ping (#1823)

* fix(preview): use Rails health endpoint for container ping

* fix(preview): point container ping to localhost/up

---------

Co-authored-by: Sure Admin (bot) <sure-admin@splashblot.com>
2026-05-18 20:07:55 +02:00
Sure Admin (bot)
b73da38f49 fix(pwa): serve manifest for html accept headers (#1828)
* fix(pwa): serve manifest for html accept headers

* style: add trailing newline to pwa controller
2026-05-18 19:10:01 +02:00
Sure Admin (bot)
4fd460d551 Add Actual Budget CSV import flow (#1830)
* Add Actual Budget CSV import flow

* Address Actual import review feedback
2026-05-18 18:38:53 +02:00
Guillem Arias
87817213be ux(goals): fix "0 of N · N reached" KPI weirdness
When every active goal already hit its target, the "Goals on track"
tile read "0 of 2 · 2 reached" — logically correct but emotionally
upside-down. Reached goals aren't being tracked toward pace anymore;
they belong in the trophy column, not in the fraction.

- New `tracked_total` excludes reached and paused goals from the
  denominator. Paused stops the pace clock on purpose; reached has
  already cleared it.
- When `tracked_total` hits zero and at least one goal is reached, the
  tile swaps to a celebratory empty state ("All caught up · N reached")
  instead of trying to render a fraction with no denominator.
- Drop "reached" from the subline when the fraction is calculable. The
  fraction is a needle, "N reached" is a trophy — surfacing them
  together muddied the message. Reached only appears in the all-caught-
  up empty state from here on.

Active-first / reached-last grid order already drops out of the
existing ACTIVE_STATUS_RANK sort (reached defaults to the lowest rank
so it naturally lands after behind / on_track / no_target_date /
paused).
2026-05-18 15:52:14 +02:00
Sure Admin (bot)
c54bbaf03a fix(preview): run preview container in development (#1821) 2026-05-17 21:35:15 +02:00
Sure Admin (bot)
4c7d3638fd fix(preview): delete stale container app before redeploy (#1820) 2026-05-17 20:24:45 +02:00
Sure Admin (bot)
34ec12b448 fix(preview): replace PR preview cleanly on redeploy (#1819) 2026-05-17 19:59:46 +02:00
Guillem Arias Fauste
7ddf946647 Merge branch 'main' into feat/goals-v2-architecture
Signed-off-by: Guillem Arias Fauste <accounts@gariasf.com>
2026-05-17 17:08:53 +02:00
Juan José Mata
ceb8e6261a Skip to alpha.9 2026-05-17 17:05:06 +02:00
Guillem Arias
a4927a3fb8 Merge remote-tracking branch 'origin/feat/goals-v2-architecture' into feat/goals-v2-architecture 2026-05-17 16:57:31 +02:00
Sure Admin (bot)
70fc52769d Add super_admin debug event log (#1816)
* Add super-admin debug event log

* Address debug log review feedback

* Whitelist debug filter params

* Make debug log retention configurable
2026-05-17 16:55:01 +02:00
Guillem Arias
89bae8a59b fix(goals): jjmata review — reconciler guard, chart i18n, pace test
Three issues raised on PR #1798 review:

- ProviderImportAdapter now memoizes account.goal_accounts.exists?
  per-account so a bulk historical import on an unlinked account
  short-circuits the reconciler instead of paying one SELECT per row.
  Linked accounts still hit the per-row reconciler with no change.
- goal_projection_chart_controller.js reads Today / Projected /
  Saved labels via Stimulus values fed from
  goals.show.projection.* locale keys instead of inlining English.
- goal_test.rb now covers Goal#pace with real inflows, asserting
  the 90-day window cutoff plus the Transaction.excluding_pending
  and entries.excluded = false filters.
2026-05-17 16:54:13 +02:00
Guillem Arias
2872f3798e Merge remote-tracking branch 'origin/main' into feat/goals-v2-architecture
# Conflicts:
#	app/views/categories/_form.html.erb
2026-05-17 16:21:42 +02:00
Sure Admin (bot)
2df10ca4ef Retry Enable Banking sync with provider-corrected date range (#1801)
* Clamp Enable Banking sync window

* Pipelock noise

---------

Co-authored-by: KiloClaw <kiloclaw@openclaw.ai>
Co-authored-by: Juan José Mata <jjmata@jjmata.com>
2026-05-17 12:09:51 +02:00
Juan José Mata
eb92890a9b Update publish.yml
Stop tagging `stable` as `latest` also

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
2026-05-17 11:12:23 +02:00
Sure Admin (bot)
cc2465b7a7 chore(ci): upgrade GitHub Actions to Node 24-compatible versions (#1810) 2026-05-17 11:06:18 +02:00
Brendon Scheiber
0c126b1674 feat(i18n): extract hardcoded English strings to locale files (#1806)
* Extract hardcoded strings to i18n

Replace numerous hardcoded English strings with I18n lookups (t / I18n.t) across controllers, views, helpers, and components, and convert model validation error messages to symbol keys. Added multiple locale files under config/locales for models and views. This centralizes user-facing notices/alerts, UI text, import/validation messages, and prepares the app for localization and easier translation maintenance.

* Update en.yml

* Update preview-cleanup.yml

* Revert "Update preview-cleanup.yml"

This reverts commit 1ba6d3c34c.

* test: align i18n assertions with translated messages

* Standardize balance error key and tweak locales

Replace SophtronAccount's :requires_balance error key with :no_balance and update related locale strings for sophtron, plaid, and simplefin accounts to use the new key and clearer copy. Also switch the QIF upload redirect notice to use a relative translation key (t('.qif_uploaded')), remove an unused SSO providers help line, and fix a trailing-newline/whitespace issue in the subscriptions locale. These changes standardize validation keys and improve translation consistency and messaging.

---------

Co-authored-by: KiloClaw <kiloclaw@openclaw.ai>
2026-05-17 09:52:49 +02:00
Sure Admin (bot)
d74b1b2a11 fix(preview): use worker list metadata for cleanup (#1799)
* fix(preview): use worker list metadata for cleanup

* fix(preview): handle cleanup edge cases

* fix(preview): harden scheduled cleanup errors

* feat(preview): add warmup screen and readiness gate

* fix(preview): report success after image deploy

* fix(preview): stop blocking healthy previews on stale status
2026-05-16 15:26:30 +02:00
Juan José Mata
3e953377a2 Pipelock noise 2026-05-15 21:25:59 +00:00
Juan José Mata
4f6c39ae38 Merge main 2026-05-15 21:23:58 +00:00
Juan José Mata
6a765a90c6 chore: GitHub workflow to auto-deploy PRs to Cloudflare (#880)
* feat: add Cloudflare Containers PR preview deployments

Add GitHub workflows to automatically deploy PRs to Cloudflare
Containers after tests pass, with automatic cleanup after 24 hours.

Components:
- workers/preview/: Cloudflare Worker entry point that routes
  traffic to the Rails container
- preview-deploy.yml: Deploys PRs after CI passes, comments
  preview URL on PR
- preview-cleanup.yml: Cleans up previews on PR close or after
  24 hours via scheduled job

The container sleeps after 30 minutes of inactivity and wakes
automatically on the next request.

Required secrets:
- CLOUDFLARE_API_TOKEN
- CLOUDFLARE_ACCOUNT_ID
- CLOUDFLARE_WORKERS_SUBDOMAIN

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: use development environment with embedded PostgreSQL for previews

- Add preview-specific Dockerfile with PostgreSQL server included
- Add docker-entrypoint.sh to start PostgreSQL and run migrations
- Change RAILS_ENV from production to development
- Auto-generate SECRET_KEY_BASE and DATABASE_URL for self-contained previews

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* feat: add Redis to preview container

- Install redis-server in the preview Dockerfile
- Start Redis in the entrypoint before PostgreSQL
- Auto-configure REDIS_URL for Sidekiq background jobs

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: mark GitHub deployment inactive on manual PR cleanup

When using workflow_dispatch with a specific pr_number, the workflow
now also marks the associated GitHub deployment as inactive, mirroring
the behavior of the batch cleanup path.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: remove npm cache config that requires missing lockfile

The setup-node action's cache feature requires a package-lock.json
which doesn't exist in workers/preview/. Remove the cache configuration
to fix the workflow.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: only update deployment status when deployment ID exists

Add condition to check steps.deployment.outputs.result exists before
attempting to update deployment status. This prevents a JavaScript
syntax error when the deployment step fails and no ID is available.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: quote shell variables to fix SC2086 shellcheck warning

Quote the --var argument and GITHUB_OUTPUT redirection to prevent
word splitting issues.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: add permissions for deployment status operations

Add deployments: write permission to the cleanup workflow so the
GITHUB_TOKEN can list and update deployment statuses.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: specify build context for Dockerfile in wrangler config

Use object syntax for image config to set build context to repository
root, allowing the Dockerfile to reference files from both the root
(Gemfile, .ruby-version) and workers/preview/ (docker-entrypoint.sh).

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: run wrangler from repo root for correct build context

- Update workflow to run wrangler with --config flag from repo root
- Update wrangler.toml paths (main, image) to be relative to repo root
- Embed entrypoint script directly in Dockerfile using heredoc
- Remove separate docker-entrypoint.sh file

This ensures the Docker build context includes Gemfile, .ruby-version,
and other files at the repo root.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: move preview Dockerfile to repo root for correct build context

Wrangler resolves paths relative to the config file, not the current
directory. Moving Dockerfile.preview to repo root ensures:
- Build context is the repo root (where Gemfile, .ruby-version are)
- Path in wrangler.toml is ../../Dockerfile.preview (relative to config)
- Worker runs from workers/preview/ directory again

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: use find to locate pg_hba.conf instead of glob in redirection

Shell glob patterns don't work with redirection operators. Use find
to locate the actual pg_hba.conf path before writing to it.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: enable workers_dev for preview deployments

Add workers_dev = true to make the preview worker accessible via
the workers.dev subdomain.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* feat: enable observability for container logs

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix preview container boot path

* fix: set preview container startup command explicitly

* fix: update preview worker compatibility date

* chore: expose preview container diagnostics

* fix: recover from stale preview container state

* fix: harden preview container startup paths

* chore: report preview startup stages

* fix: bypass stale container helper state during recovery

* fix: allow longer preview container startup

* fix: upgrade preview container runtime

* fix: use supported node version for preview deploy

* fix: use public container startup flow

* fix: simplify preview container startup

* chore: retain preview container diagnostic history

* fix: bypass systemctl redirect for postgres startup

* chore: probe rails readiness from inside preview container

* chore: capture rails process and port diagnostics

* chore: capture rails startup logs on preview timeout

* fix: align preview bind behavior with ipv6 startup model

* chore: capture preview socket state on rails timeout

* chore: capture rails wait state and child processes

* fix: launch preview with puma directly

* fix: run preview in production mode

* chore: probe preview app boot before puma

* fix: disable lookbook routes in production preview

* chore: capture ruby backtrace from hung boot probe

* fix: disable bootsnap in preview runtime

* fix: disable sidekiq web routes in production preview

* chore: trace hung preview boot probe with strace

* fix: json-escape preview telemetry payloads

* fix: pass preview telemetry env vars correctly

* chore: signal ruby child for preview boot backtrace

* fix: allow longer preview cold-start budget

* fix: skip sidekiq web requires in production preview

* chore: deploy hello world preview container

* fix(preview): restore rails image without redundant warmup

* feat(preview): seed demo dataset on boot

* ci(preview): require preview-cf label

* ci(preview): reuse pr workflow checks

* fix(preview): avoid clearing demo data in production boot

* fix(preview): tolerate already-running postgres on boot

* fix(preview): check demo user via psql during boot

* fix(preview): defer heavy demo seed until after boot

* fix(preview): move demo-user creation after rails boot

* fix(preview): fail fast on container lifecycle errors

* fix(preview): validate manual cleanup pr input

* fix(preview): parameterize preview pr number

* ci(preview): use setup-node v6

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: KiloClaw <kiloclaw@openclaw.ai>
2026-05-15 23:14:20 +02:00
Juan José Mata
495d8a223d Bump failed 2026-05-15 14:57:40 +02:00
Juan José Mata
fccc53efd0 Use GITHUB_TOKEN for bump release checkout
Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
2026-05-15 14:55:18 +02:00
Guillem Arias
314113e582 ux(goals): redesign show page — one CTA, calm banners
Header collapses to title + kebab. The status pill and the `Record pledge`
button leave the title row. Status moves into a one-line callout below the
subtitle that doubles as the catch-up demand when behind, the
reach-date when on track, or a prompt for a target date when missing.

`Record pledge` is now the only pledge entry point on the page and lives
under the ring. Behind goals pre-fill it with the catch-up delta.

The standalone catch-up alert card is gone — its title is the callout, its
pace breakdown moves into the projection chart's subtitle, and its CTA
is the ring-adjacent button. The "Adjust target instead" link is
absorbed into the kebab's existing Edit item.

Pending-pledge banner switches from a warning Alert to a neutral
container chip. It is informational state, not a warning. Title carries
the relative pledged-at meta inline; verbose auto-confirms body stays
but in subdued size.

Projection chart drops the today-line pending stub (vertical line +
dashed marker + "+ pending $X" text). That data already lives in the
pending banner above the chart; the duplicate annotation clutters the
today line, the small dashed circle reads as misaligned at small pending
amounts, and the label overlaps the projection trajectory. Shortfall
label gets a paint-order halo so it stays legible across the dashed
projection line.
2026-05-15 14:11:23 +02:00
Guillem Arias
33189c2673 ux(goals): polish detail page + unbreak render
- Fix render-blocker: Money#symbol doesn't exist (use #currency.symbol).
- Sanitize projection_summary so the _html locale renders <strong> markup
  instead of escaping it.
- Switch donut + card ring track to --budget-unused-fill;
  --budget-unallocated-fill resolves to the same gray as bg-surface in
  light mode so the unfilled arc was invisible on the detail page.
- Mobile detail: drop avatar, right-align action buttons, stack
  projection header (subtitle + legend) so the subtitle reads on one
  line; bump legend gap on mobile.
- Nowrap the projected reach-date so e.g. "Jul 2026" stays together.
2026-05-15 13:25:03 +02:00
Guillem Arias
93da21c938 fix(goals/chart): use optional chain for currency_symbol fallback
Biome lint flagged `(this.dataValue && this.dataValue.x) || fallback`
as `lint/complexity/useOptionalChain`. Same behaviour with
`this.dataValue?.x || fallback`, lint clean.
2026-05-15 07:50:23 +02:00
Guillem Arias
15c5c7783e fix(goals): round-3 review polish on PR #1798
- Demo seed_matched_pledge tie-breaks `entries.date DESC` with
  `entries.id DESC` so dense-same-day inflows pick the same row on
  every reseed
- projection_payload exposes the family-currency symbol via
  Money.new(0, currency).symbol; the chart's `_fmtMoneyShort` / fallback
  now reads it instead of the hardcoded $/€/£ map, so JPY/KRW/CHF
  goals get the correct glyph
2026-05-15 07:41:23 +02:00
Guillem Arias
d6a12614a7 fix(goals): address second AI review round on PR #1798
- Parse "YYYY-MM-DD" date-only strings as local midnight in the
  projection chart so users west of UTC stop seeing the today marker
  and hover dates land one calendar day back
- Order the demo-generator depository pickup by (created_at, id) so
  primary/secondary roles stay stable across reseeds and the state
  matrix (behind / on_track / reached / no_target_date / past-due)
  surfaces the same goals every time
- Drop the brittle " · "-split on goals.goal_card.days_left in
  Goal#header_summary (the translation has no separator suffix)
- Goal#projection_payload ships pre-formatted strings for the static
  chart annotations (target_amount_label / short, projection_end_label,
  projection_shortfall_label, pending_pledge_label_short) and the
  controller now renders those instead of running Intl.NumberFormat on
  each draw. Y-axis tick labels stay JS-side because they depend on
  D3's dynamically-chosen tick values.
2026-05-15 00:16:54 +02:00
Guillem Arias
9f29185160 fix(goals): address AI review on PR #1798 (CodeRabbit + Codex)
Correctness:
- GoalPledge#matches? rejects outflows on transfer pledges so a +$200
  purchase no longer satisfies a $200 deposit pledge after .abs
- GoalsController#sync_linked_accounts! saves through the goal so
  currency/depository/family validations actually run on update
- AlreadyClaimedError replaces empty RecordInvalid in resolve_with! and
  reconciler rescues the dedicated class
- SweepExpiredGoalPledgesJob wraps each expire! in a per-record rescue
- Assistant::Function::CreateGoal disambiguates duplicate account names
  and returns an absolute URL via mailer host config
- Family#savings_inflow_velocity defensively scopes from the family's
  accounts (was Account.joins(:goal_accounts).where(goal_id: ...))
- GoalPledgesController#set_goal preloads linked_accounts + providers
  to drop the N+1 on any_connected_account?
- Stepper subtitle update walks to the enclosing dialog before
  querySelector so two stepper instances don't fight over one header
- categories/_form.html.erb data-action targets color-icon-picker, not
  the non-existent "category" controller

UX / visual:
- Projection chart drops preserveAspectRatio="none" and pins endDate at
  today for past-due goals so the today marker stays in-domain
- _color_picker / categories form swap non-standard border-1 for border
- Goals index search input uses ring-alpha-black-100 (was raw gray-500)

Refactors:
- Goal#header_summary extracts the multi-line ERB header block
- Goal#catch_up_delta_money sums open_pledges in SQL
- Goal#projection_summary uses I18n.l for the on-track month label
- Account#default_pledge_kind moves the manual/transfer decision out of
  GoalPledgesController
- GoalPledge::Reconciler iterates ordered (created_at, id) so first-claim
  wins is deterministic under non-sequential PKs
- Goals::FundingAccountsBreakdownComponent + Goals::AccountStackComponent
  use clamp(0..) instead of Float::INFINITY / [x, 0].max
- Goals::StatusPillComponent#label provides a titleize fallback
- Goal projection chart skips the redundant initial _draw and reuses
  the snapped point in the past branch (no double-bisect)
- Goal pledge preview drops maximumFractionDigits: 0 so USD/EUR show
  cents while JPY/KRW stay whole-unit
- Demo generator captures the Wedding fund goal in the seed loop
  instead of looking it up by hardcoded name

Tests:
- GoalPledgeTest: outflow rejection
- GoalsControllerTest: cross-currency attachment rejected on update
- SweepExpiredGoalPledgesJobTest: cancelled coverage + per-record rescue
- GoalTest: pledge_action_label_key flips to manual_save without an
  unconditional guard
2026-05-15 00:01:13 +02:00
Guillem Arias
95262c1b6a fix(goals/index): completed goals join the chip-filterable grid
Completed goals previously lived in a dedicated section below the
active grid that was always visible regardless of which chip the
user selected. They were the only state without chip filter
representation.

Fold completed into the main grid in controller-side order:
active goals first (sorted by status rank), completed after
(alphabetical). Drop the separate "Completed" section. The
`data-goal-status="completed"` on each card (from
`Goal#display_status`) makes them filter naturally when the new
`completed` chip is selected.

Archived stays in its own collapsed-by-default `<details>` section
below — the visual-hide-by-default is the point there and a chip
wouldn't preserve that.

`@active_goals` keeps its meaning (active-only) for the KPI strip,
the pending-pledges callout, and the search-visibility check
needs `@grid_goals` so search shows up at six combined cards.

Section heading: "Ongoing" → "Goals". The heading now covers the
combined active + completed list, and "Ongoing" misrepresented
what's below it.
2026-05-14 23:10:51 +02:00
Guillem Arias
ec385d023c docs(goals): add llm-guide reference for the goals feature
Captures the architecture, key files, data model, status semantics,
pledge match policy, connected-vs-manual account detection, color
map convention, common tasks, and known gotchas. Matches the
existing llm-guides pattern (architecture diagram + file inventory
+ task-oriented sections + reproducible commands).

The doc is forward-looking: it covers how to add a new field to
Goal, a new status branch, a new pledge kind, and how to safely
touch the reconciler. The "Gotchas" section catalogues the
known-incomplete-but-shipping items so a future audit doesn't
re-derive them from scratch.

Demo data regeneration command is included for anyone who needs
to refresh the seed.
2026-05-14 23:07:10 +02:00
Guillem Arias
ad101f619a fix(goals): test pledge new across both turbo-frame and full-page paths
CI failure on the prior commit: `GoalPledgesControllerTest#
test_new_renders_the_pledge_form` expected 200 but got a 302 to
the goal show page. The recently-added non-frame guard on
`GoalPledgesController#new` redirects direct GETs (F5, bookmark)
back to the goal so the dialog doesn't render standalone, and the
test wasn't sending the `Turbo-Frame` header that the modal flow
uses in production.

Split the test into the two paths the controller actually serves:

- `new renders the pledge form inside a turbo frame` passes a
  `Turbo-Frame: modal` header and asserts 200 — the real modal
  flow.
- `new redirects to the goal show page on a non-frame GET` asserts
  the 302 to `goal_path(@goal)` — the guard's intended branch.

Together they cover the controller's actual contract.
2026-05-14 22:54:05 +02:00
Guillem Arias
afc67d07ae chore(goals): drop architecture notes from the repo
Pulls the two early design notes out of git tracking. They covered
the V1 ledger-based design and the engineering mechanics that led
to the V2 rewrite. With V2 shipped, the notes have served their
purpose and the design-of-record now lives in the code + this PR.

Files stay on disk locally (added to .git/info/exclude so future
git status doesn't re-surface them as untracked). Anyone who wants
the V1 reference can pull from the source branch where this work
started.
2026-05-14 22:49:46 +02:00
Guillem Arias
d32992769c feat(goals/demo): seed full state-coverage matrix + sample pledges
User asked for demo seed variety so every goal state surfaces on at
least one card. Previous seed only spanned 4 AASM states; the
computed status (:reached / :on_track / :behind / :no_target_date)
and the edge-state copy paths (past-due target_date, open pledge
banner, "Last pledge matched") were absent.

New seed coverage matrix:

  AASM states (column):
    active     → Vacation in Italy, Wedding fund, Emergency fund,
                 House downpayment, Coffee gear, Tax prep buffer
    paused     → Sabbatical
    completed  → Paid-off car
    archived   → Old laptop fund

  Computed status (active goals):
    :behind         → Vacation in Italy, House downpayment, Tax prep buffer
    :on_track-ish   → Wedding fund (12-month timeline + small target)
    :no_target_date → Emergency fund
    :reached        → Coffee gear (target 150 below any plausible
                      account balance — progress hits 100% live)

  Edge surfaces:
    Past-due active     → Tax prep buffer (target_date 2.months.ago,
                          exercises "was due" header copy and the
                          months_remaining = 0 branch in
                          monthly_target_amount)
    Open pledge banner  → Vacation in Italy + House downpayment each
                          ship a single open pledge. The show-page
                          banner renders; the index pending-pledges
                          callout renders because @any_pending_pledge
                          flips true.
    Matched pledge      → Wedding fund: after the main seed loop,
                          find_by(name: "Wedding fund") + locate the
                          most recent non-claimed primary-account
                          inflow Transaction (>= 30 days, amount < 0
                          per Sure's sign convention), create a
                          matched-status pledge against it, stamp
                          the Transaction's extra->goal->pledge_id
                          per the partial-unique-index invariant.
                          The show-header then renders "Last pledge
                          matched N days ago" via
                          Goal#last_matched_pledge_at.

Implementation notes:

- Pledges spec embeds inside each goal_spec as an optional `pledges:`
  array. The loop creates them after goal.save! using the goal's
  linked_accounts as the default account; the GoalPledge#
  account_must_be_linked_to_goal validation passes because every
  spec's account is one of the goal's linked accounts.

- The matched-pledge seed is split into a dedicated helper
  (`seed_matched_pledge_demo_for_wedding!`) because it depends on
  Transactions seeded earlier in the demo flow. Both no-Wedding-
  goal and no-recent-inflow guards bail cleanly so older demo
  variants still work.

- All seed targets are intentional. Goal#status reads the live
  linked-account balance + 90-day inflow at render time, so the
  demo statuses adapt to whatever the rest of the demo seeded.
  The targets are sized so the *intended* status is the most
  likely one for typical demo data.

Local DB unaffected: this is the demo-family generator only, run
via `Demo::Generator.new.generate_default_data!` against a fresh
family.
2026-05-14 22:39:23 +02:00
Guillem Arias
82f3d2e0fb fix(goals/show): move Edit into kebab, match house style
User clarification on the "too big edit icon" finding: the header
Edit button itself (not its icon) is what felt wrong. Investigation
showed the wider Sure pattern.

Every other "Edit" affordance in Sure lives inside a DS::Menu kebab:

  - app/views/categories/_category.html.erb
  - app/views/rules/_rule.html.erb
  - app/views/family_merchants/_family_merchant.html.erb
  - app/views/chats/_chat_nav.html.erb
  - app/views/accounts/show/_menu.html.erb
  - app/views/transactions/show.html.erb

Header rows reserve top-level buttons for primary actions (e.g.
"New transaction", "Record pledge"). The goal show page was the
outlier — Edit as an outline button next to Record pledge, which
left two competing CTAs in the header.

Move `menu.with_item(text: t(".edit"), icon: "pencil", ...)` to
the top of the kebab list. Header now has a single primary CTA
(Record pledge, demoted to outline when status is :behind) + the
kebab. Matches every other Sure resource page; eliminates the
"button-too-big" framing entirely without resorting to ad-hoc
icon-size overrides (the `[&>svg]:w-4 [&>svg]:h-4` arbitrary
selector hack would have been a one-off, nobody else uses it).

Avatar pen toggle on the new-goal color picker stays reverted to
its original w-6 h-6 + border-2 form, per the user.
2026-05-14 22:35:02 +02:00
Guillem Arias
f182da79c8 fix(goals): unified per-goal account color map + smaller pen toggle
User flagged two regressions: account colors didn't match between the
goal preview-card avatar stack on the index and the funding-widget
rows on the show page, and the color-picker pen toggle on the new-goal
modal still felt too big.

Color matching:

- `AccountStackComponent` (index card) used
  `Goals::AvatarComponent.color_for(account.name)` — MD5-of-name into
  the 10-color palette.
- `FundingAccountsBreakdownComponent` (show page) recently switched to
  `color_for(account.id.to_s)` — MD5-of-id.
- Same account, two surfaces, two different palette picks. Plus
  either hashing scheme can collide within a multi-account goal
  (palette has 10 colors).

Move ownership to the Goal model: `Goal#account_color_map` returns
`{ account_id => palette_hex }` for the goal's linked accounts. Sort
by `id` for a stable order across reloads, then assign
`palette[i % palette.size]`. Stable + collision-free up to 10
accounts in a single goal (a realistic upper bound — most goals
link 1-3).

Both consumers now read off the same source:

- `AccountStackComponent.new(accounts:, color_map:)` accepts a hash
  and falls back to the name-hash if no map provided (kept for
  callers that don't have a goal in scope yet).
- `FundingAccountsBreakdownComponent#color_for` reads
  `goal.account_color_map[account.id]`.
- Goal card on index passes `goal.account_color_map` to the stack.

Pen toggle:

The new-goal color-picker pen sat in a `w-5 h-5` circle with a
`border` ring + `text-secondary` icon. The border + secondary text
weight kept it loud against the avatar even at 20px. Drop the
border, drop the size another step (`w-4 h-4`), recolor the icon
`text-subdued` + `hover:text-secondary` so the affordance recedes
when not interacted with. Position shifts from `-bottom-1 -right-1`
(8px overhang) to `-bottom-0.5 -right-0.5` (2px overhang) since the
smaller circle doesn't need the larger float. Icon swaps "pen" for
"pencil" (the more conventional edit indicator across Sure).
2026-05-14 22:30:26 +02:00
Guillem Arias
263ccbf5cc fix(goals): scale up card/widget/chart text, fix chart continuity, ease ring focal point
Five small audit follow-ups bundled because they were each one-line
swaps and individually wouldn't earn their own commit.

Card text scale (vs Sure house style — budget_category h3 ≈ text-base,
budget _actuals_summary value text-xl, account row text-sm subtype):
- goal card title text-sm → text-base
- goal card balance text-lg → text-xl
- goal card pace/footer/subtitle text-[11px] → text-xs
- funding row subtype subtitle text-xs → text-sm
- funding row "last 30d / last 90d" labels text-[10px] → text-xs

Chart label scale (projection chart was an outlier at font-size: 10
while time_series_chart_controller uses 12):
- every `font-size: 10` in goal_projection_chart_controller.js → 12
- tooltip cssText font-size: 11 → 12

Color-picker pen toggle on the new-goal avatar was w-6 h-6 (24px
circle, ~55% of the lg 44px avatar). Shrink to w-5 h-5 + add a w-3 h-3
class on the inner icon so it scales down with it.

Graph continuity bug: the saved-line endpoint and the projection-line
start point could disagree by tens of $thousands. Saved came from
`Balance::ChartSeriesBuilder` (daily snapshot in `balances`),
projection started at `currentAmount = goal.current_balance.to_f`
(live `linked_accounts.sum(:balance)`). When the snapshot lagged
the live read, the chart showed a vertical gap at the "today" marker.

Filter any same-day-or-later points out of the raw saved series,
always extend the saved series to `(today, currentAmount)`. Saved
line now closes at exactly the projection's start. The recent
balance-drop story is still honestly shown (the line dips toward
the live value rather than ending at the stale snapshot).

Ring card focal-point (RUI audit): the left ring card on goals#show
sat at the same `shadow-border-xs` elevation as the projection chart
and funding card. "When every card is raised, nothing's primary."
Drop the shadow + container background — the ring now reads as a
status panel sitting on the page surface, not a content card
competing with its neighbours. Paused/archived/celebration/empty
right-slot variants keep elevation since they ARE content cards.

Deferred: light-mode pink distribution-bar contrast. The fix needs
a DS token decision (hairline outline vs darker step on the palette
entries); rolling it into a polish PR risks dragging in DS changes
unrelated to goals. Logged for a follow-up.
2026-05-14 22:26:53 +02:00