Commit Graph

1005 Commits

Author SHA1 Message Date
Víctor Falcón 679c8d7bff
feat: expand Sankey subcategories inline (#485)
## What

Clicking a parent category in the cashflow **Money Flow** Sankey now
expands its children inline as an extra column branching off the parent
— expenses grow to the right, income to the left — instead of swapping
the whole chart for a drilled-in view.

<img width="782" height="392" alt="image"
src="https://github.com/user-attachments/assets/6ce7d925-19d2-4744-a5da-6884a9583a4d"
/>

## Behaviour

- Toggle: click a parent to expand, click again to collapse. Multiple
parents can be open at once.
- One level deep (a child with its own children is not further
expandable).
- The parent stays as an intermediate node and its flow splits into the
children + a node for transactions booked directly on the parent
(labelled **Parent**).
- Changing the period resets expansions.

## Implementation

- `sankey-chart.tsx`: dynamic column layout (was fixed 3-column); lazily
fetches children via the existing `/api/cashflow/sankey?parent=`
endpoint and caches them; label + amount now render in a `foreignObject`
so flexbox handles spacing, vertical centering, and CSS-ellipsis
truncation (full name kept in a `title`); expand affordance is a
`ChevronsRight` icon.
- Child nodes use the same `MIN_NODE_HEIGHT` and gap as top-level nodes,
centered on the parent so links fan out cleanly.
- Removed the old drill-replace + breadcrumb flow (and the now-unused
`sankeyParent` hook option).
- Backend: the direct-transactions node is renamed from `"<name>
(direct)"` to `"Parent"` (+ `es` translation).
2026-06-04 10:31:40 +02:00
Víctor Falcón e3cbbb2e0d
ci: make deploy webhook curl robust and observable (#484)
## Problem

The deploy step intermittently fails on CI with only:

```
Response:
HTTP Status: 000
Deployment request failed with status 000
```

`000` means curl never completed a connection — the Coolify box (which
rebuilds the image from git on deploy) has its API unreachable while a
prior build runs. But the step gave no way to confirm that: `-s`
silenced curl's error message and `|| true` swallowed the exit code.

## Changes

- **Surface the real cause** — `-sS` plus `--write-out
%{exitcode}`/`%{errormsg}`/timing, so failures print the curl exit code
(7 refused, 28 timeout, …) and message instead of a blind `000`.
- **Robust parsing** — body/metadata split on an explicit
`===CURL_META===` marker instead of fragile `tail`/`sed` line counting.
- **No false timeouts** — `--max-time` raised 120→300s so a
slow-but-alive box doesn't abort mid-trigger and report a phantom `000`.
- **Wider retry window** — 10 attempts with backoff capped at 60s (~8
min) instead of 5 with a 240s dead sleep, to ride out a multi-minute
rebuild.
- **Fail fast on 4xx** — a bad token/uuid is not retryable, so don't
waste the window on it.

## Note

This makes the trigger robust and observable; the structural fix (let
Coolify pull the prebuilt ghcr image instead of rebuilding on the box)
is out of scope here.
2026-06-04 08:46:18 +02:00
Víctor Falcón 1cc10566a3
feat: parent/child category tree (#474)
## Summary

Adds nested categories (parent → child, up to **3 levels**) across the
app. Children inherit their parent's type and cashflow direction, and
every category selector now renders the hierarchy as an indented tree.
Gated behind the `CategoryTree` Pennant flag (off by default).

## Backend

- **Migration**: nullable self-referencing `parent_id`; uniqueness
scoped per-parent via a `parent_unique_marker` virtual column (root
names stay unique). New composite unique created before dropping the old
one so the `user_id` FK keeps a supporting index.
- **`CategoryTree` service**: descendant/ancestor resolution, depth &
cycle checks, type cascade, subtree deletion.
- **Validation**: depth limit, cycle prevention, inherited + locked
child type.
- **Delete strategies**: reparent (default), promote to root, or cascade
(uncategorizes affected transactions).
- **Transaction filter** expands a selected parent to its descendants.
- **Cashflow Sankey & breakdown** roll up to top-level parents with
click-to-drill (children + a parent "direct" node).
- **Budgets** tracking a parent also count their children's
transactions.
- **Unified** the frontend category query behind
`Category::forDisplay()` / `FRONTEND_COLUMNS` (8 call sites) so every
selector receives the full Category shape, including `parent_id`.

## Frontend

- New `category-tree.ts` helpers (build/flatten/descendants/path,
tree-aware selection toggle + tri-state).
- **Settings page**: indented tree, sortable by name/color/type
(siblings sorted, hierarchy preserved), parent picker, delete-strategy
dialog.
- **Combobox** (transaction table cell + edit/create modal + parent
picker): indented tree, search keeps matches with their ancestors.
- **Transaction filter**: indented tree, tri-state cascading selection
(parent ↔ children), themed checkboxes, selected branches float to top
on open, ancestor-aware search.
- **Categorizer palette** and **budget multi-select**: same indented
tree + ancestor-aware search.
- **Sankey**: click a parent node to drill into its children, with
breadcrumb.
- Pennant `CategoryTree` flag gates the parent UI.

## Tests

- Pest: model/validation, delete strategies, filter expansion, cashflow
rollup/drill, budget child inclusion.
- Vitest: tree-aware selection logic.
- All green; Pint / ESLint / Prettier clean.

## Rollout

Flag is off by default — enable per user with:
\`\`\`
php artisan feature:enable "App\\Features\\CategoryTree" you@example.com
\`\`\`
2026-06-03 19:30:12 +02:00
Víctor Falcón faccbc3c5a
refactor(js): use InputError for inline form errors (#483)
## What

15 hand-rolled `{errors.x && <p className="text-sm
text-red-500">...</p>}` blocks across 6 components (label/category
create+edit dialogs, automation-rule form, rule builder) replaced with
the existing `InputError` component.

Bonus: `InputError` uses `text-red-600 dark:text-red-400` — the inline
copies had **no dark-mode variant** (CLAUDE.md requires dark-mode
support).

## Stats

- **-63 / +21 lines**

## Checks

- `bun run test` — 154 passed
- `bun run lint` / `format` — clean (1 pre-existing warning)
- `tsc --noEmit` — 59 pre-existing errors, none new

Part of duplication-removal series (#475–#482).
2026-06-03 19:01:21 +02:00
Víctor Falcón d27905ec3d
refactor(requests): share account detail validation rules (#481)
## What

Real-estate detail rule block (~10 fields) was duplicated in **4
requests**; loan detail block in **2**. Variants differ only by
`sometimes` on `property_type` and presence of `revaluation_percentage`.

New `ValidatesAccountDetailRules` trait:

- `realEstateDetailRules(propertyTypeSometimes:, withRevaluation:)`
- `loanDetailRules()`

## Stats

- **-115 / +83 lines**; one source of truth for these field rules

## Checks

- `php artisan test --filter="Account|RealEstate|Loan"` — 355 passed
(1744 assertions)
- `vendor/bin/pint --dirty` — pass

Part of duplication-removal series (#475–#480).
2026-06-03 19:01:03 +02:00
Víctor Falcón 4028e5dfa3
refactor(js): use shared formatMonthFromYearMonth in dashboard (#482)
## What

`use-dashboard-data.ts` had a private `formatMonth()` duplicating
`utils/date.ts` `formatMonthFromYearMonth()`.

Removed the local copy; dashboard now uses the shared util.

**Tiny visual change:** non-current-year labels on dashboard net-worth
chart render `Jan '26` instead of `Jan 26` — now consistent with
cashflow-trend and account-balance charts which already use the shared
util.

## Stats

- **-14 / +2 lines**

## Checks

- `bun run test` — 154 passed
- `bun run lint` — clean (1 pre-existing warning)

Part of duplication-removal series (#475–#481).
2026-06-03 19:00:46 +02:00
Víctor Falcón 7784f0d4fb
refactor(banks): add Bank::availableForUser scope (#480)
## What

The "public banks + user's own banks" query was repeated in **5
controllers** (Transaction ×2, Settings/Bank, Budget, Cashflow,
Onboarding).

New `Bank::availableForUser($user)` scope; all 5 sites use it.

Bonus: the Onboarding variant had no `where()` grouping around
`whereNull/orWhere` — harmless today (no other constraints) but a latent
precedence bug. The scope always groups.

## Stats

- **-31 / +24 lines**, 5 call sites → 1 definition

## Checks

- `php artisan test
--filter="Bank|Transaction|Budget|Cashflow|Onboarding"` — 612 passed
(2707 assertions), 1 skipped
- `vendor/bin/pint --dirty` — pass

Part of duplication-removal series (#475–#479).
2026-06-03 17:59:24 +02:00
Víctor Falcón fe5e22bcfe
refactor(policies): extract HandlesUserOwnership trait (#478)
## What

`CategoryPolicy`, `LabelPolicy`, `TransactionPolicy`,
`AutomationRulePolicy` were structurally identical: `update`/`delete`
check `$user->id === $model->user_id`, everything else returns `false`.
`AccountPolicy` same + ownership `view`.

New `app/Policies/Concerns/HandlesUserOwnership` trait; the 5 policies
now use it (Account keeps its `view` override).

`BudgetPolicy` and `RealEstateDetailPolicy` untouched — different
semantics (all-allowed / ownership via parent account).

## Stats

- **-252 / +112 lines**

## Checks

- `php artisan test
--filter="Categor|Label|Transaction|AutomationRule|Account|Polic"` — 607
passed (2887 assertions), 1 skipped
- `vendor/bin/pint --dirty` — pass

Part of duplication-removal series (#475, #476, #477).
2026-06-03 17:43:30 +02:00
Víctor Falcón fe692e37c3
refactor(requests): share category cashflow direction resolution (#479)
## What

`StoreCategoryRequest` and `UpdateCategoryRequest` had identical 24-line
`prepareForValidation()` deriving `cashflow_direction` from category
type.

Moved to `app/Http/Requests/Concerns/ResolvesCategoryCashflowDirection`
trait.

## Stats

- **-48 / +43 lines** (net small, removes a whole duplicated logic block
that must stay in sync)

## Checks

- `php artisan test --filter=Categor` — 104 passed (565 assertions)
- `vendor/bin/pint --dirty` — pass

Part of duplication-removal series (#475–#478).
2026-06-03 17:39:40 +02:00
Víctor Falcón cc63a86a1c
refactor(requests): extract user-owned exists rules to trait (#477)
## What

The `Rule::exists('x', 'id')->where(fn => user_id)` ownership closure
was repeated **19×** across 10 Form Requests (categories, labels,
accounts, typed accounts).

New `app/Http/Requests/Concerns/ValidatesUserOwnedResources` trait:

- `$this->userOwned('categories' | 'labels' | 'accounts')`
- `$this->userOwnedAccountOfType(AccountType::Loan | RealEstate)`

`UpdateAutomationRuleRequest` intentionally untouched — #476 makes it
extend Store.

## Stats

- **-110 / +63 lines**

## Checks

- `php artisan test
--filter="Transaction|Budget|Account|AutomationRule|RealEstate|Loan"` —
641 passed (3052 assertions), 1 skipped
- `vendor/bin/pint --dirty` — pass

Part of duplication-removal series (#475, #476).
2026-06-03 17:33:54 +02:00
Víctor Falcón 65acab4512
refactor(requests): dedupe UpdateAutomationRuleRequest (#476)
## What

`UpdateAutomationRuleRequest` was **byte-identical** to
`StoreAutomationRuleRequest` (verified with `diff`): same `rules()`,
`passedValidation()`, `withValidator()`.

Now it simply extends the Store request.

## Stats

- **-74 / +1 lines**

## Checks

- `php artisan test --filter=AutomationRule` — 63 passed (211
assertions)
- `vendor/bin/pint --dirty` — applied

Part of duplication-removal series (#475 was first).
2026-06-03 17:29:23 +02:00
Víctor Falcón aa3b811027
refactor(js): extract shared getCsrfToken util (#475)
## What

Same XSRF-TOKEN cookie-parsing snippet was duplicated inline in **12
files** (some as local `getCsrfToken()` copies, some inline
`decodeURIComponent(...)` blocks).

Extracted to single util: `resources/js/lib/csrf.ts`, with vitest
coverage.

## Why

Part of duplication-removal series — PRs that mostly delete code.

## Stats

- App code: **-89 / +23 lines**
- 12 files now import one shared util
- New: `lib/csrf.ts` (8 lines) + `lib/csrf.test.ts`

## Checks

- `bun run test` — 154 pass (3 new)
- `bun run lint` — clean (1 pre-existing warning in chart.tsx)
- `bun run format` — applied
- `tsc --noEmit` — 59 pre-existing errors on main, same 59 on branch
(none introduced)
2026-06-03 17:26:09 +02:00
Víctor Falcón e178f1b1bd
feat(settings): let users disable bank transactions email (#472)
## Summary

Adds a **Notifications** section to the account settings page
(`/settings/account`, between Profile information and Update password)
where users can opt out of the daily "new transactions synced" email.

- New per-user preference `notify_on_bank_transactions_synced` on
`user_settings` (defaults to `true`, opt-out).
- `SendDailyBankTransactionsSyncedEmailJob` skips users who disabled it.
- Single generic `PATCH /settings/notifications` endpoint updates any
notification type via a key→column allowlist in
`NotificationPreferenceController::PREFERENCES`. Future notifications
only need a new entry there — no new route/controller.
- Email footer now links back to the settings section so users can
manage preferences.

## Testing

- `tests/Feature/Settings/NotificationPreferenceTest.php` — update,
unknown-key rejection, invalid value, auth, create-when-missing,
default-true, inertia prop.
- `tests/Feature/OpenBanking/SyncBankingConnectionJobTest.php` — email
not sent when disabled.
2026-06-02 12:24:39 +02:00
Víctor Falcón e5b493329a
feat(currencies): add Colombian and Dominican peso (#471)
## Summary

Adds **COP** (Colombian Peso) and **DOP** (Dominican Peso) to the
supported currency list for both accounts and user primary currency.

## Compatibility

Both are supported by the conversion API (fawazahmed0 currency-api):
- 1 USD = 3686.83 COP
- 1 USD = 58.74 DOP

No migration needed — `currency_code` columns are plain strings and
validation reads the whitelist from `config/currencies.php`.

## Changes

- `config/currencies.php` — add COP + DOP (primary + account)
- `resources/js/utils/currency.ts` — add `RD$` symbol for DOP
- `tests/Feature/Settings/AccountTest.php` — acceptance tests for both

## Testing

`php artisan test --filter="Colombian|Dominican"` → passing
2026-06-01 18:14:16 +02:00
Víctor Falcón f9d1303d98
feat(importer): support YYYYMMDD date format (#470)
## Summary
Adds a compact `YYYYMMDD` (no separators) date format to the
transactions and balance importers.

- New `DateFormat.YearMonthDayCompact = 'YYYYMMDD'` enum value
- `parseDate` parses the 8-digit form (`20241231` → `2024-12-31`)
- `autoDetectDateFormat` recognizes it (unambiguous, no separators)
- Both mapping UIs (transactions + balances) expose it as a selectable
option

## Testing
- `bunx vitest run resources/js/lib/file-parser.test.ts` — 34 passed
- Added tests: compact auto-detection + compact conversion
- `bun run format`, `bun run lint` clean
2026-06-01 16:44:46 +02:00
Víctor Falcón d68fee6c2d
fix(sentry): only report errors in production (#467)
## What

Gate Sentry error reporting on the production environment so nothing is
sent from local, staging, or testing.

- **Backend** (`config/sentry.php`): DSN resolves to `null` unless
`APP_ENV=production`. A null DSN disables the Laravel SDK entirely.
- **Frontend** (`resources/js/app.tsx`): `enabled` now requires
`import.meta.env.MODE === 'production'` (plus a DSN).
2026-06-01 12:41:31 +02:00
Víctor Falcón e3d77ce933
chore: release v0.2.4 (#468)
Patch release `v0.2.4`. Bumps version + updates CHANGELOG via
release-it.

Tag `v0.2.4` + GitHub Release created after merge (tag must point at the
merged commit).
2026-06-01 12:40:29 +02:00
Víctor Falcón 71dd6e2b7f
feat(budgets): track multiple categories and labels per budget (#466)
## Summary

Budgets previously tracked a single category **or** label (mutually
exclusive). This lets a budget span **multiple** categories and labels
at once, all pooling spend against one allocated amount per period.

Scope decided with the requester:
- **Shared pool** — one allocated amount; any tracked category/label
counts against it.
- **Multi categories + multi labels** on a single budget.
- **Create-only** — tracking is chosen at creation and locked afterward
(edit dialog shows it read-only).

## Changes

**Backend**
- New `budget_category` + `budget_label` pivot tables; data migration
copies existing `category_id`/`label_id` into them, then drops those
columns.
- `Budget` model: `categories()` / `labels()` belongsToMany.
- `BudgetTransactionService` matches transactions across **all** tracked
categories OR labels (live assignment + historical backfill).
- `StoreBudgetRequest` accepts `category_ids` / `label_ids` arrays,
requires ≥1 across both, validates ownership. `update` no longer touches
tracking.

**Frontend**
- Reusable `MultiSelect` (popover + command + badge).
- Create dialog uses multi-selects; cards and show page render tracked
categories/labels as badges; edit dialog shows them read-only.
- Dexie bumped to v10 (drops unused per-category allocations table, adds
`budget_labels`).

## Testing
- Updated all budget/transaction/listener/browser tests for the pivot
model; added cases for multi-category matching, mixed category+label
pooling, and store validation (empty selection + foreign-ownership).
- Added the new `__()` strings to `lang/es.json`.
- Local `pint`, `lint`, `format` pass. Relying on CI for the full suite.
2026-06-01 12:32:23 +02:00
Víctor Falcón 5ce439f463
feat(cashflow): rework summary cards into net + saved/invested (#465)
## What

Reworks the two top summary cards on the **Cashflow** page so they no
longer both show net flow.

### Net Cashflow (card 1)
- Shows the net amount **and** its share of income (%).
- Compares **both** the amount and the percentage with the previous
period.

### Saved & Invested (card 2, replaces "Savings Rate")
- Headline = money moved to savings + investment categories (amount).
- Percentage = that total as a share of **net cashflow** (income −
expenses).
- Compares amount and percentage vs. the previous period.
- Keeps the per-category Saved / Invested breakdown at the bottom.
- Adds a **click-triggered help popover** (shadcn `Popover`, works on
touch + desktop, dismisses on outside click / Escape) explaining the
numbers come from transactions using a **"saving"** or **"investment"**
category type.

### i18n
- The card's "Saved" label uses a dedicated key so it renders
**"Ahorrado"** on the cashflow card while form buttons keep
**"Guardado"**. A minimal `lang/en.json` keeps the English label as
"Saved".
- Spanish strings added for the new card + popover copy.

## Testing
- `vitest` — net-cashflow + saved-invested card specs (amount/percentage
comparisons, click-to-reveal popover)
- Full `pest` suite (excl. Browser) — green; localization key-coverage
test passes
- `pint --test`, `prettier --check`, `eslint` — clean
- production `bun run build` — succeeds
2026-06-01 11:37:28 +02:00
Víctor Falcón 26cf79d88b
chore: install laravel/pao dev dependency (#464)
Installs `laravel/pao` as a dev dependency via `composer require
laravel/pao --dev`.

## Changes
- Add `laravel/pao ^1.1` to `require-dev`
- Update `composer.lock`

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-06-01 10:01:38 +02:00
Víctor Falcón 448bb2e64a
feat(posthog): route analytics through reverse proxy (#463)
## What

Route PostHog through the managed reverse proxy at `t.whisper.money` to
dodge ad blockers and keep analytics first-party.

We use the **JS library method** (`posthog-js` in
`resources/js/lib/posthog.ts`), so only that init needed changes — no
snippet.

## Changes
- `api_host` default → `https://t.whisper.money` (proxy domain)
- Add `ui_host` (default `https://eu.posthog.com`) so dashboard links
resolve back to PostHog correctly
- Both stay env-overridable: `VITE_POSTHOG_HOST`, new
`VITE_POSTHOG_UI_HOST`
- Update `.env.example`

## Test
- `posthog.test.ts` passes
- format + lint clean (one pre-existing unrelated warning)
2026-06-01 09:29:30 +02:00
Víctor Falcón 96ee311299
fix(register): don't block signup on unrecognized browser timezone (#462)
## Problem

Some users reported they couldn't register: they filled the form
correctly, pressed the button, saw a loading spinner, then got bounced
back to the registration page with **no error message**. Meanwhile 20-30
users register fine every day, and the issue wasn't reproducible by the
team.

## Root cause

The register form sends a **hidden, browser-auto-detected `timezone`**
field (`Intl.DateTimeFormat().resolvedOptions().timeZone`). The backend
validated it with Laravel's `timezone` rule:

```php
'timezone' => ['nullable', 'string', 'timezone'],
```

That rule rejects **legacy IANA aliases** that many browsers/OSes still
emit — e.g. `Asia/Calcutta`, `Asia/Saigon`, `Asia/Rangoon`,
`US/Pacific`. Proof on PHP 8.4:

```
in_array("Asia/Calcutta", DateTimeZone::listIdentifiers())  →  false
```

When validation failed, Fortify redirected back with a `timezone` error
— but the form had **no error display** for timezone (every other field
has one). Result: spinner → silent bounce → no message → and the user
can't fix a hidden field anyway. The team couldn't reproduce because
their browsers send canonical zones that pass. Production tzdata may
reject even more zones.

## Fix

- Stop validating the auto-detected hidden field against the strict
timezone list.
- Add `normalizeTimezone()`: keep recognized zones (including BC aliases
via `DateTimeZone::ALL_WITH_BC`), drop anything unrecognized to `null`.
Registration can never be blocked by it again.
- Surface `errors.timezone` in the form as a safety net so a
hidden-field failure can never be silent in the future.

## Tests

- Legacy alias `Asia/Calcutta` → registers, stored as-is.
- Unrecognized zone → registers, stored `null`.
- All existing registration tests pass (13 passed).
2026-06-01 09:03:15 +02:00
Víctor Falcón a71626a350
feat(currency): add Saudi Riyal (SAR) (#461)
## What

Adds Saudi Riyal (SAR) as a supported currency for both user primary
currency and account currency.

## Why

SAR is fully supported by the `@fawazahmed0/currency-api` conversion
backend (verified rates are returned), so it works end-to-end with the
existing conversion system.

## Changes

- `config/currencies.php`: add SAR with `allows_primary: true`,
`allows_account: true`
- Tests mirroring the BRL cases in `AccountTest` and `ProfileUpdateTest`

## Testing

- `php artisan test` on both settings test files — 32 passed
- `vendor/bin/pint --dirty` — clean
2026-06-01 08:52:21 +02:00
Víctor Falcón f9bf0ea5ff
feat(discord): enrich Stripe event messages and dedupe deliveries (#460)
## Why

The Stripe subscription events posted to the Discord admin feed weren't
useful (only status + raw `cus_123` id) and sometimes arrived duplicated
— including two cancellation messages for the same subscription.

## What changed

**Richer messages** (`PostStripeEventToDiscord`)
- Customer name + email (resolved via the Stripe API), plan + interval
(`€19.99 / month`), status, subscription id.
- A `Changed` field built from Stripe's `previous_attributes` diff (e.g.
`Status: trialing → active`).
- Cancellation reason, trial-end and period-end dates where relevant.
- Invoices now show invoice number + subscription id.

**Deduplication (two causes fixed)**
- *Webhook/queue retries*: guard on the Stripe event id via
`Cache::add(..., 24h)` — first delivery wins, retries skipped.
- *Double cancellation*: Stripe fires `subscription.updated` (cancel
scheduled) **then** `subscription.deleted`. We now label the scheduled
one `🗓️ Cancellation scheduled` distinctly from `👋 Subscription
cancelled`, and only post `subscription.updated` when something
meaningful changed (status, plan, or cancellation), dropping trivial
churn.

**New** `StripeCustomerResolver` service — resolves `Name (email)` from
a customer id, falls back to the id on any error. Injectable so it's
stubbed in tests (no network).

## Tests

9 cases covering rich fields, dedup, scheduled-vs-deleted cancellation,
status-change diff, trivial-update skip, deletion reason, and invoice
amounts. All passing.

Note: this adds one Stripe API call per subscription/invoice event, made
inside the queued listener (no webhook latency).
2026-05-31 12:50:37 +02:00
Víctor Falcón 85ea3cc714
feat(accounts): show 50 transactions per page and link to full list (#459)
## What

- Bump the account page transaction list page size from **10 → 50**
(`Accounts/Show.tsx`).
- Add a **View in Transactions** button next to *Load more* (only on the
account page) that opens the Transactions page pre-filtered to the
current account via `account_ids`.
- Add Spanish translation `View in Transactions` → `Ver en
Transacciones`.

## Notes

- The account list is synced client-side (IndexedDB); `pageSize`
controls how many rows render before *Load more*, so no backend change
needed.
- The Transactions index already defaults to `per_page = 50` and reads
`account_ids` from the query string.

## Testing

- `vitest` Accounts/Show tests pass.
- `bun run format`, `bun run lint`, `bun run build` pass.
2026-05-30 18:48:21 +02:00
Víctor Falcón 0b528b7902
feat: add Discord admin feed for daily stats and Stripe events (#458)
## What

Adds a private Discord admin feed with two flows, both posting through
one webhook (`DISCORD_WEBHOOK_URL`):

### 1. Daily stats — `stats:daily-report`
Scheduled **09:00 Europe/Madrid**. Posts an embed with:
- New users created **yesterday** (Madrid calendar day, converted to UTC
for the query)
- Total users
- Active/trialing counts + current & projected **MRR / ARR** per
currency

Reuses the #457 Stripe stats logic, extracted into
`SubscriptionStatsCollector` so the existing `stripe:subscription-stats`
command and this report share one source of truth.

### 2. Stripe events — `PostStripeEventToDiscord`
Queued listener on Cashier's `WebhookReceived`. Posts on:
- `customer.subscription.created` / `updated` / `deleted`
- `invoice.payment_succeeded` / `payment_failed`

## Setup
- `DISCORD_WEBHOOK_URL` — added to prod  (set locally to test)
- Stripe dashboard must send the 5 event types above to the existing
Cashier `/stripe/webhook` endpoint
- A queue worker must be running (listener is `ShouldQueue`)

## Tests
13 passing: Discord client (3), daily report (2), Stripe event listener
(4), plus the existing stats command (4) still green after the refactor.
2026-05-30 18:14:46 +02:00
Víctor Falcón 670a0a65c7
feat: add Stripe subscription stats command (#457)
## What

Adds a `stripe:subscription-stats` Artisan command that prints
subscription stats to the CLI.

Shows, per currency:
- **Active subs** count + their MRR
- **Trialing subs** count + their MRR
- **Current MRR & ARR** (active subscriptions only)
- **Projected MRR & ARR** (if trialing subs convert to active)

## How

- Queries Stripe directly via `Cashier::stripe()`, auto-paginating
`active` and `trialing` subscriptions.
- MRR per subscription sums all items, normalizing each price to a
monthly value (handles day/week/month/year intervals, `interval_count`,
and quantity).
- Groups results per currency (EUR, BRL, …) since aggregating across
currencies would be incorrect.

```bash
php artisan stripe:subscription-stats
```

## Tests

4 Pest feature tests covering empty state, MRR/ARR math, per-currency
grouping, and quantity handling. Mocks the Stripe client.
2026-05-30 17:37:17 +02:00
Víctor Falcón 144d919c0b
fix(import): correct balance for same-day, zero and negative values (#456)
## Problem

CSV imports only carry a date (no timestamp). Rows are newest-on-top and
we import top-to-bottom. Three balance bugs:

1. **Same-day balance wrong.** The store loop did `Map.set(date,
balance)` per row, so when a day had 2+ transactions the **last**
(bottom = oldest) row overwrote the newest. The correct daily balance is
the **first** (newest) row.
2. **Zero balance dropped.** The parser guard `row[mapping.balance]`
treated numeric `0` as falsy, so a real `0` balance became `null`. `0`
is valid.
3. **Negative balance lost its sign.** `parseAmount` stripped `-` via
`replace(/[^\d]/g,'')`, so negative balances (and amounts) came out
positive.

## Fix

- `import-transactions-drawer.tsx`: keep the **first** occurrence per
date (`!balancesToImport.has(date)`).
- `file-parser.ts`: guard balance on null/undefined/empty-string only,
so `0` is kept.
- `file-parser.ts`: `parseAmount` now detects a leading `-` (or `(...)`)
and applies the sign — fixes negative balances and negative amounts.

## Tests

Added 4 cases to `file-parser.test.ts`: zero (number), zero (string),
negative, empty→null. Full suite: **144 passed**.

> Note: the same-day "keep first" logic lives in the React component and
relies on `newTransactions` staying in CSV order (top = newest), which
holds in current code.
2026-05-30 16:19:27 +02:00
Víctor Falcón 65175e184a
fix(accounts): translate update button in edit account modal (#455)
## Problem
Update button in edit account modal showed hardcoded English (`Update` /
`Updating...`) instead of translated text.

## Fix
Wrap button label in `__()` so it resolves the existing `es.json` keys
(`Actualizar` / `Actualizando...`).

## Test
`edit-account-dialog.test.tsx` passes.
2026-05-30 16:09:30 +02:00
Víctor Falcón 05ee8dc442
feat(categorize): show debtor and creditor names (#454)
## What
Show the debtor and creditor names (when present) on the categorization
page (`/transactions/categorize`).

## Changes
- `TransactionController@categorize`: select `creditor_name` and
`debtor_name` — they were never sent to the frontend.
- `categorizer-card.tsx`: render Creditor/Debtor rows below the account
when present, using the same i18n labels as the transaction columns.
- `TransactionTest`: assert both names are exposed on the categorize
page.

## Testing
- `php artisan test --filter="debtor and creditor"` — passes.
- pint, format, lint clean.
2026-05-30 12:27:59 +02:00
Víctor Falcón 4dec0ab7ca
feat: add BRL currency support (#453)
## Summary
- Add BRL (Brazilian Real) to supported currency list
(`config/currencies.php`), allowed as both primary and account currency.

## API compatibility
- Verified `@fawazahmed0/currency-api` supports BRL in both directions
(e.g. USD→BRL ≈ 5.05). No conversion changes needed.

## Tests
- Added BRL account-creation test (`AccountTest.php`).
- Added BRL primary-currency test (`ProfileUpdateTest.php`).
- Both pass.
2026-05-29 16:33:21 +02:00
Víctor Falcón cbc2f4f85f
chore: update Discord invite link (#452)
Swap Discord invite link `discord.gg/2WZmDW9QZ8` →
`discord.gg/m8hUhx6D9D` across all files (README, header, user menu,
connections page, welcome email, test).
2026-05-29 15:56:48 +02:00
Víctor Falcón 741dc49d53
fix(logging): keep laravel.log writable across container UIDs (#451)
Fixes the largest production noise cluster — **8 duplicate issues**, all
`UnexpectedValueException: The stream or file
"/app/storage/logs/laravel.log" could not be opened in append mode:
Failed to open stream: Permission denied`:

`PHP-LARAVEL-G`, `PHP-LARAVEL-Z`, `PHP-LARAVEL-12`, `PHP-LARAVEL-2P`,
`PHP-LARAVEL-2Q`, `PHP-LARAVEL-2R`, `PHP-LARAVEL-2S`, `PHP-LARAVEL-2T`.

## Root cause

`docker/entrypoint.sh` runs `migrate` / `config:cache` / etc. **as
root** before supervisor starts. With the default `umask 022`, the first
log line written during boot creates `laravel.log` as `root:root 0644`.
The persisted `whisper-storage` named volume
(`docker-compose.production.yml`) keeps that stale, non-group-writable
file across deploys — so the `www-data` php-fpm and queue workers can't
append to it and every code path that logs throws. 8 code paths → 8
Sentry issues.

## Fix

- **entrypoint**: `umask 0002`, pre-create `laravel.log` group-writable
before any artisan command, and normalize it to `0664` in the
post-artisan re-apply step.
- **config/logging.php**: `permission => 0664` on the `single` and
`daily` channels, so files Laravel creates itself (including daily
rotation) stay group-writable.

Net effect: whoever writes first (root at boot or www-data at runtime),
the file is owned `www-data` and group-writable `0664` — no more
`EACCES`.

## Tests

- `single` and `daily` channels expose `permission => 0664`.
- `bash -n docker/entrypoint.sh` passes.

## Follow-up

Once deployed and confirmed quiet, the 8 issues should be merged into
one canonical group in Sentry.

Fixes PHP-LARAVEL-G, PHP-LARAVEL-Z, PHP-LARAVEL-12, PHP-LARAVEL-2P,
PHP-LARAVEL-2Q, PHP-LARAVEL-2R, PHP-LARAVEL-2S, PHP-LARAVEL-2T.
2026-05-29 15:10:50 +02:00
Víctor Falcón 64b78e3680
fix(banking): handle balance-fetch timeouts and silence handled retries (#450)
Fixes two linked production banking-sync issues.

## PHP-LARAVEL-W — `cURL error 28: timed out` in
`EnableBankingProvider::getBalances` (8 events, 4 users, High)

`getBalances` called `$response->throw()` raw, so a connection timeout
(or ASPSP error) escaped as an **unhandled**
`ConnectionException`/`RequestException` and crashed the sync.
`getTransactions` already wraps these in
`TransientBankingProviderException` (which `implements ShouldntReport`
and is handled as a transient, retryable error in
`SyncBankingConnectionJob`).

→ `getBalances` now follows the exact same pattern. Genuine validation
errors (non-ASPSP 4xx) stay reportable.

## PHP-LARAVEL-2D — `SyncBankingConnectionJob has been attempted too
many times` (High, regressed)

The hanging balance call above pushed the job past its 120s `timeout`,
the worker was killed mid-job, and the retry tripped a
`MaxAttemptsExceededException`. That exception is thrown by the queue
worker (not catchable in `handle()`), and the job's `failed()` handler
**already** records the terminal `Error` state on the connection — so
the Sentry report is redundant operational noise.

→ Fixing W removes the main cause of the timeout. Additionally,
`MaxAttemptsExceededException` is no longer reported **for this job
only** (scoped via `dontReportWhen` on `$e->job?->resolveName()`); other
jobs still report it.

## Tests
- `getBalances` wraps connection failures and ASPSP errors as
non-reportable transient errors; keeps non-ASPSP client errors
reportable.
- `MaxAttemptsExceededException` is not reported for
`SyncBankingConnectionJob`, but still reported for other jobs.

Fixes PHP-LARAVEL-W, PHP-LARAVEL-2D.
2026-05-29 14:58:38 +02:00
Víctor Falcón bef657c2ed
fix(currency): degrade gracefully when rates return 404 (#449)
## Problem

`PHP-LARAVEL-2M` (High, escalating, 38 events) — `RuntimeException:
Failed to fetch currency rates for xxx on 2025-12-31: HTTP 404` crashing
`/dashboard`.

A user holds an account in currency `xxx` (ISO 4217 "no/unknown
currency"). No rate file exists for it, so every candidate URL returns
404. `CurrencyConversionService::fetchRates` threw an unhandled
`RuntimeException` that bubbled past the graceful-degradation logic in
`ExchangeRateService::convert` and broke the whole dashboard render.

## Fix

Distinguish **permanent** 404s from **transient** failures:
- All sources return 404 → log a warning and return `[]`. Callers
already handle empty rates (return unconverted / zero amount).
- Timeouts / 5xx / connection errors → still throw, so real outages stay
visible.

## Tests

- New: unknown base currency with all-404 sources returns `0.0` instead
of throwing.
- Existing "throws when both primary and fallback fail" (500s) still
passes — transient errors still surface.

Fixes PHP-LARAVEL-2M.
2026-05-29 14:44:56 +02:00
Víctor Falcón 5119528149
fix(categories): expose cashflow setting on create (#448)
## Summary
- Always show a simplified Cashflow and charts explanation in the
category form
- Explain how each category type affects cashflow, income/spending
charts, top spending categories, savings, and investments
- For transfer categories, keep a cashflow chart visibility selector so
users can choose hidden/inflow/outflow
- Show savings and investment categories as outflows in the cashflow
chart and store default/new categories as outflow
- Add a new migration to update existing production savings/investment
categories to outflow
- Avoid user-facing Sankey terminology and update Spanish copy to use
dinero/saldo instead of efectivo
- Add missing Spanish translations and browser/feature coverage

## Tests
- php artisan test --compact tests/Feature/LocalizationTest.php
- php artisan test --compact
tests/Feature/Console/ResetUserCategoriesCommandTest.php
- php artisan test --compact tests/Feature/Settings/CategoryTest.php
--filter="migration updates existing default saving and investment
categories|migration sets saving and investment categories to cashflow
outflow|users can create savings and investment categories|default
categories are created when user registers"
- php artisan test --compact tests/Feature/CashflowAnalyticsTest.php
--filter="sankey includes savings and investment categories on the
expense side|sankey includes outflow transfer categories on the expense
side"
- php artisan test --compact tests/Browser/CategoriesTest.php
--filter="explains savings and investment category cashflow impact in
the create dialog|can create a new transfer category with a cashflow
analytics direction"
- php artisan test --compact tests/Browser/CategoriesTest.php
- ./vendor/bin/pest --testsuite=Performance --filter="account show page
does not exceed query threshold"
- vendor/bin/pint --dirty --format agent
- npx prettier --write
resources/js/components/categories/category-cashflow-direction-fields.tsx
- npm run build (assets emitted; Sentry sourcemap upload reports local
SSL error)

## Video
- screenshots/category-create-cashflow-setting.webm

## Notes
- npm run types still fails on existing unrelated TypeScript errors.
2026-05-29 11:05:04 +02:00
Víctor Falcón 0b9406714e
fix: filter Safari cashback extension errors (#447)
## Sentry
- Issue: PHP-LARAVEL-2K
- URL: https://whisper-money.sentry.io/issues/123306290/

## Root cause
Sentry is collecting unhandled errors from a Safari/iOS browser
extension content script. Recent production events all came from
`webkit-masked-url://hidden/`, function `onResponse`, with message
`response.cashbackReminder`, on public app routes. No matching
application code exists.

## Fix
- Add a narrow client-side Sentry `beforeSend` filter for this Safari
cashback extension signature.
- Keep similarly named errors from application bundles.
- Add Vitest regression coverage.

## Verification
- `npx prettier --write resources/js/app.tsx resources/js/lib/sentry.ts
resources/js/lib/sentry.test.ts`
- `npx eslint --fix resources/js/app.tsx resources/js/lib/sentry.ts
resources/js/lib/sentry.test.ts`
- `npm test -- resources/js/lib/sentry.test.ts`
- `npm run types` (fails on existing unrelated TypeScript errors outside
touched files)
2026-05-28 15:10:49 +02:00
Víctor Falcón edb9f1c852
chore: update lead invitation schedule (#446)
## Summary
- increase scheduled lead invitation batch limit from 100 to 150
- keep Spanish translations sorted with new copy keys

## Tests
- vendor/bin/pint --dirty --format agent
- php -r 'json_decode(file_get_contents("lang/es.json"), true, 512,
JSON_THROW_ON_ERROR); echo "lang/es.json ok\n";'
- php artisan schedule:list --no-interaction
- php artisan test --compact
tests/Feature/Commands/SendUserLeadInvitationsTest.php
tests/Feature/Commands/SendUserLeadReInvitationsTest.php
2026-05-28 14:00:16 +02:00
Víctor Falcón cfa61fd23c
feat: add PKR currency support (#443)
## Summary
- Add Pakistani Rupee (PKR) to supported primary and account currencies
- Cover PKR account creation and profile currency selection

## Tests
- vendor/bin/pint --dirty --format agent
- php artisan test --compact tests/Feature/Settings/AccountTest.php
tests/Feature/Settings/ProfileUpdateTest.php
2026-05-28 09:46:09 +02:00
Víctor Falcón 2fa822e6d9
fix(categories): allow recreate after delete (#444)
## Summary
- allow users to recreate category names after soft delete
- update category unique validation to ignore trashed rows
- add active-row unique index for category names

## Tests
- php artisan test --compact tests/Feature/Settings/CategoryTest.php
2026-05-28 09:46:02 +02:00
Víctor Falcón 4f46ae3e2d
fix: move community link to user menu (#442)
## Summary
- Move Community link from sidebar footer into user dropdown above
Feedback.
- Hide empty sidebar footer nav group.
- Add tests for dropdown order and footer removal.

## Tests
- `npm test -- --run resources/js/components/user-menu-content.test.tsx
resources/js/providers/menu-item-provider.test.ts`

Note: `npm run types` currently fails on unrelated existing TypeScript
errors.
2026-05-27 17:39:26 +02:00
Víctor Falcón 10da06ed84
feat(transactions): add counterparty fields (#440)
## Summary
- add creditor/debtor fields to transactions with raw_data backfill
- store counterparties on bank sync and CSV/XLS imports
- add creditor/debtor filters plus hidden table columns

## Tests
- php artisan test --compact tests/Feature/LocalizationTest.php
tests/Feature/OpenBanking/TransactionSyncServiceTest.php
tests/Feature/TransactionFilterTest.php
- npm test -- resources/js/lib/file-parser.test.ts --run
- vendor/bin/pint --dirty --format agent

Note: `npm run types` still has pre-existing unrelated errors; no
creditor/debtor/import-related errors remained in filtered output.

## Screenshot
<img width="1241" height="676" alt="8odYWtFcvUM"
src="https://github.com/user-attachments/assets/55653485-d588-4beb-9e6a-5c7c81ba7cf8"
/>
2026-05-27 16:20:55 +02:00
Víctor Falcón 6caadad1db
fix: net category refunds in cashflow (#441)
## Summary
- net mixed-sign category transactions before cashflow analytics display
- align dashboard, cashflow trend, breakdown, and sankey behavior with
top categories
- add feature tests for refund-style expense netting

## Tests
- php artisan test --compact tests/Feature/CashflowAnalyticsTest.php
tests/Feature/DashboardAnalyticsTest.php
- vendor/bin/pint --dirty --format agent
2026-05-27 15:16:50 +02:00
Víctor Falcón d5d262e9fd
fix(chart): mask stacked bar edges (#439)
## Summary
- mask stacked bar rounded edges with the card background
- clamp bar radius for tiny stacked segments
- add regression tests for shape stroke and radius

## Tests
- npx vitest run resources/js/components/ui/stacked-bar-chart.test.tsx
--reporter=verbose
- npx eslint resources/js/components/ui/stacked-bar-chart.tsx
resources/js/components/ui/stacked-bar-chart.test.tsx
2026-05-26 17:03:06 +02:00
Víctor Falcón 534a14790e
feat(accounts): add transaction action (#438)
## Summary
- add Add transaction action to disconnected transactional account
detail pages
- keep balance actions grouped as Update balance | Import balances |
menu
- center empty data-table messages vertically

## Tests
- php artisan test --compact tests/Feature/LocalizationTest.php
tests/Feature/AccountControllerTest.php
- npm test -- resources/js/pages/Accounts/Show.test.tsx
- npx eslint resources/js/pages/Accounts/Show.tsx
resources/js/pages/Accounts/Show.test.tsx
resources/js/components/ui/data-table.tsx

Note: npm run types still fails due existing unrelated TypeScript
errors.
2026-05-26 15:57:23 +02:00
Víctor Falcón 235911b960
fix(budgets): explain locked edit fields (#437)
## Summary
- add disclaimer for locked period and carry-over budget fields
- cover disclaimer rendering with Vitest

## Tests
- npm run test --
resources/js/components/budgets/edit-budget-dialog.test.tsx
2026-05-26 15:49:53 +02:00
Víctor Falcón 0250fdc268
fix(cashflow): clarify period comparisons (#436)
## Summary
- Remove misleading primary net cashflow trend arrow
- Add previous-period comparisons for income, expenses, saved, and
invested values
- Move savings-rate comparison below the main percentage

## Tests
- npm test --
resources/js/components/cashflow/net-cashflow-card.test.tsx
resources/js/components/cashflow/savings-rate-card.test.tsx
2026-05-26 10:52:01 +02:00
Víctor Falcón 606093d311
fix: batch automation rule application (#435)
## Sentry
- Issue: PHP-LARAVEL-2C
- URL: https://whisper-money.sentry.io/issues/122336983/

## Root cause
Applying an automation rule to multiple transactions used
per-transaction `saveQuietly()` and `syncWithoutDetaching()`. Sentry
detected repeated transaction updates and pivot lookups/inserts on
`/settings/automation-rules/{automationRule}/apply`.

## Fix
- Added batched automation rule application for transaction collections.
- Bulk updates category changes in one query.
- Bulk inserts missing label pivots with `insertOrIgnore`.
- Reused batching from sync controller path and queued job chunks.

## Verification
- `vendor/bin/pint --dirty --format agent`
- `php artisan test --compact
tests/Feature/AutomationRuleApplicationTest.php`
2026-05-26 10:45:37 +02:00
Víctor Falcón d5d22b9d57
feat(leads): schedule invitation emails (#434)
## Summary
- run lead invitation emails daily at 9:00 AM
- run lead re-invitation emails daily at 9:00 AM
- use --force so scheduler runs non-interactively

## Verification
- php artisan schedule:list --no-interaction | rg
"leads:send-(re-)?invitations"
2026-05-26 08:47:28 +02:00
Víctor Falcón 7b03d7cf23
feat(leads): add user lead re-invite campaign (#432)
## Summary
- add re-invite tracking columns for user leads
- add queued re-invitation mailable and command
- default re-invite eligibility to leads invited at least 3 days ago
- localize re-invite email in Spanish for `es` leads
- add stats command output for conversion rate

## Tests
- vendor/bin/pint --dirty --format agent
- vendor/bin/phpstan analyse --memory-limit=2G
- php artisan test --compact
tests/Feature/Commands/SendUserLeadReInvitationsTest.php
tests/Feature/Mail/UserLeadReInvitationTest.php
tests/Feature/Commands/SendUserLeadInvitationsTest.php
tests/Feature/Mail/UserLeadInvitationTest.php
2026-05-26 08:35:31 +02:00